Why does fread always return 0?

I used this code to read a file. But the fread function always returns 0. What is my mistake?

FILE *file = fopen(pathToSourceFile, "rb"); if(file!=NULL) { char aByte[50000]; int ret = fread(aByte, sizeof(aByte), 1, file); if(ret != 0) { not jump into there; fseek(file, 0, SEEK_SET); fwrite(aByte, ret, 1, file); } } fclose(file); 
+4
source share
5 answers

Are you sure your file is larger than 50,000? otherwise you could try:

  fread(aByte,1, sizeof(aByte), file); 
+4
source

ferror() will tell you when something is wrong.

You can print the actual error message using perror() .

+3
source

You cannot fwrite open a file in rb mode.

Your statement that ret always zero is false. If you correctly measured your code, you will not make false statements:

 #include <stdio.h> #include <stdlib.h> int main() { FILE *file = fopen("junk.dat", "rb"); if(file!=NULL) { char aByte[50000]; int ret = fread(aByte, sizeof(aByte), 1, file); fprintf(stderr, "fread returned %d\n", ret); if(ret != 0) { int fs = fseek(file, 0, SEEK_SET); if(fs == -1) { perror("fseek"); exit(1); } fs = fwrite(aByte, ret, 1, file); if(fs != ret) { perror("fwrite"); exit(1); } } } fclose(file); return 0; } 

Productivity:

 fread returned 1 fwrite: Bad file descriptor 

at startup.

+1
source

In case someone else comes across this. I just ran into a similar problem. This is because the 2nd argument to fread must be the size of each element in the buffer . In OP code, this is the size of the pointer to the buffer.

This should work if buff has at least 1 element:

 int ret = fread(aByte, sizeof(aByte[0]), 1, file); 
0
source

You:

#include <unistd.h>

If not, and if you compile without -Wall, the C compiler may erroneously assume that the second argument to fread () is int, not off_t, which could ruin the function call. Your code snippet does not show any #include statements, so please make sure you include everything you use.

-1
source

All Articles