D
D
dandropov952018-08-31 11:14:10
C++ / C#
dandropov95, 2018-08-31 11:14:10

How to write a number to a file in binary mode?

int value = 11; // ... ... ... 00001011
In string mode, you can simply use fprintf(fp, "%d", value)it and then the symbolic representation of the number 11 will be written to the file.
And how to write the binary representation of the number to the file, that is, the number itself and not the string.
I only know about methods fread/fwrite, but with the help of them you can only write an array of data.
How do you write a single number to a file?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GrigorySvetov, 2018-08-31
@dandropov95

1. If it is about binary output (that is, when the symbol itself does not carry a semantic load, but carries the symbol number in the encoding) ("real" binary output).
The main joke is that an array in C can be understood as just a pointer to a set of values ​​fixed in size, and the array variable itself can be understood as a pointer to this set.
And indeed, the usual reference to the index arr[i] in C is translated into *(arr+i) (dereferencing by a pointer with an offset).
So when we write fwrite(arr, ...), we are actually writing a POINTER there. Otherwise, C is enough anyway what happens (the main thing is that without access to someone else's memory, otherwise the system will already kill the process here). Those. we pass a pointer to a NUMBER (one number) as if it were a whole array, then we write everything honestly for it. The code turns out like this:

#include <stdio.h>
int main(){
  FILE *fp;       //переменная файлового потока
  int value=11;   //наша переменная с числом
  fp=fopen("output.txt","wb");//открываем файл на перезапись ('w') в бинарном режиме ('b' в "wb")
  if (fp==NULL){            	     //если файл не был открыт, то...
    perror("file hadn't opened");//вывести в поток ошибок сообщение (обычно это то же, что поток вывода (т.е. экран компьюетра)

  } else {                            //иначе..
    fwrite(&value,sizeof(int),1,fp); //вывести значение как массив с единственной ячейкой
  }
  fclose(fp);//закрыть в любом случае (если fp==NULL, ошибкой всё равно не будет, а читается удобнее, чем все эти ветки if'ов
  return 0;
}

2. If about what is in the comment, i.e. with zeros and ones in the file... This is a "fake" binary mode, because each character '0' and '1' are really honest single characters that should be read as text. In this case, I think, you just process this number bit by bit and drive it with fputc() (but fopen() will already be like this: (and not ) fopen("<имя файла в форме строки>", "w");fopen("<имя файла в форме строки", "wb");

R
Radjah, 2018-08-31
@Radjah

codewiki.wikidot.com/c:system-calls:write The
second parameter is a pointer to your int, the third parameter is its size (like 4 bytes or sizeof).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question