class. It explains the use of ifstream and ofstream for reading and writing files, respectively, and introduces the fstream class for combined operations. Additionally, it covers error checking, file opening and closing procedures, and includes multiple code examples to illustrate these concepts."> class. It explains the use of ifstream and ofstream for reading and writing files, respectively, and introduces the fstream class for combined operations. Additionally, it covers error checking, file opening and closing procedures, and includes multiple code examples to illustrate these concepts.">
[go: up one dir, main page]

0% found this document useful (0 votes)
2 views18 pages

File PGM

The document provides a comprehensive overview of file handling in C++, detailing how to create, read, write, and append to files using the <fstream> class. It explains the use of ifstream and ofstream for reading and writing files, respectively, and introduces the fstream class for combined operations. Additionally, it covers error checking, file opening and closing procedures, and includes multiple code examples to illustrate these concepts.

Uploaded by

suganya.cse
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)
2 views18 pages

File PGM

The document provides a comprehensive overview of file handling in C++, detailing how to create, read, write, and append to files using the <fstream> class. It explains the use of ifstream and ofstream for reading and writing files, respectively, and introduces the fstream class for combined operations. Additionally, it covers error checking, file opening and closing procedures, and includes multiple code examples to illustrate these concepts.

Uploaded by

suganya.cse
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/ 18

C++ File Handling

File handling in C++ is a mechanism to create and perform read/write operations on a file.
We can access various file handling methods in C++ by importing the <fstream> class.
#include <fstream>
<fstream> includes two classes for file handling:
 ifstream - to read from a file.
 ofstream - to create/open and write to a file.
Note: Our online compiler cannot handle file handling right now. So, please install an IDE or
text editor on your computer to run the programs given here.

Opening and Closing a File


In order to work with files, we first need to open them. In C++, we can open a file using
the ofstream and ifstream classes.
For example, here's how we can open a file using ofstream:
std::ofstream my_file("example.txt");
Here,
 my_file - the name of the object of the ofstream class.
 example.txt - the name and extension of the file we want to open.
Note: We can also use the open() function to open a file. For example,
std::ofstream my_file.open("example.txt");
Closing a File
Once we're done working with a file, we need to close it using the close() function.
my_file.close();
Let's take an example program to look at these operations.

Example 1: Opening and Closing a File


#include <iostream>
#include <fstream>

using namespace std;

int main() {

// opening a text file for writing


ofstream my_file("example.txt");

// close the file


my_file.close();

return 0;
}
This code will open and close the file example.txt.
Note: If there's no such file to open, ofstream my_file("example.txt"); will instead create a
new file named example.txt.

Check the File for Errors


In file handling, it's important to ensure the file was opened without any error before we can
perform any further operations on it.There are three common ways to check files for errors:
1. By Checking the File Object
ofstream my_file("example.txt");

// check if the file has been opened properly


if (!my_file) {

// print error message


cout << "Error opening the file." << endl;

// terminate the main() function


return 1;
}
Notice the condition in the if statement:
if (!my_file) {...}
This method checks if the file is in an error state by evaluating the file object itself.
 If the file has been opened successfully, the condition evaluates to true.
 If there's an error, it evaluates to false, and you can handle the error accordingly.
2. Using the is_open() Function
The is_open() function returns
 true - if the file was opened successfully.
 false - if the file failed to open or if it is in a state of error.
For example,
ofstream my_file("example.txt");

if (!my_file.is_open()) {
cout << "Error opening the file." << endl;
return 1;
}
3. Using the fail() Function
The fail() function returns
 true - if the file failed to open or if it is in a state of error.
 false - if the file was opened successfully.
ofstream my_file("example.txt");

if (my_file.fail()) {
cout << "Error opening the file." << endl;
return 1;
}
Note: For simplicity, we recommend using the first method.

Read From a File


Reading from text files is done by opening the file using the ifstream class. For example,
ifstream my_file("example.txt");
Then, we need to read the file line-by-line. To do this, we need to loop through each line of
the file until all the lines are read, i.e., until we reach the end of the file.
We use the eof() function for this purpose, which returns
 true - if the file pointer points to the end of the file
 false - if the file pointer doesn't point to the end of the file
For example,
// variable to store file content
string line;

// loop until the end of the file


