Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append file in c++ using fstream? [duplicate]

Tags:

c++

fstream

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";
    }
}

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

Thank you in advance.

edit:

Here is wider point of view:

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);
}
like image 877
Tomasz Szulc Avatar asked May 12 '14 18:05

Tomasz Szulc


1 Answers

This works.. 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;
}
like image 96
Software_Designer Avatar answered Nov 14 '22 22:11

Software_Designer