gpt4 book ai didi

C++ 二进制文件方法正在从文件中删除内容?

转载 作者:行者123 更新时间:2023-11-30 02:04:40 25 4
gpt4 key购买 nike

我有一个任务,我要写各种东西的输入(以结构的形式),然后写入一个二进制文件。当程序打开时,我必须能够读取和写入文件。其中一种方法需要打印出二进制文件中的所有客户端。它似乎在工作,除非每当我调用该方法时,它似乎都会删除文件的内容并防止向其中写入更多内容。以下是适用的片段:

fstream binaryFile;
binaryFile.open("HomeBuyer", ios::in | ios::app | ios::binary);

同一个文件应该在你运行程序的两次之间可用,所以我应该用 ios::app 打开它,对吗?

添加条目的方法如下:

void addClient(fstream &binaryFile) {
HomeBuyer newClient; //Struct the data is stored in
// -- Snip -- Just some input statements to get the client details //

binaryFile.seekp(0L, ios::end); //This should sent the write position to the
//end of the file, correct?
binaryFile.write(reinterpret_cast<char *>(&newClient), sizeof(newClient));

cout << "The records have been saved." << endl << endl;
}

现在是打印所有条目的方法:

void displayAllClients(fstream &binaryFile) {
HomeBuyer printAll;
binaryFile.seekg(0L, ios::beg);
binaryFile.read(reinterpret_cast<char *>(&printAll),sizeof(printAll));

while(!binaryFile.eof()) { //Print all the entries while not at end of file
if(!printAll.deleted) {
// -- Snip -- Just some code to output, this works fine //
}

//Read the next entry
binaryFile.read(reinterpret_cast<char *>(&printAll),sizeof(printAll));
}
cout << "That's all of them!" << endl << endl;
}

如果我单步执行程序,我可以输入任意数量的客户端,并且它会在我第一次调用 displayAllClients() 时输出所有客户端。但是一旦我调用 displayAllClients() 一次,它似乎就清除了二进制文件,并且任何进一步的显示客户端的尝试都没有结果。

我是否错误地使用了 seekp 和 seekg?

据我所知,这应该将我的写入位置设置为文件末尾:

binaryFile.seekp(0L, ios::end);

这应该将我的阅读位置设置为开头:

binaryFile.seekg(0L, ios::beg);

谢谢!

最佳答案

在解决问题时粘贴评论。

如果 EOF,您需要在 seekp()seekg() 之前调用 binaryFile.clear()已设置,否则它们将无法工作。

关于C++ 二进制文件方法正在从文件中删除内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10358079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com