2012-04-19 58 views
2

我有一個txt文件是這樣的:如何使用C++編輯文本文件中的一行?

"shoes":12 
"pants":33 
"jacket":26 
"glasses":16 
"t-shirt":182 

我需要更換套的數量(從26至42例如)。所以,我寫了這個代碼,但我不知道如何編輯特定的行那裏是單詞「外套」:

所有的
#include <iostream> 
#include <fstream> 

using namespace std; 

int main() { 

    ifstream f("file.txt"); 
    string s; 

    if(!f) { 
     cout< <"file does not exist!"; 
     return -1; 
    } 

    while(f.good()) 
    {  
     getline(f, s); 
     // if there is the "jacket" in this row, then replace 26 with 42. 
    } 


    f.close(); 
    return 0; 
} 
+0

這是C++,所以它不是重複的。 – xRobot 2012-04-19 10:09:28

+0

你想在C,C++還是兩者兼顧的解決方案? – 2012-04-19 10:11:32

+0

在C或C++中......無所謂:) – xRobot 2012-04-19 10:12:32

回答

3

爲了修改文本文件中的數據,您通常必須將整個文件讀入 到內存中,然後在那裏進行修改,然後重寫 它。在這種情況下,我建議定義項的結構, 與namequantity項,定義爲 名的平等機會,以及超載operator>>operator<<讀取和文件寫入 它。然後,您就整體邏輯將使用功能,如:

void 
readData(std::string const& filename, std::vector<Entry>& dest) 
{ 
    std::ifstream in(filename.c_str()); 
    if (!in.is_open()) { 
     // Error handling... 
    } 
    dest.insert(dest.end(), 
       std::istream_iterator<Entry>(in), 
       std::istream_iterator<Entry>()); 
} 

void 
writeData(std::string const& filename, std::vector<Entry> const& data) 
{ 
    std::ifstream out((filename + ".bak").c_str()); 
    if (!out.is_open()) { 
     // Error handling... 
    } 
    std::copy(data.begin(), data.end(), std::ostream_iterator<Entry>(out)); 
    out.close(); 
    if (! out) { 
     // Error handling... 
    } 
    unlink(filename.c_str()); 
    rename((filename + ".bak").c_str(), filename.c_str()); 
} 

(我建議在錯誤處理引發異常,所以你不要 擔心的if S的else分支除外。爲 在第一個創建的ifstream,錯誤條件是例外。)

+0

如果整個文件必須被讀取並保存在內存中,那麼SQLite DB是如何管理的(這顯然是基於單個文件的)?用C++ 11編輯行描述符有沒有更簡單的方法?可能你可以編輯你的答案,在文件中重寫,數據量完全相同嗎? [例如。覆蓋](http://stackoverflow.com/a/10226445/514235)該文件中的一個字段,該字段爲0並將其設置爲1。 – iammilind 2016-07-18 06:12:38

0

首先,這是不可能用簡單的方式。假設您想要編輯所述行但寫入更大的數字,則文件中不會有空間。所以通常在中間的eidts通過重寫文件或寫一個副本來完成。程序可能會使用內存,臨時文件等,並將其隱藏起來,但是在文件中間鏈接一些字節只能在非常困難的環境中工作。

所以你想要做的是寫另一個文件。

... 
string line; 
string repl = "jacket"; 
int newNumber = 42; 
getline(f, line) 
if (line.find(repl) != string::npos) 
{ 
    osstringstream os; 
    os << repl << ':' << newNumber; 
    line = os.str(); 
} 
// write line to the new file. For exmaple by using an fstream. 
... 

如果文件是相同的,可以讀取所有行的內存,如果有足夠的內存,或使用臨時文件的輸入或輸出。