Category: C++ File Handling

https://zain.sweetdishy.com/wp-content/uploads/2026/02/File-Handling-1.png

  • C++ Reading From File

    File I/O (Input/Output) in C++ is the process of reading and writing to files. C++ provides this for handling files through the standard library with <fstream> header file. File I/O allows programs to persist data, interact with external resources, and store/retrieve information beyond the scope of program execution.

    Types of File Streams

    There are three primary types of file streams, where each is associated with different operations −

    • ifstream (Input File Stream) − This is used for reading data from a file.
    • ofstream (Output File Stream) − This is used for writing data to a file.
    • fstream (File Stream) − This is used for both input and output operations on a file. It combines the functionality of both ifstream and ofstream.

    Basic Steps in File I/O

    Heres the given basic steps in file I/O −

    Opening a File

    Before reading or writing to a file, it must be opened using one of the file stream classes. If the file is successfully opened, the program will proceed with I/O operations.

    Performing File Operations

    You can read from or write to a file using the appropriate methods.

    Closing the File

    After the file operations are completed, you should close the file to make sure that all data is flushed and the file is properly released.

    Reading with ifstream (Stream Extraction Operator)

    Using stream extraction operator (>>) is the simplest way to read data from a file in C++. This operator reads formatted data from a file, similar to how data is read from standard input.

    Example

    Heres the given example for Reading with ifstream −

    #include <fstream>#include <iostream>#include <string>intmain(){
       std::ifstream inputFile("example.txt");// Open the file for readingif(!inputFile){
          std::cerr <<"Error opening file!"<< std::endl;return1;}
    
       std::string word;while(inputFile >> word){// Reads until a whitespace is encountered
          std::cout << word << std::endl;// Print each word from the file}
    
       inputFile.close();// Close the file when donereturn0;}

    Here, The >> operator reads data word by word, stopping at whitespace (spaces, newlines, etc.).

    But it doesn’t handle reading lines of text (as it stops at whitespace), and it can be tricky for reading complex data formats (like lines containing spaces).

    Using getline() to Read Lines

    If you want to read an entire line or text, including steps you can use the getline() function. This function will read characters from the file until a newline character (‘\n’) is encountered.

    Example

    Heres the given example for using getline() to read lines −

    #include <fstream>#include <iostream>#include <string>intmain(){
       std::ifstream inputFile("example.txt");// Open the file for readingif(!inputFile){
          std::cerr <<"Error opening file!"<< std::endl;return1;}
    
       std::string line;while(std::getline(inputFile, line)){// Read a full line of text
          std::cout << line << std::endl;// Output the line to the console}
    
       inputFile.close();// Close the file when donereturn0;}

    Reading Binary Files (using read())

    The above discussed methods are for text files, for binary files you can use the read() function to read raw binary data from a file.

    Example

    Heres the given example for Reading Binary Files (using read()) −

    #include <iostream>#include <fstream>intmain(){
       std::ifstream file("example.bin", std::ios::binary);// Check if the file was successfully openedif(!file){
          std::cerr <<"Error opening file!"<< std::endl;return1;}// Get the length of the file
       file.seekg(0, std::ios::end);
       std::streamsize size = file.tellg();
       file.seekg(0, std::ios::beg);// Read the entire file content into a bufferchar* buffer =newchar[size];
       file.read(buffer, size);// Print raw data (optional, for demonstration)for(std::streamsize i =0; i < size;++i){
          std::cout << std::hex <<(0xFF& buffer[i])<<" ";// Print byte in hex}delete[] buffer;
       file.close();return0;}

    Handling Errors in File I/O

    Handling errors is important to ensure that your program behaves correctly when files are not available, can’t be opened, or when unexpected conditions occur during reading/writing.

    Checking for Errors with fail()eof(), and good().

    C++ provides several member functions of the ifstream/ofstream objects to check for various conditions.

    • fail(): Checks if a non-recoverable error occurred during I/O.
    • eof(): Checks if the end of file (EOF) was reached.
    • good(): Returns true if no error has occurred.

    Handling End-of-File (EOF)

    When reading from a file, it’s important to handle the case when you reach the end of the file. The standard approach is to use eof() or std::getline() operators, which automatically stop when the end of the file is reached.

    Handling I/O Errors Gracefully

    During file operations, you should check for fail() or bad() states to detect errors like unexpected end-of-file or data corruption.

  • C++ Files and Streams

    So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output respectively.

    This tutorial will teach you how to read and write from a file. This requires another standard C++ library called fstream, which defines three new data types −

    Sr.NoData Type & Description
    1ofstreamThis data type represents the output file stream and is used to create files and to write information to files.
    2ifstreamThis data type represents the input file stream and is used to read information from files.
    3fstreamThis data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.

    To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.

    Opening a File

    A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only.

    Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.

    voidopen(constchar*filename, ios::openmode mode);

    Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened.

    Sr.NoMode Flag & Description
    1ios::appAppend mode. All output to that file to be appended to the end.
    2ios::ateOpen a file for output and move the read/write control to the end of the file.
    3ios::inOpen a file for reading.
    4ios::outOpen a file for writing.
    5ios::truncIf the file already exists, its contents will be truncated before opening the file.

    You can combine two or more of these values by ORing them together. For example if you want to open a file in write mode and want to truncate it in case that already exists, following will be the syntax −

    ofstream outfile;
    outfile.open("file.dat", ios::out | ios::trunc );

    Similar way, you can open a file for reading and writing purpose as follows −

    fstream  afile;
    afile.open("file.dat", ios::out | ios::in );

    Closing a File

    When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination.

    Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.

    voidclose();

    Writing to a File

    While doing C++ programming, you write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object instead of the cout object.

    Reading from a File

    You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object.

    Read and Write Example

    Following is the C++ program which opens a file in reading and writing mode. After writing information entered by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen −

    #include <fstream>#include <iostream>usingnamespace std;intmain(){char data[100];// open a file in write mode.
       ofstream outfile;
       outfile.open("afile.dat");
    
       cout <<"Writing to the file"<< endl;
       cout <<"Enter your name: "; 
       cin.getline(data,100);// write inputted data into the file.
       outfile << data << endl;
    
       cout <<"Enter your age: "; 
       cin >> data;
       cin.ignore();// again write inputted data into the file.
       outfile << data << endl;// close the opened file.
       outfile.close();// open a file in read mode.
       ifstream infile; 
       infile.open("afile.dat"); 
     
       cout <<"Reading from the file"<< endl; 
       infile >> data;// write the data at the screen.
       cout << data << endl;// again read the data from the file and display it.
       infile >> data; 
       cout << data << endl;// close the opened file.
       infile.close();return0;}

    When the above code is compiled and executed, it produces the following sample input and output −

    $./a.out
    Writing to the file
    Enter your name: Zara
    Enter your age: 9
    Reading from the file
    Zara
    9
    

    Above examples make use of additional functions from cin object, like getline() function to read the line from outside and ignore() function to ignore the extra characters left by previous read statement.

    File Position Pointers

    Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg (“seek get”) for istream and seekp (“seek put”) for ostream.

    The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to the end of a stream.

    The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file’s starting location. Some examples of positioning the “get” file-position pointer are −

    // position to the nth byte of fileObject (assumes ios::beg) fileObject.seekg( n ); // position n bytes forward in fileObject fileObject.seekg( n, ios::cur ); // position n bytes back from end of fileObject fileObject.seekg( n, ios::end ); // position at end of fileObject fileObject.seekg( 0, ios::end );