You can't fwrite to a file open in rb mode.
Your statement that ret is always zero is false. If you had properly instrumented your code, you'd not be making false claims:
#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; }
Yields:
fread returned 1 fwrite: Bad file descriptor
when run.
freadshould return the number of bytes actually read, which may be less than 50000.freadreturns the number of objects read. If you are reading up to one 50000 byte objects it will return 0 or 1.