Reputation: 4585
Why I am getting :
fread() failed
I am running this code in VS 2010
#include<stdio.h>
#include<string.h>
#define SIZE 1
#define NUMELEM 5
int main(void)
{
FILE* fd = NULL;
char buff[100];
memset(buff,0,sizeof(buff));
printf(" Starting to open");
fd = fopen("test","r+");
if(NULL == fd)
{
printf("\n fopen() Error!!!\n");
return 1;
}
printf("\n File opened successfully through fopen()\n");
if(SIZE*NUMELEM != fread(buff,SIZE,NUMELEM,fd))
{
printf("\n fread() failed\n");
return 1;
}
}
Upvotes: 0
Views: 5436
Reputation: 941
What if there are less number of characters stored in the file?
fread()
returns the amount of characters that it has read from the file and in your code, the number of characters read != number of characters in the file.
Upvotes: 1
Reputation: 4002
Don't compare fread() return value with requested size. Some times requested size of data not available in the file.and don't compare with SIZE*NUMELEM,fread always returns number of items read successfully. For more information read manual page of fread()
Upvotes: 1
Reputation:
Because you haven't read the documentation of fread()
. It returns NUMELEM
, and not SIZE * NUMELEM
.
Upvotes: 2