如何在c++中使用fstream附加文件

How to append file in c++ using fstream?

本文关键字:fstream 文件 c++      更新时间:2023-10-16

我尝试在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;
}