我有一个允许用户输入新记录(放入结构然后写入文件),打印所有记录或编辑特定记录的程序。我已经包含了我的功能。这些记录是针对girlcout cookie信息的。它有名称,数量,价格和成本。它打开文件,要求用户输入名称,然后当它找到名称时,它将所有数据读入临时结构变量(与写入文件的相同),用户可以在其中更改数量和重写它在它被读取的同一个地方。除了更新的数量之外,所有内容都应该是相同的。它会执行所有这些操作,但由于某种原因会将所有其他记录变为null或0之前的所有其他记录。我的错误是什么让这个改变了我文件中的所有其他记录。我只想编辑这个特定的一个。 这只是功能。帮助真的很感激!C++ fstream通过.txt搜索结构
功能代码:
void editField()
{
char input[20];
fstream data("cookies.txt", ios::in);
cookies test;
if (!data) {
cout << "Error opening file. Program aborting.\n";
return;
}
cout << "Please enter the name of the cookie you are searching for: ";
cin.getline(input,20);
data.read(reinterpret_cast<char *>(&test),
sizeof(test));
while (!data.eof())
{
if(strcmp(input,test.name) == 0) {
int position = data.tellp();
data.close();
data.clear();
data.open("cookies.txt", ios::binary | ios::out);
cout << "Please enter the new quantity for the cookie ";
cin >> test.quantity;
data.seekp(position-sizeof(test),ios::cur);
data.write(reinterpret_cast<char *>(&test), sizeof(test));
}
// Read the next record from the file.
data.read(reinterpret_cast<char *>(&test),
sizeof(test));
}
return;
}
像往常一样'while(!data.eof())'是错误的 - 我没有读过去(在这样做之后,这段代码是垃圾) – 2015-04-01 20:32:44
这段代码并不按原样编译。请发布有问题的[最小示例](http://stackoverflow.com/help/mcve) – chwarr 2015-04-01 20:52:46
这不能编译?我现在正在运行它?我是包含的#include 的#include 的#include 的#include 的#include 的#include 的#include –
Reaperr
2015-04-01 20:57:52