2010-03-06 10 views

Antwort

184
#include <fstream> 

int main() { 
    std::ofstream outfile; 

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

Keine Notwendigkeit, die Datei manuell zu schließen, wie es so auf die Zerstörung der Fall ist. Siehe http://stackoverflow.com/questions/748014/. Außerdem wird im Beispiel nicht verwendet. – swalog

+5

Sie können ios :: app anstelle von ios_base :: app verwenden –

+3

Kann 'std :: ofstream :: out | std :: ofstream :: app' anstelle von 'std :: ios_base :: app'? http://www.cplusplus.com/reference/fstream/ofstream/open/ – Volomike

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

Dies ist C-Weg, nicht C++. –

+3

@ Dženan. C ist eine Teilmenge von C++ und macht diesen Ansatz nicht ungültig. – Osaid

+4

@Osaid macht es einfach überflüssig ... – arman

5

verwende ich diesen Code. Es stellt sicher, dass die Datei erstellt wird, wenn sie nicht existiert, und fügt auch ein paar Fehlerprüfungen hinzu.

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; 
} 
Verwandte Themen