2012-06-19 161 views
2

我希望能夠將行添加到文件的開頭。將文本和行添加到文件的開頭(C++)

我正在編寫的這個程序將從用戶獲取信息,並準備寫入一個文件。那麼這個文件將會是一個已經生成的差異文件,並且在開頭添加的是描述符和標籤,這使得它與Debian的DEP3 Patch標籤系統兼容。

這必須是跨平臺的,所以它需要在GNU C++(Linux的)和Microsoft C到工作++(和任何Mac都配備)

(相關主題在其他地方:http://ubuntuforums.org/showthread.php?t=2006605

+0

爲什麼要使用C++的呢? –

+0

[在C++中,在文本文件的開頭插入一行的正確方法是什麼?](http://stackoverflow.com/questions/4179349/in-c-what-is-the-proper插入一行文本的開頭) –

+0

看起來像是重複的,但其他問題沒有很好的答案。 –

回答

9

trent.josephsen's回答:

您不能在磁盤上的文件開始處插入數據。您需要將整個文件讀入內存,在開始時插入數據,然後將整個文件寫回磁盤。 (這是不是唯一的方法,但由於該文件不是太大,它可能是最好的。)

您可以通過使用std::ifstream輸入文件和std::ofstream輸出文件達到這樣。之後,您可以使用std::removestd::rename,以取代舊文件:

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

int main(){ 
    std::ofstream outputFile("outputFileName"); 
    std::ifstream inputFile("inputFileName"); 
    std::string tempString; 

    outputFile << "Write your lines...\n"; 
    outputFile << "just as you would do to std::cout ...\n"; 

    outputFile << inputFile.rdbuf(); 

    inputFile.close(); 
    outputFile.close(); 

    std::remove("inputFileName"); 
    std::rename("outputFileName","inputFileName"); 

    return 0; 
} 

不使用removerename使用std::stringstream另一種方法:

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

int main(){ 
    const std::string fileName = "outputFileName"; 
    std::fstream processedFile(fileName.c_str()); 
    std::stringstream fileData; 

    fileData << "First line\n"; 
    fileData << "second line\n"; 

    fileData << processedFile.rdbuf(); 
    processedFile.close(); 

    processedFile.open(fileName.c_str(), std::fstream::out | std::fstream::trunc); 
    processedFile << fileData.rdbuf(); 

    return 0; 
} 
+3

'while'循環可以用'outputFile << inputFile.rdbuf();' – jxh

+0

替換寫完後其他文件,他可以「刪除」原始文件,並用原始名稱「重命名」另一個文件。儘管如此,可能要在'fstream's上調用'close'。 – jxh

+0

而不是使用'vector '爲什麼不使用'stringstream'? –

相關問題