gpt4 book ai didi

c++ - 如何使用 fstream 在 C++ 中追加文件?

转载 作者:行者123 更新时间:2023-12-02 08:21:33 28 4
gpt4 key购买 nike

我尝试用 C++ 附加文件。启动时文件不存在。操作后,文件中只有一行而不是五行(此方法调用了 5 次)。看起来文件正在创建,接下来每个写操作文件都被清除并添加新字符串。

void storeUIDL(char *uidl) {
fstream uidlFile(uidlFilename, fstream::app | fstream::ate);

if (uidlFile.is_open()) {
uidlFile << uidl;
uidlFile.close();
} else {
cout << "Cannot open file";
}
}

我尝试过 fstream::in ,fstream::out 。如何在此文件中正确附加字符串?

提前谢谢您。

编辑:

这是更广泛的观点:

for (int i = 0; i < items; i++) {
MailInfo info = mails[i];
cout << "Downloading UIDL for email " << info.index << endl;

char *uidl = new char[100];
memset(uidl, 0, 100);
uidl = servicePOP3.UIDL(info.index);
if (uidl != NULL) {
if (existsUIDL(uidl) == false) {
cout << "Downloading mail with index " << info.index << endl;
char *content = servicePOP3.RETR(info);

/// save mail to file
string filename = string("mail_" + string(uidl) + ".eml");
saveBufferToFile(content, filename.c_str());
storeUIDL(uidl);
sleep(1);
} else {
cout << "Mail already exists." << endl;
}
} else {
cout << "UIDL for email " << info.index << " does not exists";
}

memset(uidl, 0, 100);
sleep(1);
}

最佳答案

这有效.. std::fstream::in | std::fstream::out | std::fstream::out | std::fstream::app .

#include <fstream>
#include <iostream>
using namespace std;

int main(void)
{

char filename[ ] = "Text1.txt";

fstream uidlFile(filename, std::fstream::in | std::fstream::out | std::fstream::app);


if (uidlFile.is_open())
{
uidlFile << filename<<"\n---\n";
uidlFile.close();
}
else
{
cout << "Cannot open file";
}




return 0;
}

关于c++ - 如何使用 fstream 在 C++ 中追加文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23615975/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com