我已经写了一个二进制文件,他有以下功能:
int writeFile(FILE *f_to, void *from, int size){
int write = fwrite(from, 1, size, f_to);
if (write == size)
return 0;
else
return -1; //fails
}
void createDataFile(const char *fname)
{
FILE * out_file;
out_file = fopen(fname, "ab+");
if (out_file == NULL){
std::cout << "error no file to be written" << endl;
}
writeFile(out_file, (INT32U*)&(newPtr->hdr), sizeof(S_MES_HDR));
writeFile(out_file, (INT32U*)&(newPtr->mon_hdr), sizeof(S_MON_HEADER));
writeFile(out_file, (INT32U*)&(newPtr->data_hdr), sizeof(S_MON_DATA_HEADER));
writeFile(out_file, (INT32U*)&(newPtr->data), ((ptr->hdr.id.data_len*sizeof(INT32U)) - sizeof(S_MON_HEADER)-sizeof(S_MON_DATA_HEADER)));
cout<< sizeof(S_MES_HDR)<<endl;
cout<< sizeof(S_MON_HEADER)<<endl;
cout<< sizeof(S_MON_DATA_HEADER)<<endl;
cout<<((ptr->hdr.id.data_len*sizeof(INT32U)) - sizeof(S_MON_HEADER)-sizeof(S_MON_DATA_HEADER))<<endl;
fclose(out_file);
S_TERM_PACKET *monPacketPointer2;
monPacketPointer2 = new S_TERM_PACKET;
out_file = fopen(fname, "ab+");
createMessage(monPacketPointer2, 1, 'R', 6, out_file);
fclose(out_file);
S_TERM_PACKET *monPacketPointer3;
monPacketPointer3 = new S_TERM_PACKET;
out_file = fopen(fname, "ab+");
createMessage(monPacketPointer3, 3, 'M', 3, out_file);
fclose(out_file);
cout << "output file has been created." << endl;
}
int main()
{
createDataFile("test.data");
return 0;
}
我得到了以下输出:http://prntscr.com/43dpsm。我写入test.data文件的总字节数是*(16 + 8 + 4 + 40) 3 = 204字节。
现在,当我使用以下函数读取test.data文件时:
int ReadFile(FILE *f_in, void *dest, int size)
{
int read = fread(dest, 1, size, f_in);
if (read == size){
return 0;
}
return -1;
}
void readData(const char* id, Structure*head)
{
ReadFile(p_file, (INT32U*)&termPacketPointer->hdr, sizeof(S_MES_HDR));
cout << "total read size:" << sizeof(S_MES_HDR)+(termPacketPointer-> hdr.id.data_len)*sizeof(INT32U) << endl;
cout << "data len:" << (termPacketPointer->hdr.id.data_len) << endl;
ReadFile(p_file, (INT32U*)&termPacketPointer->term_data, (termPacketPointer-> hdr.id.data_len)*sizeof(INT32U));
}
int main()
{
// createDataFile("test.data");
File * p_file=fopen("test.data", "rb");
if(p_file==NULL)
return -1;
if (!feof(p_file))
{
readData("25", head);
}
if (!feof(p_file))
{
readData("25", head);
}
if (!feof(p_file))
{
readData("25", head);
}
if (!feof(p_file))
{
readData("25", head);
}
fclose(p_file);
return 0;
}
我最后得到了以下输出和运行时错误。
总阅读尺寸:68 数据len:13
总阅读尺寸:68 数据len:13
总阅读尺寸:68 数据len:13
总读取大小:210756 数据len:52685因此,在读取68 * 3 = 204字节后,它等于我写入文件的字节数,它没有停止并继续读取。我的假设是它没有看到 eof ,但我知道fclose自动将它放入。我怎么能解决我的问题?提前谢谢。
答案 0 :(得分:3)
有一件事可以帮助我实际检查fread()
的返回状态。内部函数执行此操作并返回-1表示错误,但main()
中的调用不检查状态。
在许多实现中,feof()
在尝试读取文件末尾之前不会成立。