-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; } 
2
  • The file is rewritten every time Commented Jul 10, 2016 at 19:03
  • Simply read the documentation for the functions you use. The documentation is very clear about what they do. -1 Commented Jul 11, 2016 at 0:29

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.