c++ - 为什么 fseek 不起作用?

标签 c++ io

我写了一个函数来列出我的文件,它是二进制的,并用我的结构中的 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 ++;
}

它打印一次我的所有文件,但没有退出我的循环。我的函数继续打印文件中的最后数据。我如何退出我的函数并找到文件末尾? fseek 有效吗?

最佳答案

while(!feof(bookFilePtr)) 是执行读取循环的糟糕方法。 !feof(...) 不保证 fread 会成功。您应该在 fread 成功时循环

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

fseek 的调用也是多余的:fread 已经推进了文件游标本身,所以你不需要寻找。

关于c++ - 为什么 fseek 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8543882/

相关文章:

c++ - 类成员函数声明疑问

c++ - 如何修改 C++ 中的 const 引用

ruby - 当 shell 有子进程时,为什么 ruby​​ 的 PTY 库无法捕获输入?

ios - Openssl iOS 缓冲区限制

java - Android 上 Assets 文件夹中的 InputStream 返回空

c++ - 为什么允许从对象到引用的隐式转换?

c++ - 在 C++ 中使用 For 循环查找素数

c++ - printf 与 std::string?

file - 如何从文件中获取随机行?

Golang - 如何克服 bufio 的 Scan() 缓冲区限制?