[英]How to append text to a text file in C++?
How to append text to a text file in C++?如何将文本附加到 C++ 中的文本文件? And create a new text file if it does not already exist and append text to it if it does exist.
如果尚不存在,则创建一个新文本文件,如果存在,则将文本附加到其中。
You need to specify the append open mode like您需要指定附加打开模式,如
#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
outfile << "Data";
return 0;
}
I use this code.我用这个代码。 It makes sure that file gets created if it doesn't exist and also adds bit of error checks.
它确保在文件不存在时创建该文件,并添加一些错误检查。
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;
}
#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;
}
You could use an fstream
and open it with the std::ios::app
flag.您可以使用
fstream
并使用std::ios::app
标志打开它。 Have a look at the code below and it should clear your head.看看下面的代码,它应该会让你清醒。
...
fstream f("filename.ext", f.out | f.app);
f << "any";
f << "text";
f << "written";
f << "wll";
f << "be append";
...
You can find more information about the open modes here and about fstreams here .你可以找到关于开放模式的详细信息,在这里和有关fstreams这里。
You could also do it like this你也可以这样做
#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;
}
The code below should work:下面的代码应该工作:
#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;
}
I hope this helps you :)我希望这可以帮助你 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.