C: Unable to write data on file

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+");

           return false;

#option 1//this is not working 
    #end of option 1

#option 2//this works 
    int fd = fileno(file);
    int x = write(fd,file_data,file_size);//
    #end of option 1


My file data looks like this

  1. 4 bytes are reserved for integers (required).
  2. Reserve 200 bytes for the string (optional).


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.

Related Problems and Solutions