Eliad Cohen
Eliad Cohen

Reputation: 368

fread() after fwrite() gets 0 bytes

I am set a big buffer for the FILE* object(size of 8 * 1024) and I'm making a write of 4 bytes to it and then I read of the 4, but the read fail. If I flush the FILE* the read succeeds.

typedef struct _MyFile {                 /* file descriptor */
    unsigned char fileBuf[8*1024];
    FILE *file;
} MyFile;

int main() {
    MyFile myFile;
    int res;
    char bufWrite[4] = { 1, 2, 3, 4 };
    char bufRead[4];

    /* Open file for both reading and writing */
    myFile.file = fopen("myfile.txt", "w");

    /* Change the file internal buffer size */
    setvbuf(myFile.file, myFile.fileBuf, _IOFBF, sizeof(myFile.fileBuf));

    /* Write data to the file */
    res = (int)fwrite(buf, 1, 4, myFile.file);
    printf("write: res = %d\n", res);

    /* Seek to the beginning of the file */
    fseek(fp, SEEK_SET, 0);

    /* Read and display data */
    res = (int)fread(buf, 1, 4, myFile.file);
    printf("read: res = %d\n", res);
    fclose(myFile.file);

    return 0;        
}

The output is:

write: res = 4
read: res = 0

If I write more than 8K or use write() instead of fwrite() the fread() works well.

The thing is I can't use fflush()!!!

Is there any way to fix it?

Upvotes: 2

Views: 1819

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140196

You have opened your file in write-only mode. The handle isn't aware that you want to read on it.

Just open your file in read-write mode:

myFile.file = fopen("myfile.txt" , "w+");

I have tested it and it successfully reads back the data in the read buffer.

write mode only:

write : res = 4
read: res = 0
bufRead: -83 20 82 117

read/write mode:

write : res = 4
read: res = 4
bufRead: 1 2 3 4

Edit: my first attempt use "rw" mode which worked but gave strange write return value result:

write : res = 0
read: res = 4
bufRead: 1 2 3 4

Upvotes: 3

Related Questions