简体   繁体   English

为什么fseek不起作用?

[英]why fseek doesn't work?

I wrote a function that list my file that it's binary and write it with fwrite func from my struct: 我写了一个函数,列出我的文件,它是二进制文件,并用我的struct中的fwrite func编写它:

void ReadFile::printList(){
clearerr(bookFilePtr);
fseek(bookFilePtr,0L,SEEK_SET); // set to begin of file
int counter = 1;
cout << "***************************************************" << endl;
struct book tmp ;
while (!feof(bookFilePtr)){
            fread(bookPtrObj,sizeof(struct book),1,bookFilePtr);   
    cout << bookPtrObj->name << "s1"<< endl;
    cout << bookPtrObj->publisher << "s2"<< endl;
    cout << bookPtrObj->author << "s3" <<endl;
    cout << bookPtrObj->stock << endl;
    cout << bookPtrObj->translation << endl;
    cout << bookPtrObj->trasnlator << "s4" <<endl;
    cout << bookPtrObj->delayDays << endl;
    cout << bookPtrObj->delayPay << endl;
    cout << "***************************************************" << endl;
    fseek(bookFilePtr,counter * sizeof(struct book) ,SEEK_SET); // seek to next data
    counter ++;
}

It prints for once all of my file , but didn't quit from my loop. 它打印一次我的所有文件,但没有退出我的循环。 and my func continue to print last data in file.How i do to quit my func and find out to end of file? 我的func继续打印文件中的最后一个数据。如何退出我的func并找到文件结尾? does fseek work? fseek工作吗?

while(!feof(bookFilePtr)) is a bad way to do a reading loop. while(!feof(bookFilePtr))是一个不好的阅读循环方式。 !feof(...) does not guarantee that fread will succeed. !feof(...)并不保证fread会成功。 You should loop while fread succeeds instead. 你应该fread成功时循环。

while(fread(bookPtrObj, sizeof(struct book), 1, bookFilePtr) == 1) {
    //  blah blah do the things
}

The call to fseek is redundant too: fread already advances the file cursor itself, so you don't need to seek. fseek的调用也是多余的: fread已经提升了文件光标本身,所以你不需要寻找。

while (!feof(f)) does not mean what you think it means. while (!feof(f))并不意味着你认为它意味着什么。 It does not mean 'current position is at end of file', it means 'last read attempted to read past end of file': it's a flag that's set by fread and others, and cleared by fseek and others. 它并不意味着“当前位置在文件末尾”,它意味着“最后一次读取尝试读取文件末尾”:它是由fread和其他人设置的标志,由fseek和其他人清除。 fread has a return value. fread有一个返回值。 That return value indicates whether the read was successful. 该返回值表示读取是否成功。 Use that as your loop condition. 将其用作循环条件。

You're ignoring fseek 's return value as well, which is bad for the same reasons, but that isn't the cause of your problem, at least not directly. 你也忽略了fseek的回报价值,这也是出于同样的原因,但这不是问题的原因,至少不是直接的。

BTW, I'm assuming this is just code to experiment with fseek , but your fseek 's in the loop set the position to where the position should already be, so it adds no value. 顺便说一句,我假设这只是试验fseek代码,但你的循环中的fseek将位置设置到位置应该已经存在的位置,因此它不会增加任何值。

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

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