简体   繁体   中英

fread_s reading the wrong amount of bytes

I am reading a collection file (20 or so small files in one) with fread_s and the content is being written in a struct . Like 99% of the times it reads the data correctly, but one time, at always the same position it seems to ignore the byte size of the element size parameter and just reads 500 or so bytes until it aborts and reports a feof error. The thing is, it doesn't even write the last three bytes of the int to the struct.

When I remove the checks, and let it continue reading, it will read normal again, like nothing happened.

I observed that the _Placeholder variable in the file pointer gets changed to a different value, and then back again, but I guess its just the eof error getting packed in there.

#pragma pack(push, 1)
struct fileHeader {
    __int32 typeID;
    bool isGFX;
    char filename[8];
    __int32 offset;
};
#pragma pack(pop)

#define HEADERSIZE 68
#define FILEHEADERSIZE 17

....
FILE *file;
fopen_s(&file, filename.c_str(), "r");

for (int i = 0; i < header.files - 1; i++) {
    fseek(file, HEADERSIZE + i * FILEHEADERSIZE, 0);

    fileHeader headerFile;
    memset(&headerFile, 0, FILEHEADERSIZE);

    int oldPointer = ftell(file); //118
    int d = fread_s(&headerFile, FILEHEADERSIZE, FILEHEADERSIZE, 1, file); //returns 0
    int newPointer = ftell(file); //630

    int e = errno; //0
    int ea = ferror(file); //0
    int ef = feof(file); //1

    //getting used here in a function
}
headerFile = {typeID=17 isGFX=true filename=0x00fefd05 "CURSORR" offset = 164} - offset should be 6820

Like Jonathan Leffler said in the comments, the mistake was, that I didn't read in binary mode. a simple change fopen_s(&file, filename.c_str(), "r"); to fopen_s(&file, filename.c_str(), "rb"); fixed the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM