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

时间:2014-05-12 18:14:35

标签: c++ 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);
}

2 个答案:

答案 0 :(得分:3)

这有效.. 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;
}

答案 1 :(得分:0)

看起来这个问题已经回答over yonder

试一试:

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