How to Handle File I/O in C++

Most of the times when you are working on a programming project, you have to play with files to get some data or to write some data or readings into the file for later use. All the programming languages provide file input and output capabilities. C++ also have file I/O functionality. It is little tricky to handle but not complex. C++ provides a library called fstream, which handles all the file I/O functions. So you have to add this library in your code to use file I/O functionality. Following is the step by step guide to handle files in C++.

Instructions

  • 1

    “fstream” provides two different functions for file inputs and file outputs. The function which is used to get input from a file is called ifstream, and for the outputs we use ofstream. Both of these functions provide file open and close functions as well.

  • 2

    To open a file for an input use following syntax:


    ifstream filexyz;


    Or alternatively if you know the name of the file use following:


    ifstream filexyz  (name_of_file);


    To read or write any file you have to open it first, for example if you want to open filexyz for input then use following:


    filexyz.open();


    This will open the file for inputs. Once you have done with file operations, you now close the file by using:


    filexyz.close();


    Same is the case with output wp-content/uploads.

  • 3

    Once you are done with creation of wp-content/uploads, you can simply replace cin with file you created and cout with the output file you created for the input and output purpose.

  • 4

    To demonstrate file I/O more effectively, consider following example in which will simply output a string to a file and will also read a string from a file.


    Example:



    # include
    # include
    using namespace std;
    int main( ){
    char   our_str[15]; // create a sequence of characters (a string) with length 15
    ofstream fout (“temporary.txt”); //create a temporary.txt file for outputs.
    fout.open();
    fout<<”these lines will be copied to temporary.txt” temporary.txt
    fout.close(); //close temporary.txt
    ifstream fin(temporary.txt); //open the file temporary.txt to take input from this file
    fin.open();
    ifstream>> our_str; //this will copy a string from temporary.txt to our_str
    cout<< our_str//this will show us what is copied from the file to our_str.
    fin.close(); //close the file
    return 0;
    }



    Implement the above example in your compiler and try to evaluate the output.






Leave a Reply

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


4 × = thirty two