2015-04-01 45 views
-1

我有一个允许用户输入新记录(放入结构然后写入文件),打印所有记录或编辑特定记录的程序。我已经包含了我的功能。这些记录是针对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; 
} 
+0

像往常一样'while(!data.eof())'是错误的 - 我没有读过去(在这样做之后,这段代码是垃圾) – 2015-04-01 20:32:44

+0

这段代码并不按原样编译。请发布有问题的[最小示例](http://stackoverflow.com/help/mcve) – chwarr 2015-04-01 20:52:46

+0

这不能编译?我现在正在运行它?我是包含的#include 的#include 的#include 的#include 的#include 的#include 的#include Reaperr 2015-04-01 20:57:52

回答

0
  • 变化while(!data.eof())while(data)
  • 为了清晰起见,在你while循环的开始从文件中读取一个记录,而不是结尾。
  • 当您的记录被写入时,您可以跳出循环。
  • 写cookies.txt时,用std::ios::binary | std::ios::in | std::ios::out打开它。从std::ios::beg寻找。
  • 您可以同时读取和写入文件。这应该起作用,但没有必要。在写入之前先关闭文件进行阅读。
+0

谢谢!它只是在ios :: out时默认创建一个新文件。我应该已经知道的东西。感谢您对新手的尊重和帮助! – Reaperr 2015-04-01 21:11:31