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