简体   繁体   English

fread_s读取错误的字节数

[英]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 . 我正在读取带有fread_s的收集文件(一个中包含20个左右的小文件),并且内容正在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. 就像99%的时间一样,它正确地读取数据,但是一次,在总是相同的位置,它似乎忽略了元素大小参数的字节大小,只是读取500个左右的字节,直到中止并报告feof错误为止。 The thing is, it doesn't even write the last three bytes of the int to the struct. 关键是,它甚至没有将int的最后三个字节写入结构。

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. 我观察到文件指针中的_Placeholder变量被更改为另一个值,然后再次返回,但是我猜想它只是eof错误被打包在那里。

#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. 就像乔纳森·莱夫勒(Jonathan Leffler)在评论中说的那样,错误是我没有以二进制模式阅读。 a simple change fopen_s(&file, filename.c_str(), "r"); 一个简单的更改fopen_s(&file, filename.c_str(), "r"); to fopen_s(&file, filename.c_str(), "rb"); fopen_s(&file, filename.c_str(), "rb"); fixed the problem. 解决了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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