如何使用fstream在c ++中附加文件? [英] How to append file in c++ using fstream?

查看:64
本文介绍了如何使用fstream在c ++中附加文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to append file in C++. At start file doesn't exists. After operations there is only one line in file instead of five (5 calls of this method). It looks like file is creating, next every write operation file is cleaned out and new string is added.

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 .如何在此文件中正确附加字符串?

I tried with fstream::in ,fstream::out. How to append string correctly in this file?

谢谢.

这里是更广泛的观点:

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在c ++中附加文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