2017-08-12 110 views
0

我正在写使用结构库系统观看如何使用C++删除/更新txt文件中的特定数据?

struct Book 
{ 
    char name[50]; 
    int ID; 
    char author[50]; 
    double price; 
    int copies; 
}; 

和所看到的文件组织。

ID Name   Author   Price Copies 
1 HarryPotter Lol   30  5  
2 EnglishMan English   30  5  
3 Spiderman Marvel   30  5  
4 Avengers Marvel   30  5   

比方说,我想用程序来更新书号。 2(EnglishMan)并更名为IronMan,我该如何使用文件做到这一点?

+0

你必须读取文件并解析它。查询您感兴趣的项目,修改它并将整个内容保存到文件中。实施取决于您选择哪一个最适合您使用。有一些库可以用来简化STL,boost或QT等库。 –

+0

@rafaelgonzalez我很新的编程,所以我不知道你说的大部分 – MiDo

+0

考虑使用SQLite数据库。 – 2017-08-12 18:42:16

回答

2

如果您使用纯文本文件作为数据存储,你只需要按照这个不方便的工作流程:

  1. 阅读完整的文件到你的数据结构。
  2. 修改数据。
  3. 截断或删除文件。
  4. 将所有数据写入文件。

有一些丑陋的黑客来编辑文件的某些部分,但它们并没有让事情变得更好。

为了管理表格数据,在你的例子中,relational databases已经发明很久以前了。开始学习SQLite,从长远来看,你的生活会更容易。

0

你所做的事情本质上是试图创建自己的数据库,这种数据库在最好情况下会适得其反。但如果是学习文件I/O和字符串流,下面的代码可以帮助你理解概念,尽管它可能不是最有效的做事方式。

在一般情况下,@Murphy说,你需要阅读的文件,将其复制到缓冲区,调整缓冲区根据自己的喜好,截断该文件,写自己的缓冲区里的文件。

int searchbyID(string filename, string ID, string newName); 

    int main() 
    { 
     searchbyID("d:\\test.txt", "2", "silmarillion"); 
    } 

    int searchbyID(string filename, string ID, string newName) 
    { 
     // open an input file stream 
     ifstream inputfile(filename); 

     if (!inputfile) 
      return -1; // couldn't open the file 

     string line,word; 
     string buffer; 

     // read the file line by line 
     while (getline(inputfile, line)) 
     { 
      std::stringstream record(line); 

      //read the id from the file and check if it's the asked one 
      record >> word; 
      if (word == ID) 
      { 
       // append the ID first 
       buffer += ID + "\t"; 

       //append the new name instead of the old one 
       buffer += newName + "\t"; 

       //pass the old name 
       record >> word; 

       //copy the rest of the line just as it is 
       while (record >> word) 
        buffer += "\t" + word + "\t"; 
       buffer += "\n"; 
      } 
      else 
      { 
       //if not, just pass the line as it is 
       buffer += line + "\n"; 
      } 

     } 
     // close input file stream 
     inputfile.close(); 

     // open an output file stream 
     ofstream outputfile(filename); 

     // write new buffer to the file 
     outputfile << buffer; 

     //close the output file stream 
     outputfile.close(); 

     return 0; 
    } 
相关问题