2011-08-03 77 views
12

因此,我已經創建了一個程序,其中有一個字符串,我想要將其流式傳輸到現有文本文件的末尾。所有的什麼小我的是這樣的:(C++)將字符串寫入文件末尾(C++)

void main() 
{ 
    std::string str = "I am here"; 
    fileOUT << str; 
} 

我知道有多少被添加到這一點,如果它似乎我要求人們爲我的代碼,我也道歉,但我完全喪失因爲我之前從未做過這種類型的編程。

我嘗試過不同的方法,我已經遇到了互聯網,但這是最接近的作品,有點熟悉。

+1

的'main'函數返回'int'。總是。 (不是我原來的報價。)將0或EXIT_SUCCESS返回到正常終止的操作系統或EXIT_FAILURE。 –

+1

@Thomas Matthews這不是整個代碼......事實上,這甚至不是我的主要功能。但謝謝你爲我注意! – ked

回答

22

打開使用std::ios::app

#include <fstream> 

std::ofstream out; 

// std::ios::app is the open mode "append" meaning 
// new data will be written to the end of the file. 
out.open("myfile.txt", std::ios::app); 

std::string str = "I am here."; 
out << str; 
+0

哦,我的天啊,那是一個快速回答!非常感謝!我無法相信這很簡單。但是我有一個問題,___。open(「file」,std :: ios :: app)佔用了很多內存嗎?我正在處理非常大的文件,因此非常關鍵。 – ked

+0

@ked:否,'out.open(..)'和'std :: ofstream out(..)'只打開數據傳輸的句柄。您可以「打開」一個大文件,除非您實際上將整個內容讀入內存,否則不必擔心內存。 –

+0

謝謝噸傢伙!包括其他所有回答的人! – ked

2

打開你的流作爲追加,寫入它的新文本將寫在文件的末尾。

+0

雖然這不是最詳細的答案,但沒有必要降低它,它是完全正確和完整的。 – Blindy

+0

作爲新人,我有點需要看看代碼本身,但仍然是感謝! – ked

5

要追加內容的文件後,你的文件,只需打開與ofstream一個文件中app模式(代表追加(代表出文件流)。

#include <fstream> 
using namespace std; 

int main() { 
    ofstream fileOUT("filename.txt", ios::app); // open filename.txt in append mode 

    fileOUT << "some stuff" << endl; // append "some stuff" to the end of the file 

    fileOUT.close(); // close the file 
    return 0; 
} 
2

我希望這不是你的整個代碼,因爲如果是這樣,它有很多錯誤的地方。

你會寫到一個文件的方式看起來是這樣的:

#include <fstream> 
#include <string> 

// main is never void 
int main() 
{ 
    std::string message = "Hello world!"; 

    // std::ios::out gives us an output filestream 
    // and std::ios::app appends to the file. 
    std::fstream file("myfile.txt", std::ios::out | std::ios::app); 
    file << message << std::endl; 
    file.close(); 

    return 0; 
} 
+1

哈哈,別擔心它不是。我只是寫了一些文件,其餘的只有200行......迄今爲止 – ked