Site icon T4Tutorials.com

File Handling using File Streams in C++

File Handling using File Streams in C++

Files are the medium for storing the data and information. We can define the Streams as a sequence of bytes(8bits=1byte). To store the data permanently,  we use the files and use these data to read or write in the form of I/O operations by transferring bytes of data. when we use the File Streams, then We use the header file <fstream>.

Let’s see some other header files related to File Streams.

File Handling Operations:

How to Create/open a File in C++?

The Syntax for file creation in filestreams: FilePointer.open(“Path”,ios::mode);

#include<iostream>
#include<conio.h>
#include <fstream>
using namespace std;
int main()
{
    fstream T4T; // Step 1: Creating object of fstream class
    T4T.open("D:\T4Tutorials.txt",ios::out);  // Step 2: Creating new file
    if(!T4T) // Step 3: Checking whether file exist
    {
        cout<<"File creation failed";
    }
    else
    {
        cout<<"New file created";
        T4T.close(); // Step 4: Closing file
    }
    getch();
    return 0;
}

How to Write a File in C++?

#include <iostream>
#include<conio.h>
#include <fstream>

using namespace std;

int main()
{
    fstream T4T; // Step 1: Creating object of fstream class
    T4T.open("D:\T4Tutorials.txt",ios::out);  // Step 2: Creating new file
    if(!T4T) // Step 3: Checking whether file exist
    {
        cout<<"File creation failed";
    }
    else
    {
        cout<<"New file created";
        T4T<<"Hello";    // Step 4: Writing to file
        T4T.close(); // Step 5: Closing file
    }
    getch();
    return 0;
}

How to Read a File in C++?

#include <iostream>
#include<conio.h>
#include <fstream>

using namespace std;

int main()
{
    fstream T4T; // step 1: Creating object of fstream class
    T4T.open("D:\T4Tutorials.txt",ios::in);   // Step 2: Creating new file
    if(!T4T) // Step 3: Checking whether file exist
    {
        cout<<"No such file";
    }
    else
    {
        char ch;
        while (!T4T.eof())
        {
            T4T >>ch;  // Step 4: Reading from file
            cout << ch;   // Message Read from file
        }
        T4T.close(); // Step 5: Closing file
    }
    getch();
    return 0;
}

How to Close a File in C++?

#include <iostream>
#include<conio.h>
#include <fstream>

using namespace std;

int main()
{
    fstream T4T; // Step 1: Creating object of fstream class
    T4T.open("D:\T4Tutorials.txt",ios::out);  // Step 2: Creating new file
    T4T.close(); // Step 4: Closing file
    getch();
    return 0;
}
Exit mobile version