【问题标题】:How to append text to a text file in C++?如何在 C++ 中将文本附加到文本文件?
【发布时间】:2011-01-24 12:01:07
【问题描述】:

如何在 C++ 中将文本附加到文本文件?如果它不存在则创建一个新的文本文件,如果它存在则追加文本。

【问题讨论】:

标签: c++ filestream


【解决方案1】:

你需要像这样指定追加打开模式

#include <fstream>

int main() {  
  std::ofstream outfile;

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

【讨论】:

  • 不需要手动关闭文件,因为它在销毁时会这样做。见stackoverflow.com/questions/748014。此外,示例中没有使用
  • 你可以使用 ios::app 代替 ios_base::app
  • 可以用std::ofstream::out | std::ofstream::app代替std::ios_base::app吗? cplusplus.com/reference/fstream/ofstream/open
  • 如果你想减少代码,你还可以在构造函数中做更多的事情:std::ofstream outfile("test.txt", std::ios_base::app);
  • 在使用std::ofstream 时,您不需要显式指定out 标志,它始终为您隐式使用out 标志。与 std::ifstreamin 标志相同。如果您改用std::fstream,则必须明确指定inout 标志。
【解决方案2】:

我使用此代码。如果文件不存在,它会确保创建该文件,并添加一些错误检查。

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

【讨论】:

    【解决方案3】:
     #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;
    
    }
    

    【讨论】:

    • 这是 C 方式,不是 C++。
    • @Dženan。 C 作为 C++ 的子集并不会使这种方法无效。
    • @Osaid C 不是 C++ 的子集。编译器编译其代码以实现向后兼容性。许多 C 有效的东西不是 C++ 有效的东西,例如VLA。
    • 但是如果我们想在文件中间附加文本呢?用C风格?使用文件 *??带有 fseek() 和 ftell() 的 "a+" 或 "a" 对我不起作用
    【解决方案4】:

    您可以使用fstream 并使用std::ios::app 标志打开它。看看下面的代码,它应该会让你头脑清醒。

    ...
    fstream f("filename.ext", f.out | f.app);
    f << "any";
    f << "text";
    f << "written";
    f << "wll";
    f << "be append";
    ...
    

    你可以找到更多关于开放模式here和fstreamshere的信息。

    【讨论】:

      【解决方案5】:

      你也可以这样做

      #include <fstream>
      
      int main(){   
      std::ofstream ost {outputfile, std::ios_base::app};
      
      ost.open(outputfile);
      ost << "something you want to add to your outputfile";
      ost.close();
      return 0;
      }
      

      【讨论】:

      • 将文件名传递给ofstream 构造函数会立即打开文件,因此之后调用open() 是多余的。
      • ost.close(); 也是多余的,因为它在 std::ofstream 析构函数中被调用。
      【解决方案6】:

      下面的代码应该可以工作:

      #include <fstream>
      #include <string>
      #include <iostream>
      
      using namespace std;
      
      int main()
      {
          ofstream writer("filename.file-extension" , ios::app);
      
          if (!writer)
          {
              cout << "Error Opening File" << endl;
              return -1;
          }
      
          string info = ""; //insert your text to be appended here
          writer.append(info);
          
          writer << info << endl;
          writer.close;
          return 0;   
      } 
      

      希望对你有帮助:)

      【讨论】:

      • 你不需要 writer.close();带括号?
      猜你喜欢
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多