咨詢通義千問的“C++ 寫入txt文件內(nèi)容并追加內(nèi)容”:
可以使用ofstream類來寫入txt文件內(nèi)容。若想追加內(nèi)容,可以使用ios::app標(biāo)志來創(chuàng)建輸出流對象,然后在寫入時(shí)將其設(shè)置為ios::app。以下是一個(gè)示例代碼:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream out(""D:\\example.txt", ios::app);
time_t now = time(nullptr);
char timeStr[30];
strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", localtime(&now));
out << timeStr << endl;
out << "Hello, World!" << endl;
out << "This is an example." << endl;
out.close();
return 0;
}
在這個(gè)例子中,我們創(chuàng)建了一個(gè)名為“example.txt”的輸出流對象,并將其設(shè)置為ios::app。然后,我們寫入了兩行文本,并在文件末尾添加了它們。最后,我們關(guān)閉了輸出流對象。
若想在文件開頭追加內(nèi)容,可以使用ios::ate標(biāo)志來創(chuàng)建輸出流對象。這將導(dǎo)致輸出流對象自動(dòng)跳過文件開頭的內(nèi)容,并將下一個(gè)寫入操作添加到文件末尾。以下是一個(gè)示例代碼:文章來源:http://www.zghlxwxcb.cn/news/detail-665223.html
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream out(""D:\\example.txt", ios::ate | ios::out);
time_t now = time(nullptr);
char timeStr[30];
strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", localtime(&now));
out << timeStr << endl;
out << "This is an example." << endl;
out << "Hello, World!" << endl;
out.close();
return 0;
}
在這個(gè)例子中,我們創(chuàng)建了一個(gè)名為“example.txt”的輸出流對象,并將其設(shè)置為ios::ate | ios::out。然后,我們寫入了兩行文本,并在文件末尾添加了它們。最后,我們關(guān)閉了輸出流對象。文章來源地址http://www.zghlxwxcb.cn/news/detail-665223.html
到了這里,關(guān)于C++ 寫入txt文件內(nèi)容并追加內(nèi)容的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!