我尝试在C++中附加文件。起始文件不存在。操作完成后,文件中只有一行,而不是5行(此方法的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);
}发布于 2014-05-13 03:12:20
这行得通..std::fstream::in | 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;
}发布于 2014-05-13 02:43:40
看起来这个问题已经在over yonder上得到了回答。
试一试:
fstream uidFile(uidFilename, fstream::out | fstream:: app | fstream::ate);编辑:
我写了这段代码,并在Windows7 x64上的Visual Studio2012中编译了它。它非常适合我。看起来另一个答案对你有效,但如果这个也有效,请让我知道。
#include <iostream>
#include <fstream>
using namespace std;
void save(char * string)
{
fstream myFile("test.txt", fstream::out | fstream::app);
if(myFile.is_open())
{
myFile.write(string, 100);
myFile << "\n";
}
else
{
cout << "Error writing to file";
}
}
int main()
{
char string[100] = {};
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 100; j++)
{
string[j] = i + 48; //48 is the ASCII value for zero
}
save(string);
}
cin >> string[0]; //Pause
return 0;
}https://stackoverflow.com/questions/23615975
复制相似问题