文件仅读取1个记录,然后到达文件的末尾,即使还有其他记录

file reads just 1 record and then reaches the end of file even tho there are other records

本文关键字:文件 记录 其他 读取 1个 然后      更新时间:2023-10-16

,所以我被赋予了创建像程序之类的库的任务我被指示对添加的书籍进行不同的操作(添加书籍,删除..)

addbook函数写入书籍对象,每本书的记录都会获取一个endl可行者(这样我稍后可以在使用getline上获取记录)

打印本函数只需将书籍对象带出并打印出

我的问题是当我尝试打印文件中的所有书籍记录(代码编写)时,它只读取第一个记录,显然它立即到达文件末尾。甚至还没有读取文件中的其余记录

我的问题是如何在不读取整个文件的情况下到达文件末尾以及如何解决此问题,以便我可以阅读所有已写入文件中的记录

#include<iostream>
#include<fstream>
#include<strstream>
#include <cstring>
using namespace std;
struct book{
    char ISBN[6];
    char TITLE[100];
    char AUTHOR_NAME[100];
    float PRICE;
    int YEAR;
    int NUM_PAGES;
    book(char* isbn = "" , char* title = "" , char* author = "" , float price = 0 , int year = 0, int nPages = 0){
        strcpy(ISBN ,isbn);
        strcpy(TITLE , title);
        strcpy(AUTHOR_NAME ,author);
        PRICE = price;
        YEAR = year;
        NUM_PAGES = nPages;
    }
};
void printBook(book b);
void addBook(fstream& file );
//void deleteBook(fstream& file , int isbn);
//void updateBook(fstream& file , int isbn);
//void printBookByTitle(fstream& file , char* title);
//void printAll(fstream& file);
void addBook(fstream& file ){
    cout << "nplease enter your book's n1- ISBNn2- title n3- author name n4- price n5- year n6- number of pagesn";
    book b;
    cin.getline(b.ISBN , 6);
    cin.getline(b.TITLE ,100);
    cin.getline(b.AUTHOR_NAME ,100);
    cin >> b.PRICE;
    cin >> b.YEAR;
    cin >> b.NUM_PAGES;
    cin.ignore();
    file.write((char*)& b ,sizeof(b));
    file<<'n';
}
void printBook(book b){
    cout << "the book's ISPN is " << b.ISBN << endl;
    cout << "the title of this book is " << b.TITLE << endl;
    cout << "the author is " << b.AUTHOR_NAME << endl;
    cout << "the book's price is "<<b.PRICE<< endl;
    cout << "the year by which was published is "<< b.YEAR << endl;
    cout << "the number of pages on this book is " << b.NUM_PAGES << endl << endl;
}
int main()
{
    fstream file;
    file.open("farah.txt" , ios::out | ios::in );
    book b;
    addBook(file);
    addBook(file);
    addBook(file);

    file.seekg(0);
    do{
        file.getline((char*)& b , sizeof(b)+1);
        printBook(b);
    }while(!file.eof()-1);
    return 0;
}
file.write((char*)& b ,sizeof(b));
file<<'n';

因此,您写出可能包含newline字符的原始记录,然后写出一个newline字符。

    file.getline((char*)& b , sizeof(b)+1);

然后,您使用getline尝试将其读回去。但这行不通。按照定义,一条线以newline字符结束。因此,记录可能会出现,如果通过读取行的函数读取以占据多个行。

增加一个大小会导致一个巨大的问题。当您的实现看到book b时,它知道分配sizeof(book)字节以容纳对象。但是,您读取的字节数不仅仅是读取的字节 - 写入您尚未分配的内存,可能会踩在其他对象上或造成访问违规。

您有一些选择:

您可以使用原始读取函数读取sizeof(b)字节,然后读取Newline字符。您可以使用原始读取功能并摆脱Newline。您可以将记录格式化为一行,然后使用读取行读取线条的函数。

最后,您还滥用eof。您正在尝试使用它来预测未来,也就是说,告诉您未来的阅读是否会成功。但是eof是一个状态报告功能(例如selectstatfsaccess等),而不是未来预测的功能。相反,查看读取是否真正成功,而不是尝试以某种方式确保它在执行之前不会失败。

while(!file.eof()-1);应该是 while(!file.eof());这可能是主要问题。

char* isbn = "" , char* title = "" , char* author = "" ...

仅在C 中允许,因为您正在尝试将char *转换为const char *