如何在C++中将文本追加到文本文件中?

Ahm*_*rid 169 c++ filestream

如何在C++中将文本追加到文本文件中?如果不存在则创建new,如果存在则追加.

Ber*_*ron 255

#include <fstream>

int main() {  
  std::ofstream outfile;

  outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
  outfile << "Data"; 
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 无需手动关闭文件,因为它在销毁时会这样做.请参见http://stackoverflow.com/questions/748014/.此外,示例中未使用<iostream>. (11认同)
  • 您可以使用ios :: app代替ios_base :: app (6认同)
  • 如果你想减少代码,你也可以在构造函数中做更多:std :: ofstream outfile("test.txt",std :: ios_base :: app); (6认同)
  • 可以使用`std :: ofstream :: out | std :: ofstream :: app`而不是`std :: ios_base :: app`?http://www.cplusplus.com/reference/fstream/ofstream/open/ (3认同)

Osa*_*aid 11

 #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;

}
Run Code Online (Sandbox Code Playgroud)

  • 这是C方式,而不是C++. (27认同)
  • @Osaid C不是C++的子集.编译器编译其代码以实现向后兼容性.许多C-valid事物不是C++ - 有效的东西,例如VLA. (5认同)
  • @Dženan.C是C++的一个子集并不会使这种方法无效. (3认同)

Shi*_*hah 10

我用这个代码.它确保文件在不存在时被创建,并且还会添加一些错误检查.

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;
}
Run Code Online (Sandbox Code Playgroud)