I used the fread function and I am getting a buffer size 4 and a “Reading Error”.
Why is my buffer not the fileSize?
Here is my code:
FILE *fp;
char* buffer;
fp = fopen("help.txt","r");
if (fp == NULL){
fputs("Can't open Help file, Help.txt",stderr);
exit(1);
}
fseek(fp, 0, SEEK_END);
long fileSize = ftell(fp);
rewind(fp);
buffer = (char*) malloc (sizeof(char)*fileSize);
if(buffer == NULL){
fputs("Memory Allocation Error",stderr);
exit(2);
}
size_t result = fread(buffer,1,fileSize,fp);
if(result != fileSize){
fputs("Reading error\n",stderr);
printf("File Size : %lu\n",fileSize);
printf("Result : %lu\n",result);
printf("Buffer Size : %u\n",sizeof(buffer));
exit(3);
}
fputs(buffer,stdout);
fclose(fp);
free (buffer);
This is the output when I run the program:
Reading error
File Size : 224
Result : 219
Buffer Size : 4
The buffer is allocated correctly. The buffer size is calculated uslng
sizeof(char)*fileSize, notsizeof(buffer). You can test if the buffer was allocated or not by verifying ifbufferis null. If it’s not, then it successfully allocated the buffer with the size greater than or equal to the size you requested.The problem is that you opened the file in text mode. Because of that, Windows will replace all the “\r\n” sequences in your file with “\n” as ANSI C requires. You can either accept this behavior or you can open your file in binary mode using
fp = fopen("help.txt","rb");to read all the contents unaltered.