while (!my_file.eof()) {

// store the current line of the file


// in the "line" variable
getline(my_file, line);

// print the line variable


cout << line << endl;
}
Here, the while loop will run until the end of the file. In each iteration of the loop,
 getline(my_file, line); reads the current line of the file and stores it in
the line variable.
 Then, it prints the line variable.
Next, let's clarify this with a working example.

Example 2: Read From a File


#include <iostream>
#include <fstream>
using namespace std;
int main() {
// open a text file for reading
ifstream my_file("example.txt");
// check the file for errors
if(!my_file) {
cout << "Error: Unable to open the file." << endl;
return 1;
}
// store the contents of the file in "line" string
string line;
// loop until the end of the text file
while (!my_file.eof()) {
// store the current line of the file
// in the "line" variable
getline(my_file, line);
// print the line variable
cout << line << endl;
}
// close the file
my_file.close();
return 0;
}
Suppose example.txt contains the following text:

Contents of example.txt
Then, our terminal will print the following output:
Hello, World!
How are you?

Write to a File
We use the ofstream class to write to a file. For example,
ofstream my_file("example.txt");
We can then write to the file by using the insertion operator << with
the ofstream object my_file. For example,
#include <iostream>
#include <fstream>

using namespace std;

int main() {

// open a text file for writing


ofstream my_file("example.txt");

// check the file for errors


if(!my_file) {
cout << "Error: Unable to open the file." << endl;
return 1;
}

// write multiple lines to the file


my_file << "Line 1" << endl;
my_file << "Line 2" << endl;
my_file << "Line 3" << endl;

// close the file


my_file.close();

return 0;
}
Notice the following code for writing to the file:
my_file << "Line 1" << endl;
my_file << "Line 2" << endl;
my_file << "Line 3" << endl;
This is similar to printing output to a screen:
cout << "Line1" << endl;
In file handling, we just replace cout with the file object to write to the file instead of the
console.
Our particular code will write the following text to example.txt:
Line1
Line2
Line3
Note: Writing to an existing file will overwrite the existing contents of the file.

Append to a Text File


To add/append to the existing content of a file, you need to open the file in append mode.
In C++, you can achieve this by using the ios::app flag when opening the file:
ofstream my_file("example.txt", ios::app);
Now, let's add some more text to the existing content of example.txt:
#include <iostream>
#include <fstream>

using namespace std;

int main() {

// open a text file for appending


ofstream my_file("example.txt", ios::app);

// if the file doesn't open successfully, print an error message


if(!my_file) {
cout << "Failed to open the file for appending." << endl;
return 1;
}

// append multiple lines to the file


my_file << "Line 4" << endl;
my_file << "Line 5" << endl;

my_file << "Line 6" << endl;

// close the file


my_file.close();

return 0;
}
This will add the following lines to example.txt:
Line 4
Line 5
Line 6

Contents Appended to an Existing File

File Handling With fstream


Instead of using ifstream to read from a file and ofstream to write to the file, we can simply
use the fstream class for all file operations.
The constructor for fstream allows you to specify the file name and the mode for file
operations.
Mode Description

ios::in Opens the file to read (default for ifstream).


ios::out Opens the file to write (default for ofstream).

ios::app Opens the file and appends new content to itat the end.
Let's look at an example:
#include <iostream>
#include <fstream>

using namespace std;

int main() {

// 1. write to a text file


fstream my_file("example.txt", ios::out);

if (my_file) {
my_file << "This is a test line." << endl;
my_file.close();
}
else {
cout << "Unable to open file for writing." << endl;
return 1;
}

// 2. read from the same file


string line;
my_file.open("example.txt", ios::in);

if (my_file) {
while (!my_file.eof()) {
getline(my_file, line);
cout << "Read from file: " << line << endl;
}
my_file.close();
}
else {
cout << "Unable to open file for reading." << endl;
return 1;
}

// 3. append data to the end of the file


my_file.open("example.txt", ios::app);

if (my_file) {
my_file << "This is another test line, appended to the file." << endl;
my_file.close();
}
else {
cout << "Unable to open file for appending." << endl;
return 1;
}

return 0;
}
Output
Read from file: This is a test line.
Read from file:
If we look at the file after running the program, we will find the following contents:

File Handling Using fstream


Note: Using ifstream and ofstream explicitly signifies the intention of reading or writing,
respectively, making the code more readable and less prone to errors. Using fstream for
both might lead to ambiguity or unintended operations if not handled carefully.

