tags:

views:

128

answers:

3

I used this code to read file. But fread function always return 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); 
+1  A: 

are you sure that your file has a size greater than 50000 ? else you could try:

 fread(aByte,1, sizeof(aByte),  file);
Pierre
YES because i readed data from a mp3 file that the size on disk is 3.2mb :S
+2  A: 

ferror() will tell when something is wrong.

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

Johnsyweb
`ferror()` won't tell you *what* is wrong, it'll tell you *if* something is wrong - it's just a true/false indication. Using `perror()` if `ferror()` returns true is good advice.
caf
@caf: Thanks. Fixed.
Johnsyweb
+1  A: 

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.

msw
Yes sorry i change to rb to test fread. please skip to fwrite. :)
It is best to cut and paste the code that you are actually having problems with end you can edit your question if your code changes.
msw