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

时间:2010-03-06 17:16:32

标签: c++ filestream

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

6 个答案:

答案 0 :(得分:236)

#include <fstream>

int main() {  
  std::ofstream outfile;

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

答案 1 :(得分:9)

我使用此代码。它确保文件在不存在的情况下被创建,并且还会添加一些错误检查。

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

答案 2 :(得分:8)

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

}

答案 3 :(得分:1)

您也可以这样

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

答案 4 :(得分:0)

我从一本名为“简单步骤中的C ++编程”的书中得到了我的答案代码。以下可能会有效。

#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 text here";
    writer.append(info);

    writer << info << endl;
    writer.close;
    return 0;   
} 

我希望这会对你有所帮助。

答案 5 :(得分:0)

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

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

您可以找到有关开放模式here和fstreams here的更多信息。