2016-01-22 115 views
0
void readersWriters::WriteLine(int lineNumber, std::string newLine) 
{ 
    fstream file(_fileName, std::fstream::out | std::fstream::in); 

    if (file.is_open()) 
    { 
     int count = 1; 
     string line_data; 
     bool found = false; 
     while (!file.eof() && !found) 
     { 
      getline(file, line_data); 
      if (count == lineNumber) 
      { 
       writeLock(); 
       found = true; 
       if (line_data.length() > newLine.length()) 
        newLine += line_data.substr(newLine.length(), line_data.length()); 

       file << newLine; 
       getline(file, line_data); 

       writeUnlock(); 
      } 
      count++; 
     } 
     file.close(); 
     if (!found) 
     { 
      cout << ERROR_WRITE << endl; 
     } 
    } 
} 

我想寫入到fstram文件,該函數運行沒有任何錯誤,但文件保持不變。我不明白爲什麼會發生:(。 感謝halp :)不能寫入fstream文件

+2

可能重複:http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Tas

+1

你爲什麼要讀,並在同一時間寫入文件? – NathanOliver

+0

'while(!file.eof()'Whoops –

回答

0

你不能以這種方式修改文件。將文件作爲字符串矢量(每行一個字符串)讀取文件最簡單,修改內存中的行,然後再次保存行。