Creating a file using file stream


//C++ program to create a file.

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
fstream file; //object of fstream class

//opening file "sample.txt" in out(write) mode


file.open("sample.txt",ios::out);

if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}
cout<<"File created successfully.";

//closing the file


file.close();

return 0;
}
Output
File created successfully.

Program to read text character by character in C++


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

int main() {
char ch;
const char *fileName = "test.txt";

// declare object
ifstream file;

// open file
file.open(fileName, ios::in);
if (!file) {
cout << "Error in opening file!!!" << endl;
return -1; // return from main
}

// read and print file content


while (!file.eof()) {
file >> noskipws >> ch; // reading from file
cout << ch; // printing
}
// close the file
file.close();

return 0;
}
Output
Hello friends, How are you?
I hope you are fine and learning well.
Thanks.

Write and read text in/from file


//C++ program to write and read text in/from file.
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
fstream file; //object of fstream class

//opening file "sample.txt" in out(write) mode


file.open("sample.txt",ios::out);

if(!file)
{
cout<<"Error in creating file!!!"<<endl;
return 0;
}

cout<<"File created successfully."<<endl;


//write text into file
file<<"ABCD.";
//closing the file
file.close();

//again open file in read mode


file.open("sample.txt",ios::in);

if(!file)
{
cout<<"Error in opening file!!!"<<endl;
return 0;
}

//read untill end of file is not found.


char ch; //to read single character
cout<<"File content: ";

while(!file.eof())
{
file>>ch; //read single character from file
cout<<ch;
}

file.close(); //close file

return 0;
}
Output
File created successfully.
File content: ABCD.

Write and read variable's values in the file


//C++ program to write and read values using variables in/from file.
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
char name[30];
int age;
fstream file;

file.open("aaa.txt",ios::out);
if(!file)
{
cout<<"Error in creating file.."<<endl;
return 0;
}
cout<<"\nFile created successfully."<<endl;

//read values from kb


cout<<"Enter your name: ";
cin.getline(name,30);
cout<<"Enter age: ";
cin>>age;
//write into file
file<<name<<" "<<age<<endl;

file.close();
cout<<"\nFile saved and closed succesfully."<<endl;

//re open file in input mode and read data


//open file
file.open("aaa.txt",ios::in);
if(!file){
cout<<"Error in opening file..";
return 0;
}
file>>name;
file>>age;

cout<<"Name: "<<name<<",Age:"<<age<<endl;
return 0;
}
Output
File created successfully.
Enter your name: Mike
Enter age: 21

File saved and closed succesfully.


Name: Mike,Age:21

Write and read object values in the file using read and write function
//C++ program to write and read object using read and write function.
#include <iostream>
#include <fstream>

using namespace std;

//class student to read and write student details


class student
{
private:
char name[30];
int age;
public:
void getData(void)
{ cout<<"Enter name:"; cin.getline(name,30);
cout<<"Enter age:"; cin>>age;
}

void showData(void)
{
cout<<"Name:"<<name<<",Age:"<<age<<endl;
}
};

int main()
{
student s;

ofstream file;

//open file in write mode


file.open("aaa.txt",ios::out);
if(!file)
{
cout<<"Error in creating file.."<<endl;
return 0;
}
cout<<"\nFile created successfully."<<endl;

//write into file


s.getData(); //read from user
file.write((char*)&s,sizeof(s)); //write into file

file.close(); //close the file


cout<<"\nFile saved and closed succesfully."<<endl;

//re open file in input mode and read data


//open file1
ifstream file1;
//again open file in read mode
file1.open("aaa.txt",ios::in);
if(!file1){
cout<<"Error in opening file..";
return 0;
}
//read data from file
file1.read((char*)&s,sizeof(s));

//display data on monitor


s.showData();
//close the file
file1.close();

return 0;
}
Output
File created successfully.
Enter name:Mike
Enter age:21

File saved and closed succesfully.


Name:Mike,Age:21

C++ program to demonstrate example of tellg and tellp – tellg() and tellp() function
example in c++ programming language.
tellg() and tellp() example in c++
//C++ program to demonstrate example of tellg() and tellp() function.

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

int main()
{
fstream file;
//open file sample.txt in and Write mode
file.open("sample.txt",ios::out);
if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}
//write A to Z
file<<"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//print the position
cout<<"Current position is: "<<file.tellp()<<endl;
file.close();

//again open file in read mode


file.open("sample.txt",ios::in);
if(!file)
{
cout<<"Error in opening file!!!";
return 0;
}
cout<<"After opening file position is: "<<file.tellg()<<endl;

//read characters untill end of file is not found


char ch;
while(!file.eof())
{
cout<<"At position : "<<file.tellg(); //current position
file>>ch; //read character from file
cout<<" Character \""<<ch<<"\""<<endl;
}

//close the file


file.close();
return 0;
}
Output
Current position is: 26
After opening file position is: 0
At position : 0 Character "A"
At position : 1 Character "B"
At position : 2 Character "C"
At position : 3 Character "D"
At position : 4 Character "E"
At position : 5 Character "F"
At position : 6 Character "G"
At position : 7 Character "H"
At position : 8 Character "I"
At position : 9 Character "J"
At position : 10 Character "K"
At position : 11 Character "L"
At position : 12 Character "M"
At position : 13 Character "N"
At position : 14 Character "O"
At position : 15 Character "P"
At position : 16 Character "Q"
At position : 17 Character "R"
At position : 18 Character "S"
At position : 19 Character "T"
At position : 20 Character "U"
At position : 21 Character "V"
At position : 22 Character "W"
At position : 23 Character "X"
At position : 24 Character "Y"
At position : 25 Character "Z"

C++ tellg(), seekg() and seekp() Functions


tellg(), seekg() and seekp() functions are used to set/get the position of get and put pointers
in a file while reading and writing.
Syntaxes
// tellg()
streampos tellg();

// seekg()
istream& seekg (streampos pos);
istream& seekg (streamoff off, ios_base::seekdir way);

// seekp()
stream& seekp (streampos pos);
ostream& seekp (streamoff off, ios_base::seekdir way);
Parameters
 pos – represents the new absolute position within the stream (from the beginning).
 off – represents the offset to seek.
 pos – represents the following constants,
o ios_base::beg / ios::beg – beginning of the stream.
o ios_base::cur / ios::cur – current position in the stream.
o ios_base::end / ios::end – end the stream.
C++ example of tellg(), seekg(), and seekp() functions
In the below program, we are using a file 'my.txt', the file contains the following text,
File: my.txt
IncludeHelp is specially designed to provide help to students,
working professionals and job seekers
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
fstream F;
// opening a file in input and output mode
F.open("my.txt", ios::in | ios::out);

// getting current location


cout << F.tellg() << endl;

// seeing 8 bytes/characters
F.seekg(8, ios::beg);
// now, getting the current location
cout << F.tellg() << endl;
// extracting one character from current location
char c = F.get();
// printing the character
cout << c << endl;

// after getting the character,


// getting current location
cout << F.tellg() << endl;
// now, seeking 10 more bytes/characters
F.seekg(10, ios::cur);
// now, getting current location
cout << F.tellg() << endl;
// again, extracing the one character from current location
c = F.get();
// printing the character
cout << c << endl;

// after getting the character,


// getting current location
cout << F.tellg() << endl;
// again, seeking 7 bytes/characters from beginning
F.seekp(7, ios::beg);
// writting a character 'Z' at current location
F.put('Z');
// now, seeking back 7 bytes/characters from the end
F.seekg(-7, ios::end);
// now, printing the current location
cout << "End:" << F.tellg() << endl;
// extracting one character from current location
c = F.get();
// printing the character
cout << c << endl;

// closing the file


F.close();
return 0;
}
Output
0
8
e
9
19
i
20
End:93
s

C++ program to read integers from a text file with ifstream


Below is an example of reading integers from a text file with C++ ifstream.
#include <fstream>
#include<iostream>
using namespace std;

int main() {
// Let, create an array to store
// integers
int int_arr[30];

// Open file through ifstream


ifstream ifs("file.txt");

int count = 0; // counter variable


int x; // variable to store the value

// read the valye


while (ifs >> x)
// Assign it into the array
int_arr[count++] = x;

// Print the stored array of integers


cout << "The integers in the file are:" << "\n";
for (int i = 0; i < count; i++) {
cout << int_arr[i] << ' ';
}

//close the file


ifs.close();
}
File
file.txt contains the following data:
10 20 30 40 50 60
Output
The output of the above program is:
The integers in the file are:
10 20 30 40 50 60

You might also like