I have the following program and it works but when i try to append to the file, it will not do it. Can anyone help,

Thank you

GCard

#include <fstream>
#include <iostream>
using namespace std;
int main() 
    {
    char buffer[256];
    // open it for output then write to it
    fstream myfile;
    myfile.open("test3.txt",ios::out | ios::trunc);
    if (myfile.is_open())
      {
       myfile << "This outputting a line.\n";
       myfile.close();
    }
    // open it for input and read in
    myfile.open("test3.txt",ios::in);
    myfile.getline(buffer,100);
    cout << "The file contains   " << buffer << "\n";
    myfile.close();
    cout << "Click to continue";
    cin.get();
    //open for appending and append
    myfile.open("test3.txt",ios::app);
    myfile << " Hey this is another line \n";
    myfile.close();
    // open for input and print to screen
    // open it for input and read in
    myfile.open("test3.txt",ios::in);
    myfile.getline(buffer,300);
    cout << "The file contains   " << buffer << "\n";
    myfile.close();
    cout << "Click to continue";
    cin.get();
    return 0;
}// end of main

>but when i try to append to the file, it will not do it
Won't do what? Append to the file at all? Or it won't print the second line?

your program is working correctly, and is doing exactly what you told it to. The second line of text is written to the file, as you'd see if you opened the file in an editor.

Here's what's confusing you:

myfile.getline(buffer,300);

Remember that getline reads into buffer, up to 300-1 characters, or until a newline is encountered. So, your reading step is only showing you the first line of the file. To read all the file, you need to loop through the file.

your program is working correctly, and is doing exactly what you told it to. The second line of text is written to the file, as you'd see if you opened the file in an editor.

Here's what's confusing you:

myfile.getline(buffer,300);

Remember that getline reads into buffer, up to 300-1 characters, or until a newline is encountered. So, your reading step is only showing you the first line of the file. To read all the file, you need to loop through the file.

But it does not appear to be appending to my program, why is that ?

As I said previously, the data IS being appended to the file. Your code for displaying it, however, only reads the first line of the file.
You need to read multiple and display multiple times to see all the data that's been put in the file.

This article has been dead for over six months. Start a new discussion instead.