2017-08-12 60 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; 
    } 
相關問題