C++ fstream 在 .txt 中搜索结构

C++ fstream searching through a .txt for a structure

我有一个程序允许用户输入新记录(放入结构然后写入文件)、打印所有记录或编辑特定记录。我已经包含了我的功能。这些记录是针对女童子军 cookie 信息的。它具有名称、数量、价格和成本。它打开文件要求用户输入名称,然后当它找到该名称时,它会将所有数据读入一个临时结构变量(与写入文件的内容相同),用户可以在其中更改数量和在读取它的同一个地方重写它。一切都应该是相同的,除了更新的 quantity.It 完成了所有这些,但由于某种原因将它之前的所有其他记录变为空或 0。我的错误是什么让我改变了文件中的所有其他记录。我只想编辑这个特定的。 这只是功能。非常感谢您的帮助!

功能代码:

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())更改为while(data)
  • 为清楚起见,请在 while 循环开始时从文件中读取记录,而不是在结束时。
  • 您可以在写入记录后跳出循环。
  • 写cookies.txt时,用std::ios::binary | std::ios::in | std::ios::out打开。从 std::ios::beg.
  • 中寻找
  • 您已打开文件以同时读取和写入。这应该有效,但没有必要。在写入之前关闭文件以进行读取。