4

I am trying to read an empty file with fread. Before i created the file with a blocksize of 4096 and an amount of 40 blocks. At the moment I know that these Blocks are "empty" but if i read the file like in my code below I cannot tell wether it is empty or not. I mean I am expecting nread to be NULL or something like that. Do you know what I have to compare nread with? Thank you!

int test()
{

   char buf[4096];
   FILE *file;
   size_t nread;

   file = fopen("out/abc.store", "r");
   if (file) {
       while ((nread = fread(buf, 1, sizeof buf, file)) > 0)
          fwrite(buf, 1, nread, stdout);
      if (ferror(file)) {
      /*error handling*/
   }
   fclose(file);
}

EDIT:

I created the file like that:

char *content=(char*)malloc(uintBlockSize*uintBlockCount);
memset(content,0,uintBlockSize*uintBlockCount);
...
 while (i!=0)
 {
   check=fwrite(content,uintBlockSize, 1, storeFile);
   if (check!=1)
       return 1;
   i--;
 }
Flexo
  • 87,323
  • 22
  • 191
  • 272
SevenOfNine
  • 630
  • 1
  • 6
  • 25

2 Answers2

1

Check to see if fread returned 0. From the documentation (here):

The total number of elements successfully read is returned.

Jacob Pollack
  • 3,703
  • 1
  • 17
  • 39
-1

fread will return the number of successfully read elements, so in this case, fread will return 0 (assuming it did not read anything), or EOF if it is the end.

phyrrus9
  • 1,441
  • 11
  • 26