2014-05-11 17 views
0

我在做這個項目,我想爲設備保存一些變量; Devicename,ID和類型。需要關於通過fstream保存變量的幫助,我需要使用向量嗎?

bool Enhedsliste::newDevice(string deviceName, string type) 
{ 
fstream myFile; 
string line; 
char idDest[4]; 

myFile.open("Devices.txt", ios::app | ios::in | ios::out); //Opretter/Åbner fil, app = startlinje er den nederste linje, in out = input output 
if (myFile.is_open()) 
{ 
    while (getline(myFile, line)) //Går filen igennem for hver linje 
    { 
     if (line == deviceName) 
     { 
      cout << deviceName << "-device already exists." << endl; 
      return false; 
     } 
    } 
} 
else 
{ 
    cout << "Uable to open file." << endl; 
    return false; 
} 
myFile.close(); 

myFile.open("Devices.txt", ios::app | ios::in | ios::out); //Opretter/Åbner fil, app = startlinje er den nederste linje, in out = input output 
if (myFile.is_open()) 
{ 
    if (type == "Lampe") 
     type_ = 1; 
    else if (type == "Roegalarm") 
     type_ = 2; 
    else if (type == "Tyverialarm") 
     type_ = 3; 
    else 
    { 
     cout << "Type does not exists." << endl; 
     return false; 
    } 

    deviceName_ = deviceName; 
    myFile << deviceName_ << endl; 

    id_++; 
    sprintf_s(idDest, "%03d", id_); 
    myFile << idDest << endl; 

    myFile << type_ << endl; 

    myFile.close(); 

    return true; 
} 
else 
{ 
    cout << "Uable to open file." << endl; 
    return false; 
} 
} 

現在我也要打個deleteDevice,在那裏我可以把設備名作爲參數,它會發現該行並刪除ID和類型,但我對如何做到這一點不知道。

我需要重寫我的addDevice向量嗎?我該怎麼做?

在此先感謝並對錯誤的代碼,解釋等抱歉。我是新手。

回答

0

要從當前文本文件中刪除一行,您必須閱讀所有行,例如,將數據存儲在std::map中,刪除相關項目並將其全部寫回。另一種方法是使用數據庫或二進制固定大小的記錄文件,但將所有內容讀入內存是很常見的。順便說一句,我會刪除ios::app附加模式打開文件閱讀。它轉化爲fopen的追加模式的等價物,但C99標準對於閱讀意味着什麼還不清楚,如果有的話。

0

要刪除單個設備,您可能會讀取該文件並寫入臨時文件。 傳輸/過濾數據後,重命名並刪除文件:

#include <cstdio> 
#include <fstream> 
#include <iostream> 

int main() { 
    std::string remove_device = "Remove"; 
    std::ifstream in("Devices.txt"); 
    if(! in) std::cerr << "Missing File\n"; 
    else { 
     std::ofstream out("Devices.tmp"); 
     if(! out) std::cerr << "Unable to create file\n"; 
     else { 
      std::string device; 
      std::string id; 
      std::string type; 
      while(out && std::getline(in, device) && std::getline(in, id) && std::getline(in, type)) { 
       if(device != remove_device) { 
        out << device << '\n' << id << '\n' << type << '\n'; 
       } 
      } 
      if(! in.eof() || ! out) std::cerr << "Update failure\n"; 
      else { 
       in.close(); 
       out.close(); 
       if(! (std::rename("Devices.txt", "Devices.old") == 0 
       && std::rename("Devices.tmp", "Devices.txt") == 0 
       && std::remove("Devices.old") == 0)) 
        std::cerr << "Unable to rename/remove file`\n"; 
      } 
     } 
    } 
} 
+0

這不會留下空白嗎? – Thisen

+0

我剛剛意識到一些事情。如果你這樣做,身份證號碼將回到3,但可能已經有ID爲3的設備。所以這是行不通的。 – Thisen