0% found this document useful (0 votes)
18 views2 pages

Appending A File

code

Uploaded by

Shivam Gauns
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views2 pages

Appending A File

code

Uploaded by

Shivam Gauns
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Appending a File

#include <iostream>
#include <fstream>
using namespace std;

int main() {
fstream fout("abc.txt", ios::app); // Open file for appending data

// Check if the file opened successfully


if (fout.is_open()) {
cout << "File opened successfully!" << endl;

string data;
cout << "Enter data to append to file: ";
getline(cin, data); // Get input from user

fout << data << endl; // Write data to the file


cout << "Data appended successfully!" << endl;

fout.close(); // Close the file


} else {
cout << "File could not be opened!" << endl;
}

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.

You might also like