【发布时间】:2011-01-24 12:01:07
【问题描述】:
如何在 C++ 中将文本附加到文本文件?如果它不存在则创建一个新的文本文件,如果它存在则追加文本。
【问题讨论】:
标签: c++ filestream
如何在 C++ 中将文本附加到文本文件?如果它不存在则创建一个新的文本文件,如果它存在则追加文本。
【问题讨论】:
标签: c++ filestream
你需要像这样指定追加打开模式
#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
outfile << "Data";
return 0;
}
【讨论】:
std::ofstream::out | std::ofstream::app代替std::ios_base::app吗? cplusplus.com/reference/fstream/ofstream/open
std::ofstream 时,您不需要显式指定out 标志,它始终为您隐式使用out 标志。与 std::ifstream 的 in 标志相同。如果您改用std::fstream,则必须明确指定in 和out 标志。
我使用此代码。如果文件不存在,它会确保创建该文件,并添加一些错误检查。
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;
}
【讨论】:
你也可以这样做
#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 析构函数中被调用。
下面的代码应该可以工作:
#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;
}
希望对你有帮助:)
【讨论】: