Search code examples
carraysiofilestream

Why does this C code to read/write array of integers from file not work?


I have the following C code:

   int a[5] = {1,2,3,4,5};
   int b[5];
   FILE *fp;
   fp=fopen("test","w");
   fwrite(a,sizeof(a),1,fp);
   fread(b,sizeof(b),1,fp);
   for (int i = 0; i < 5; i++) {
      printf("%d ", b[i]);
   }
   printf("\n");

In this code I create an array a, write it to a file test, then try to read it from the file into b. However, instead of 1, 2, 3, 4, 5, printing b outputs 1, 14, 0, 0, 0.

I tried replacing

   fwrite(a,sizeof(a),1,fp);
   fread(b,sizeof(b),1,fp);

with

fwrite(a,sizeof(int),sizeof(a),fp);
   fread(b,sizeof(int),sizeof(b),fp);

and got the same result.

Does anyone know what I'm doing wrong here?


Solution

  • You have opened the file for writing only, which means that reading will fail. The program prints garbage as the fread call fails so the output locations remain uninitialized. It would be good to check the return value of fread and take appropriate action.

    You can open the file for both reading and writing with the mode r+ or w+ (these are the same, except w+ will truncate the file first).

    Also you probably want binary mode since you are writing raw ints (the default is text mode, when the stream might adjust line endings and make other translations).

    When using + mode, after a write then you are not allowed to read without doing a positioning operation. So the code might be (pseudocode):

    fp=fopen("test","w+b");
    fwrite(a,sizeof(a),1,fp);
    rewind(fp);   // same as seeking to the start
    fread(b,sizeof(b),1,fp);
    

    In Standard C there is only one file position indicator , there are not separate positions for reading and writing. To have separate read and write positions you'd need to manage this yourself with fseek (and open the file in binary mode), or use some operating system facility.