2013-05-05 12 views
0

下面的代碼完全符合它應有的一個例外。修改後的緩衝區內容不會保存到文件中。我已經完成了代碼,我可以看到緩衝區正在改變,所以我不確定發生了什麼。任何意見將不勝感激。需要一些幫助,瞭解爲什麼wifstream緩衝區不會被保存迴文件

bool replacestring(char *ifile, wstring& searchString, wstring& replacementString) 
{ 
    wstring buffer; 
    wifstream finout(ifile, ios_base::in | ios_base::out | ios_base::binary); 

if(!finout.is_open()) 
{ 
    cout << "Can not open file " << endl; 
    return(1); 
} 
while(getline(finout,buffer)) 
{ 
    auto pos = buffer.find(searchString) ; 
    while(pos != std::string::npos) 
    { 
     buffer.replace(pos, searchString.size(), replacementString) ; 
     pos = buffer.find(searchString, pos + replacementString.size()) ; 
    } 
    if(finout.bad()) 
     perror("BAD READ"); 
} 
finout.close(); 
return 0; 
} 

回答

2

你從一個流複製到緩衝區中的一些數據後,該緩衝區與物流分離,並以緩衝所做的更改不會流中得到體現。

ifstreamwifstream是輸入流,而不是輸出流。

filebufwfilebuf可能是你想要的。

或者Boost.Iostreams

使用ofstreamwofstream寫入第二個文件可能會更容易。這也將避免破壞現有文件的風險。

類似的問題: