Làm cách nào để nối văn bản vào một tệp văn bản trong C++? Tạo mới nếu không tồn tại và nối thêm nếu tồn tại.Làm cách nào để nối văn bản vào một tệp văn bản trong C++?
Trả lời
#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("test.txt", std::ios_base::app);
outfile << "Data";
return 0;
}
Không cần phải đóng tệp theo cách thủ công, vì nó sẽ bị phá hủy. Xem http://stackoverflow.com/questions/748014/. Ngoài ra,
Bạn có thể sử dụng ứng dụng ios :: thay cho ios_base :: app –
Có thể sử dụng 'std :: ofstream :: out | std :: ofstream :: app' thay vì 'std :: ios_base :: app'? http://www.cplusplus.com/reference/fstream/ofstream/open/ – Volomike
#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;
}
Tôi sử dụng mã này. Nó đảm bảo rằng tập tin được tạo ra nếu nó không tồn tại và cũng cho biết thêm chút kiểm tra lỗi.
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;
}
http://cplusplus.com/reference/iostream/ofstream/open/ – bobobobo