Adithya
Adithya

Reputation: 43

fread() weird behavior in C

I have this code that's behaving weirdly when I try setting max via different methods.

#include<stdio.h>
#include<stdlib.h>

int main(int argc,char* argv[])
{
  int max=0;
  FILE* fp=fopen(argv[1],"r");
  FILE* fp1=fopen(argv[2],"w");
  while(fgetc(fp)!=EOF)
    ++max;
  //printf("\n%d\n",max); //933
  char *s=(char*)calloc(max,sizeof(char));
  if(fread(s,sizeof(char),max,fp)==max)
    fwrite(s,sizeof(char),max,fp1);
  else
    fprintf(stderr,"\nError reading file %s\n",argv[1]);
  fclose(fp);
  fclose(fp1);
  return 0;
}

As can be seen from the code,I use a while loop to find the size of the file (in no.of bytes) and set it to max.When fread tries reading the file argv[1] with "this" max it throws up an error i.e,

fread(s,sizeof(char),max,fp)

returns 0.

However,when I initialize max with the known file size (as calculated by the previous method while commenting out the while loop) ,the program produces the expected result.

I have no clue why something like this would happen.Can someone point out where I'm going wrong? Any constructive help would be much appreciated. Thank you.

Upvotes: 1

Views: 136

Answers (1)

SleuthEye
SleuthEye

Reputation: 14579

As implied by @BLUEPIXY in comments, the first sequence of operation which computes max has the side effects of setting the read location to the end of the file.

Thus, any subsequent fread intended to acquired the data fail because there are no more data to be acquired. Resetting the read location to the beginning of the file with:

while(fgetc(fp)!=EOF)
  ++max;
rewind(fp); // <------------------ reset read location to start of file.

// go on to read the data
char *s=(char*)calloc(max,sizeof(char));
if(fread(s,sizeof(char),max,fp)==max)
...

should resolve the problem.

Upvotes: 3

Related Questions