Answer the question
In order to leave comments, you need to log in
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
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;
}
fopen("<имя файла в форме строки>", "w");
fopen("<имя файла в форме строки", "wb");
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question