File I/O Functions Part -I

Working with Files in C++ using Classes

C++ provides some useful classes to handle files, including:

  • fstream: combines ofstream and ifstream to create, read, and write to files
  • ofstream: creates and writes to files
  • ifstream: reads from files

To use these classes, one must include the <fstream> header file in their program.

A. Opening a File

To work with files in C++, the first step is to open it. There are two ways to do this:

  • Using the constructor
  • Using the open() member function of the class

A file can be opened for multiple purposes, such as writing to it or reading from it.

Here is an example to demonstrate opening a file using the constructor.

#include <iostream>
#include <fstream>
 
using namespace std;
 
int main()
{
    ofstream out("example.txt");
    out << "Hello, this is a text file.";
    out.close();
    return 0;
}

This is how we use the constructor ofstream to open a file. Another example demonstrates the use of the ifstream constructor.

#include <iostream>
#include <fstream>
 
using namespace std;
 
int main()
{
    ifstream in("example.txt"); 
    return 0;
}

In order to read from a file in C++, the file must already exist and be located in the same directory as the program. A class object is created using the “ifstream” type, which is specifically designed for reading from the file.

B. Closing a File

In C++, it is a good practice to close open files. Failing to do so can result in the file remaining open even after the program is finished using it. Therefore, it is important to manually close the file using the close method.

Syntax:

file_objectname.close();
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in