2014-06-26 121 views
1

我想編輯一個文本文件,但我一直在尋找正確的功能或方法。 到目前爲止,我可以打開一個文本文件並查找某個Sting,但我不知道如何移動光標,添加或替換信息,下面顯示的僞代碼中的步驟4 - 7。編輯文本文件

你能提供一些指導嗎?我應該使用哪些功能(如果它們已經存在)? 一個樣本'簡單'的代碼也將不勝感激。

Pseudocode: 

1. Open file. 
2. While not eof 
3. Read file until string "someString" is found. 
4. Position the cursor at the next line (to where the someString was found). 
5. If "someString" = A go to step 6. Else go to step 7. 
6.  Replace the information in whole line with "newString". Go to step 8. 
7.  Add new information "newString_2", without deleting the existing. 
8. Save and close the text file. 

謝謝。

+0

文件沒有像這樣的「遊標」。你是在談論編寫一個* visual *文本編輯器,或者你是在談論從文件中讀取文本,然後寫出它的新版本? – crashmstr

+1

你不能直接在文件中替換一行,文件不會做出這樣的區分。我的建議是,您閱讀文件並將所需的輸出寫入新文件。 – Havenard

+0

@Havenard這將是更簡單的解決方案,但您可以通過刪除內容並插入新內容來「替換一行」。 –

回答

1

這應該是一個良好的開端:

// basic file operations 
#include <string> 
#include <fstream> 

int main() 
{ 
    std::fstream myfile; 
    std::string line; 

    while (!myfile.eof()) 
    { 
    std::getline(myfile,line); // Check getline() doc, you can retrieve a line before/after a given string etc. 
    //if (line == something) 
    //{ 
     // do stuff with line, like checking for content etc. 
    //} 
    } 
    myfile.close(); 
    return 0; 
} 

更多信息here

2

我會建議把函數getline命令進入while循環,因爲那不會停止,只是由於EOF但是當getline無法再讀取。 就像發生錯誤bad時(當程序讀取文件時有人刪除文件時發生這種情況)。

看來你想在一個字符串內搜索,所以「查找」可能會很有幫助。

#include <iostream> 
#include <fstream> 
#include <string> 

int main(){ 
    std::fstream yourfile; 
    std::string line, someString; 

    yourfile.open("file.txt", ios::in | ios::app); //The path to your file goes here 

    if (yourfile.is_open()){ //You don't have to ask if the file is open but it's more secure 
    while (getline(line)){ 
     if(line.find(someString) != string::npos){ //the find() documentation might be helpful if you don't understand 
     if(someString == "A"){ 
      //code for replacing the line 
     } 
     else{ 
      yourfile << "newString_2" << endl; 
     } 
     } //end if 
    } //end while 
    } //end if 
    else cerr << "Your file couldn't be opened"; 

    yourfile.close(); 
    return 0; 
} 

我不能告訴你如何替換文本文件中的單行,但我希望你可以使用我可以給你的那一點。

+0

是的,我的答案很快且不完整,因爲我認爲這個問題微不足道,並在網絡上大量記錄。但我也會這麼做:) –

+1

我完全同意,但我有一些時間,以節省^^ – Skardan