-1

Help please, code execution outputs instead of

123456

just

456

Why the file is cleared before writing? Trunc not set

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ofstream a{ "1.txt",ios_base::ate };
    a << "123";
    a.close();
    ofstream b{ "1.txt",ios_base::ate };
    b << "456";
    b.close();
    ifstream c{ "1.txt" };
    string str;
    c >> str;
    cout << str;
    return 0;
}
Dekel
  • 60,707
  • 10
  • 101
  • 129

2 Answers2

0

You need to use app in your second writer to append the content to the file instead of rewritting it, as follows:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ofstream a{ "1.txt",ios_base::ate };
    a << "123";
    a.close();
    ofstream b{ "1.txt",ios_base::app }; //notice here is app instead of ate
    b << "456";
    b.close();
    ifstream c{ "1.txt" };
    string str;
    c >> str;
    cout << str;
    return 0;
}

As in this question :

std::ios_base::ate does NOT imply std::ios_base::app

So if you use ate it does not mean that it will append the content to the file.

Community
  • 1
  • 1
meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
0

You can find the different between ios_base:ate and ios_base:app here

For your code, you can change it like this:

ofstream b {"1.txt", ios_base:app};
Community
  • 1
  • 1
GAVD
  • 1,977
  • 3
  • 22
  • 40