C: Unable to write data on file … here is a solution to the problem.
C: Unable to write data on file
I want to open
a file and write some data on it, so I have to use (Fopen) “I can’t use open because I need fopen on some other things”
Now if I
want to write on a file using fwrite it just don’t know why this is what I mentioned in code #option1, but if I get the file descriptor and use the normal write method everything works fine, see #option 2 below.
Can anyone help me make fwrite work?
char file_data[256] // has some values
int file_size = strlen(file_data);
FILE *file;
file = fopen(MY_FILE_NAME, "w+");
if(!file){//edited
return false;
}
#option 1//this is not working
fwrite(file_data,1,file_size,file);
#end of option 1
#option 2//this works
int fd = fileno(file);
int x = write(fd,file_data,file_size);//
#end of option 1
Edit
My file data looks like this
- 4 bytes are reserved for integers (required).
- Reserve 200 bytes for the string (optional).
Solution
Buffered IO operations use buffers that are managed by the C library. Your “problem” is that fwrite is buffered, meaning that in order to write a file, you will most likely need to flush it with fflush(),
or just close the file.