2010-03-06 134 views

回答

184
#include <fstream> 

int main() { 
    std::ofstream outfile; 

    outfile.open("test.txt", std::ios_base::app); 
    outfile << "Data"; 
    return 0; 
} 
+9

無需手動關閉文件,因爲它這樣做時破壞。請參閱http://stackoverflow.com/questions/748014/。此外,示例中未使用。 – swalog 2013-09-12 15:47:31

+5

你可以使用ios :: app來代替ios_base :: app – 2015-07-09 17:50:21

+3

可以使用'std :: ofstream :: out | std :: ofstream :: app'而不是'std :: ios_base :: app'? http://www.cplusplus.com/reference/fstream/ofstream/open/ – Volomike 2016-02-25 22:12:31

7
#include <fstream> 
#include <iostream> 

FILE * pFileTXT; 
int counter 

int main() 
{ 
pFileTXT = fopen ("aTextFile.txt","a");// use "a" for append, "w" to overwrite, previous content will be deleted 

for(counter=0;counter<9;counter++) 
fprintf (pFileTXT, "%c", characterarray[counter]);// character array to file 

fprintf(pFileTXT,"\n");// newline 

for(counter=0;counter<9;counter++) 
fprintf (pFileTXT, "%d", digitarray[counter]); // numerical to file 

fprintf(pFileTXT,"A Sentence");     // String to file 

fprintf (pFileXML,"%.2x",character);    // Printing hex value, 0x31 if character= 1 

fclose (pFileTXT); // must close after opening 

return 0; 

} 
+16

這是C方式,不是C++。 – 2014-07-14 11:07:54

+3

@Dženan。 C是C++的一個子集並不會使這種方法失效。 – Osaid 2014-09-12 09:13:48

+4

@Osaid它只是使其冗餘...... – arman 2014-09-24 01:38:04

5

我用這個代碼。它確保文件在不存在的情況下被創建,並且還添加了一些錯誤檢查。

static void appendLineToFile(string filepath, string line) 
{ 
    std::ofstream file; 
    //can't enable exception now because of gcc bug that raises ios_base::failure with useless message 
    //file.exceptions(file.exceptions() | std::ios::failbit); 
    file.open(filepath, std::ios::out | std::ios::app); 
    if (file.fail()) 
     throw std::ios_base::failure(std::strerror(errno)); 

    //make sure write fails with exception if something is wrong 
    file.exceptions(file.exceptions() | std::ios::failbit | std::ifstream::badbit); 

    file << line << std::endl; 
}