Archived

This topic is now archived and is closed to further replies.

SikCiv

fread return value.

Recommended Posts

SikCiv    122
I use fopen, fread, and fclose to read a file, but I have a problem reading a file that is shorter than what I specify. For example, when I ask it to read 192K; -if the file it bigger than 192K, it reads the data ok. -if the file is smaller than 192K, fread returns 0. Is this normal? Ive looked at the fread function in VCHelp, and it says that it reads what it can, and returns the number of bytes read. How do I overcome this problem? Im guessing I have to get the file size first..correct? If so, how?
    
    
    // open the file.

    fp = fopen( szFileName, "rb");
    if (!fp)
    {
        return SetError(ERR_CANNOTOPENFILE);
    }


    // read the whole struct.

    if( fread(&LevelData, sizeof(LEVELDATA), 1, fp) == 0)
    {
        fclose(fp);
        return SetError(ERR_CANNOTREADFILE);
    }
    
    // Close the file

    fclose(fp); 

    

Share this post


Link to post
Share on other sites
Void    126
The docs are correct and perfectly valid..

In your code, you are trying to read in 1 LEVELDATA object, so assuming your LEVELDATA object is 192K bytes, then if your file has lesser than 192K bytes, no object will be read so the bytes read will be 0.

If you are doing something like this

fread(&LevelData, sizeof(LEVELDATA), 2, fp) // expect to read 2 objects

Then if your file is lesser (192 * 2)K but more than 192K, then 1 object will be read, and fread will return 192K..

You should be using feof and ferror to test for end of file and file error, rather than return value from fread.

Share this post


Link to post
Share on other sites