Daniel Marschall
Daniel Marschall

Reputation: 3879

File will not be completely read byte by byte

Using a C program I am writing in Dev-C++, I want to read a binary file byte by byte. For some reason, the read stops at 261 bytes. Here is a simplified code which reproduces the bavior.

int main(int argc, char *argv[])
{
   FILE *in_fp;
   char in_filename[25] = "data.raw";
   in_fp = fopen(in_filename,"r");
   if( in_fp == NULL ) {
      perror("Error while opening the input file.\n");
      system("PAUSE");
      exit(EXIT_FAILURE);
   }

   int readcnt = 0;
   while (1) {
      unsigned char buffer;
      if (fread(&buffer, sizeof(unsigned char), 1, in_fp) == 0) {
         printf("read eof after %d\n", readcnt);
         break;
      } else {
         printf("read = %d\n", buffer);
      }
      readcnt++;
   }


   fclose(in_fp);

   return 0;
}

The file data.raw has a size of 104 KiB.

The output of the program above ends with:

...
read = 255
read = 4
read = 204
read eof after 260

Using an hex-editor, I can find the bytes FF 04 CC , and there should be bytes followed after this, since the file is not at the end: FF 04 CC 1A 1F C5 8A .

I also tried fgetc() and feof() and the behavior is the same.

Why does the reading stops at offset 260?

Upvotes: 1

Views: 147

Answers (1)

cnicutar
cnicutar

Reputation: 182734

You probably need to open your file in "binary mode":

fopen(in_filename, "rb");

Upvotes: 4

Related Questions