Files Handling in C++ - ProgrammerTech
Language:

Search

Files Handling in C++

  • Share this:
Files Handling in C++

Files Handling in C++

Files are meant to process files, and they are media for storing data to be overwritten.

And this data is saved inside it or a processing of the data on the computer is carried out, such as reading from the file, writing to a file, or taking a second copy of it.

We will explain how to deal with files in terms of reading and writing.

In order to open a file, we must specify the path and extension of this file, and when we open this file, we must tell the program that we want to read from this file, write, or both.

In order to work with the files we must include the <fstream> package because it contains the classes for that.

In addition to the <iostream> package because we will need the >> operator from it when writing to the file.

 

fstream package explained

When dealing with files, we must use the fstream library for dealing with files, and it means the file stream, that is, dealing with files.

In addition to the iostream library, it means the Input Output Stream that we always use at the beginning of the program, which contains the input and output commands.

 

Classes derived from the fstream . package

  1. ofstream class for creating an object, creating a new file, and then writing to this file.
  2. The ifstream class enables us to create an object and read from a file from within the editor via the console's output screen.
  3. The fstream class enables us to create a new file and to read and write from the file, and it is considered to be a combination of the previous classes of ofstream and ifstream.

These classes contain an open function () and a close () function.

 

Creating and writing a file in C++

example 1

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ofstream first_file;
    first_file.open("/home/data/Desktop/tech1.txt");
    first_file << "welcome in website programmer tech";
    first_file.close();
    return 0;
}

At the beginning of this program we called the iostream library and the fstream library for handling files.

We defined the program that we want to use the ofstream class to create a file and write to it, and the object we created is first_file. We will use this derived object to create a file and write to it.

In the next line, we put the object at the beginning and with it the open function in order to open the file, then we specified the path, name, and format of this file, txt, any text file.

Then, using the object, we wrote a statement to add to the text file that it will create when the program runs.

Then we closed the program via the close command, using the object for this command.

And when the code is executed, we will get the following result.

1-10.webp

 

We note that a new file has been created on the desktop with the name tech1 and its .txt format. When we open this file, we will find the sentence that we added to it a while ago in the editor.

In this case, any word that we add through the editor will delete the old word in the text file. And in its place becomes the word we have just written.

Here we do not want to delete what already exists, we want it to remain.

We will solve this problem with the following example using the parameter ios::app.

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ofstream first_file;
    first_file.open("/home/data/Desktop/tech1.txt",ios::app);
    first_file << "welcome in website programmer tech";
    first_file.close();
    return 0;
}

We note here that we have added the parameter ios::app in order to tell the editor that we want to add this talk to the text file and not delete and replace what is inside the file.

And when running it will be in the form.

2-10.webp

 

When executing the previous program, it added what we wrote to the text file and did not replace it.

 

Read the content of a file and display it in the program

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ifstream first_file;
    first_file.open("/home/data/Desktop/tech1.txt");
    cout << first_file.rdbuf();
    first_file.close();
    system("pause");
    return 0;
}

At the beginning of this program we called the iostream library and the fstream library for handling files.

We then tell the program that we want to use the ifstream class to read from the file through the console's output window.

The object we created is first_file. We will use this derived object to read from the file.

In the next line, we put the object at the beginning and with it the open function in order to open a file, then we specified the path, name, and format of this file, txt, any text file.

And we used the cout function to print what we want on the output screen and we used the rdbuf function.

Then we closed the file using close and then we used the word pause in order to suspend the execution screen when it was opened.

And when you use the execution command of the previous code, the result will be.

3-10.webp

 

We also noticed that we read everything inside the specified file via the console output window with ease.

 

Create a file, write to it, read and display its content

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    fstream first_file;
    first_file.open("/home/data/Desktop/tech1.txt",ios::out|ios::app);
    first_file << "\n saja";
    first_file.close();
    system("pause");
    return 0;
}

We use the fstream class and the first_file object is the object we will use to handle the file.

We use the open function to open the file, specify the file path, and use the ios::out constant of the ios parameter. It is used to tell the editor's interpreter that we are going to open the file for writing. And we put | It means the boolean function or then we used the constant ios::app which tells the interpreter that every new we write will be added at the end of the file.

After that we wrote the name saja in order to add it in a new line in the file and we closed the file via close.

When running we will find the result.

4-12.webp

 

We have added the word saja in a new line of this file.

 

Save what the user enters through the program in a file

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ofstream outfile;
    string name;
    outfile.open("/home/data/Desktop/tech11.txt");
    if(outfile)
    {
        cout << "Enter your name: ";
        getline(cin, name);
        outfile << name;
    }
    outfile.close();
    return 0;
}

We created an object from the ofstream class and the object is an outfile because this object we will use to create the file and make the user write with it.

And we created a text variable called name in order to store what the user enters into it.

We called the open() function to create a new file named tech11 within the specified path to save and open.

And we made sure that the connection to the file that the outfile object refers to has no problems before dealing with it.

Then we asked the user to enter the name, and when he enters it, it will be stored inside the variable name.

And finally we close the open file in memory with close().

 

Delete a file from the computer using the remove() function

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    char fileName[] = "saja.txt";
    if (remove(fileName) == 0)
    {
        cout << "File deleted successfully";
    }    
    else
    {
        perror("File deletion failed");
    }
    return 0;
}

We created a char array in which we stored the name of the file we want to delete, which is saja.txt.

We called the remove() function in order to try to delete the file from the given array.

And we set conditions. In the event of deleting the file, it prints the sentence “The file has been deleted.”.


Muhammad Alush

Muhammad Alush

إسمي محمد تركي العلوش من سورية من ريف حلب الشرقي 1994, محب للتقنية و التعلم الذاتي, و جميع خبراتي تعلمتها ذاتياً, و اللغات البرمجية التي أتقنها هي html, css, javascript, php, c, python بالإضافة إلى حبي الكبير لمجال الشبكات.

موقعي programmer-tech.com