如何在c++中使用fstream附加文件
How to append file in c++ using fstream?
我尝试在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::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;
}
看起来这个问题在那边已经有答案了。
试一试:
fstream uidFile(uidFilename, fstream::out | fstream:: app | fstream::ate);
编辑:我写了这段代码,并在Windows 7 x64上的Visual Studio 2012中编译。这对我来说非常有效。看起来另一个答案对你有效,但请让我知道这个是否也有效。
#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;
}
相关文章:
- 使用fstream对txt文件中的数字进行循环
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- 使 std::fstream 写入文件末尾,但从头开始读取
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- 如何检查文件是否已存在于 fstream C++中
- 使用 fstream 库并在屏幕上打印的文件有问题?
- Windows std::fstream 修改文件后打开()?
- 如何删除文件中的数字,通过 c++ fstream 的
- 如何使用单个fstream创建、读取和写入文件
- 变量 std::fstream 文件具有初始值设定项,但类型不完整 编译错误
- STD :: FSTREAM文件处理重复使用的问题
- 如何通过C++将 fstream 文件放入头文件中
- 您可以使用指针指向FSTREAM文件吗?
- 可移植fstream文件路径的正确语法是什么
- 保存系统未打开fstream文件
- 无法写入 fstream 文件
- 是否有可能通过使用openMP在fstream(文件读取)上获得一些性能提升
- Fstream文件正在被重写
- 根据ID/Registration搜索和编辑.txt fstream文件