如何使用 fstream 在 C++ 中追加文件? [复制]

2023-11-21

我尝试用 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。如何在此文件中正确附加字符串?

先感谢您。

edit:

这是更广泛的观点:

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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 fstream 在 C++ 中追加文件? [复制] 的相关文章

随机推荐