Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are element size and count exchangable in an fread call? [duplicate]

Let's say I have a file with a size of 5000 bytes, which I am trying to read from.

I have this code:

int main()
{
  char *file_path[] = "/path/to/my/file"
  FILE *fp= fopen(file_path,"rb"); //open the file
  fseek(fp, 0, SEEK_END); // seek to end of file
  unsigned long fullsize = ftell(fp); //get the file size (5000 for this example)
  fseek(fp, 0, SEEK_SET); //bring back the stream to the begging  
  char *buf = (char*)malloc(5000);
  fread(buf,5000,1,fp);
  free(buf);
  return 0;
}

I can also replace the fread call with

fread(buf,1000,5,fp);

What is better? And why? In matters of optimization, I understand the return value is different.

like image 361
raptor0102 Avatar asked Dec 30 '25 01:12

raptor0102


1 Answers

If you exchange those two arguments, you still request to read the same number of bytes. However the behaviour is different in other respects:

  • What happens if the file is shorter than that amount
  • The return value

Since you should always be checking the return value of fread, this is important :)

If you use the form result = fread(buf, 1, 5000, fp);, i.e. read 5000 units of size 1, but the file size is only 3000, then what will happen is that those 3000 bytes are placed in your buffer, and 3000 is returned.

In other words you can detect a partial read and still use the partial result.

However if you use result = fread(buf, 5000, 1, fp);, i.e. read 1 unit of size 5000, then the contents of the buffer are indeterminate (i.e. the same status as an uninitialized variable), and the return value is 0.

In both cases, a partial read leaves the file pointer in an indeterminate state, i.e. you will need to fseek before doing any further reads.

Using the latter form (i.e. any size other than 1) is probably best used for when you either want to abort if the full size is not available, or if you're reading a file with fixed-size records.

like image 161
M.M Avatar answered Dec 31 '25 16:12

M.M