Appending A File
Appending A File
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream fout("abc.txt", ios::app); // Open file for appending data
string data;
cout << "Enter data to append to file: ";
getline(cin, data); // Get input from user
return 0;
}
Explanation:
<fstream>: This header is included to handle file operations in C++.
using namespace std;: This allows you to use standard library objects
like cout, cin, etc., without prefixing std::.
fstream fout("abc.txt", ios::app);: Opens the file abc.txt in append
mode (ios::app). If the file doesn't exist, it will be created.
ios (which stands for "input/output stream") is a base class that provides
several modes for opening and manipulating files. These modes
determine how the file will be accessed (read, write, append, etc.).
ios::app: The app stands for "append." It means that when the file is
opened, the program will start writing data at the end of the file,
preserving any existing content. If the file doesn't exist, it will be created.
if (fout.is_open()): Checks if the file was successfully opened.
getline(cin, data);: Reads an entire line from user input into the data
variable.
fout << data << endl;: Appends the user input to the file.
This line is used to append (write) the content of the data variable (which
contains user input) to the file.
fout.close();: Closes the file once data has been appended.