简体   繁体   中英

fwrite/fread doesn't work well in Windows

I wrote a program in that create a structure variable, then write it in a file using the function fwrite . The returned code is 1 (I wrote just one structure variable). When I tried to read the file with fread function it returns 0 and the variable is not filled completely.

This problem is specific for windows only. I tried the same code with Linux (Ubuntu virtual machine) and it worked well.

Here is the structure:

struct MyStruct
{
    char comment[40];
    int nbpts;
    float time[4096];
    float value[4096];
};

FILE* fp = fopen(fileTrace, "w");
fwrite(&var, sizeof(struct MyStruct), 1, fp);


fread(&var, sizeof(struct MyStruct), 1, fp);

Any ideas?

You need to open the file for reading too:

fopen(..., "w+")

And you should open it in binary mode, so fwrite / fread doesn't do any funky character conversions (eg platform specific line-endings for Windows):

fopen(..., "w+b")

If you want to fread directly after a fwrite you have to reset the file pointer position, so that fread starts reading from where you have written your data.

To summarize:

   if ((fp = fopen("var.dat", "w+b")) != NULL) {
      fwrite(&var, sizeof(var), 1, fp);
      rewind(fp);
      memset(&var, 0, sizeof(var)); // reset var
      fread(&var, sizeof(var), 1, fp);
      // ...          
      fclose(fp);
   }

(This examples uses rewind to set the file pointer to the beginning, you might have to use fseek instead)


A word of caution: To be portable, you should not write a struct directly to disk, but actually serialize it (ie manually write out every field to the file, maybe prefixed with a small header), since compiler-specific padding might (or will) cause problems.

int main()
{
    const char *pFIle = "test.txt";
    char var[sizeof(struct MyStruct)] = {0};
    int ret = 0;
    FILE* fp = fopen(pFIle, "w+");
    ret = fwrite(&var, sizeof(struct MyStruct), 1, fp);
    printf("fwrite ret =%d;\r\n", ret);
    fflush(fp);
    fseek(fp, 0, SEEK_SET);
    ret = fread(&var, sizeof(struct MyStruct), 1, fp);
    printf("fread ret =%d;\r\n", ret);
    return 0;
}

I have test, everything is OK on windows. Let me know if you have other problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM