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.">
File PGM
File PGM
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.
int main() {
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.
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.
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>
int main() {
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.
int main() {
return 0;
}
This will add the following lines to example.txt:
Line 4
Line 5
Line 6
ios::app Opens the file and appends new content to itat the end.
Let's look at an example:
#include <iostream>
#include <fstream>
int main() {
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;
}
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;
}
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:
#include <iostream>
#include <fstream>
int main()
{
fstream file; //object of fstream class
if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}
cout<<"File created successfully.";
return 0;
}
Output
File created successfully.
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
}
return 0;
}
Output
Hello friends, How are you?
I hope you are fine and learning well.
Thanks.
int main()
{
fstream file; //object of fstream class
if(!file)
{
cout<<"Error in creating file!!!"<<endl;
return 0;
}
if(!file)
{
cout<<"Error in opening file!!!"<<endl;
return 0;
}
while(!file.eof())
{
file>>ch; //read single character from file
cout<<ch;
}
return 0;
}
Output
File created successfully.
File content: ABCD.
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;
file.close();
cout<<"\nFile saved and closed succesfully."<<endl;
cout<<"Name: "<<name<<",Age:"<<age<<endl;
return 0;
}
Output
File created successfully.
Enter your name: Mike
Enter 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>
void showData(void)
{
cout<<"Name:"<<name<<",Age:"<<age<<endl;
}
};
int main()
{
student s;
ofstream file;
return 0;
}
Output
File created successfully.
Enter name:Mike
Enter 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();
// 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);
// 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;
int main() {
// Let, create an array to store
// integers
int int_arr[30];