3

How can you open a text file and append all its lines to another text file in C++? I find mostly solutions for separate reading from a file to a string, and writing from a string to a file. Can this elegantly be combined?

It is not always given that both files exist. There should be a bool return when accessing each of the files.

I'm sorry if this is already off-topic: Is appending text content to a file conflict-free in the meaning that multiple programs can do this simultaneously (the order of the lines DOESN'T matter) ? If not, what would be an (atomic) alternative?

fotinsky
  • 972
  • 2
  • 10
  • 25
  • possible duplicate of [Appending a new line in a file(log file) in c++](http://stackoverflow.com/questions/10071137/appending-a-new-line-in-a-filelog-file-in-c) – KevinDTimm Oct 29 '13 at 17:24
  • @Kevin: That question doesn't appear to address multiple simultaneous writers. – Ben Voigt Oct 29 '13 at 18:16
  • From what I tested there are no conflicts. I mark this thread as answered. – fotinsky Nov 02 '13 at 00:05

2 Answers2

8

I can only speak for opening a file and appending it to another file:

std::ifstream ifile("first_file.txt");
std::ofstream ofile("second_file.txt", std::ios::app);

//check to see that the input file exists:
if (!ifile.is_open()) {
    //file not open (i.e. not found, access denied, etc). Print an error message or do something else...
}
//check to see that the output file exists:
else if (!ofile.is_open()) {
    //file not open (i.e. not created, access denied, etc). Print an error message or do something else...
}
else {
    ofile << ifile.rdbuf();
    //then add more lines to the file if need be...
}

REFERENCES:

http://www.cplusplus.com/doc/tutorial/files/

https://stackoverflow.com/a/10195497/866930

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
jrd1
  • 10,358
  • 4
  • 34
  • 51
1
std::ifstream in("in.txt");
std::ofstream out("out.txt", std::ios_base::out | std::ios_base::app);

for (std::string str; std::getline(in, str); )
{
    out << str;
}
David G
  • 94,763
  • 41
  • 167
  • 253