Dealing with files in C++
File processing inC++
Dealing with files or processing files(Files Handling)It is intended to perform an operation on the files on the user’s computer, such as reading the content of a file and displaying it in the program, creating a copy of it, modifying or deleting its content, whether the file type istxt
, jpg
, mp4
or any other type.
Now, to work with files we must include the package <fstream>
because it contains the classes that are dedicated to that, in addition to the package <iostream>
because we will need it operator <<
when writing to the file.
So these two lines should be written when dealing with files.
#include <iostream> #include <fstream>
Important technical terms
The name of the package
<fstream>
is derived from the phraseFile StreamWhich means that it is intended for handling files.The name of the package
<iostream>
is derived from the phraseInput Output StreamWhich means that it contains input and output commands, whether on the screen or in .
Classes package fstream
inC++
The package <fstream>
contains the following basic classes that can be used to work with files.
Class with its definition | |
---|---|
ofstream
Used to create an object that allows us to create and write to a new file. |
|
ifstream
Used to create an object that allows us to read the content of the file. |
|
fstream
It is used to create an object that allows us to create a new file, write to it and read from it as well. So this class is considered a merging of the class ofstream and the classifstream . |
How to open and close a file inC++
If you want to read or write the content of a file, it must be opened by your program itself to be able to do so.
The three classes ifstream
, ofstream
and fstream
all of them contain a function called open()
that we use to open the file we want to work with.
Function constructionopen()
void open(const char *filename, ios::openmode mode)
Parameter location
filename
We pass the name and path of the file we want to open as plain text.mode
It is an optional parameter that we can pass in place of one or more of the ready-made constants in the classios
to tell the compiler why we want to open the file.
In the following table we put the names of the class constants ios
that you can pass in place of the parametermode
.
hard with its definition | |
---|---|
ios::app
Used to inform the compiler that new content to be added will be placed at the end of the file. |
|
ios::ate
It is used to inform the compiler that the file will be opened for writing and reading, indicating that it will start from the end. |
|
ios::in
Used to notify the compiler that the file will be opened to read from. |
|
ios::out
Used to inform the compiler that the file will be opened for writing. |
|
ios::trunc
Used to tell the translator that if a file already exists, its content will be erased when it is opened. |
When calling the function, open()
you can use the operator |
if you want to pass more than one parameter place value to it mode
as follows.
ofstream myfile; myfile.open ("example.txt", ios::out | ios::app);
Very important technical information
The class
ofstream
uses constantios::out
by default.The class
ifstream
uses constantios::in
by default.The class
fstream
uses constantsios::in | ios::out
by default.
The importance of closing the file when finished in C++
When you finish dealing with any file, close it immediately because this will improve the performance of the program as it will reduce the size of the space reserved for the file in the memory in addition to you being able to deal with this file directly from outside your program.
ifstream
All three classes have ofstream
a fstream
function named that close()
we use to close the file.
So to close the connection with any open file, you must call the function close()
from the object you originally opened the file with.
Checking the state of the object through which we are dealing with the file inC++
When the function is used open()
to open the file, whether for the purpose of reading or writing in it, this may not always work.
For example, if you want to create a new file, you may not have permission to create a file on the computer, or there is not enough space to create the file in it, or the file already exists but is opened by another program. And if you want to read the content of a file on the computer, you may also encounter some problems, such as the path of the file being placed is incorrect, or the file is opened by another program, or you do not have permission to read from it, etc..
After creating the object with which you will deal with the file, you can use conditional statements if
and else
easily as follows to see if you can deal with the file or not.
ofstream myfile; myfile.open ("example.txt"); if (myfile) { // If the connection to the file has no problems, the commands we put here will be executed } else { // If you want to inform the user that there was a problem connecting to the file, you can write it here }
There are 4 ready-made functions that you can use to ensure that the connection to the file is correct and that no problem occurred when dealing with it, whether when reading or writing in it.
Function name and definition | |
---|---|
bool bad()
Used to check if there is any problem reading or writing to a file. Return if there is a problem and return if there is no problem. One of the problems we mean is if you try to write in the file, but there is not enough space for storage, or if you open a file with an object from , but you intend to use it for reading and not for writing. In these cases, you can make use of this function to see if an error occurred or not. true false ofstream |
|
bool fail()
Just like the function bad() , in addition to it checks for problems that may occur when dealing with file content. For example, if you read a number stored in a file and you read it in your program and then treat it as an ordinary number without converting it to a number, you will find that it alerts you about this error as well. Return if there is a problem and return if there is no problem. true false |
|
bool eof()
The name of the function is an abbreviation of a sentenceEnd Of FileIt is used to check whether you have read or written to the end of the file. Returns true if the compiler has reached the end of the file, and returns false if it has yet to reach the end of the file. |
|
bool good()
It is used to find out if there was any problem when dealing with the file and it includes all kinds of problems that may occur. Return if there is no problem and return if there is a problem. true false |
All three classes contain these functions and you will find how to use them later in the examples ifstream
.ofstream
fstream
Comprehensive examples of file handling inC++
How to create a new file on the computer and write to it using a class object ofstream
.
Here we have put an example on how to create a new file on the computer and write to it with a class objectofstream
.
In the following example, we have created a new text file named demo.txt
in the same project we are working on.
Then we make sure that the file has been created successfully and then write two lines inside it.
Example
#include <iostream> #include <fstream> using namespace std; int main() { // because we will use it to create a new file and write in it outfile named ofstream here we have created an object from class ofstream outfile; // and open it "demo.txt" to create a new file called open() here we called the function outfile.open("demo.txt"); // it doesn't have any problems before dealing with it outfile here we made sure that the connection to the file that the object refers to if(outfile) { // outfile Here we have added text in the file the object is pointing to outfile << "This is a line.\n"; outfile << "This is another line.\n"; } // To close the connection with the open file in the outfile of the object close() here we called the function outfile.close(); return 0; }
• When you run the program, a file will be created with its name demo.txt
in the same project we are working in, with the following text inside it.
This is a line. This is another line.
• After we ran the program, we opened the project folder to make sure that the file demo.txt
was actually created in it.
How to read the content of a file on the computer and display it in the program by a class object ifstream
.
Here we have put an example on how to read the content of a file on the computer and display it in the program by a class objectifstream
.
Note: We will read the content of the file we created in the previous example.
In the following example, we have read the content of the file demo.txt
that we created in the previous example in the same project we are working on.
Then we displayed the content of the file in the program, ie in the console.
Example
#include <iostream> #include <fstream> using namespace std; int main() { // Because we will use it to read the content of a file in the computer called ifstream. Here we created an object from the class ifstream file; // "demo.txt" to open the file open() here we called the function infile.open("demo.txt"); // it has no problems before dealing with it infile here we made sure that the connection to the file that the object refers to if(infile) { // We will use this variable to temporarily store each newline we fetch from the file in before it is displayed string line; // line finds a newline, it will put it temporarily in the variable getline() as long as the while function is here for each cycle of the loop while (getline (infile, line)) { // Then we will display it and go down on a new line so that all the content of the file does not appear on one line cout << line << endl; } } // To close the connection with the infile from the close() object, here we called the function infile.close(); return 0; }
• When the program is run, the content of the file will be displayed as demo.txt
follows.
This is a line. This is another line.
How to create a file, write to it, and then read its content with a class object fstream
Here we have put an example on how to create a file, write in it, and then read its content with a class objectfstream
.
In the following example, we have created a new text file named demo.txt
in the same project we are working on.
Then we make sure that the file has been created successfully and then write two lines inside it.
Then we go back to the beginning of the file using the function and seekg()
pass the value 0
to it to refer to the first character in the file.
Then we read the text that we added in the file from it and display it in the program, ie in the console.
Example
#include <iostream> #include <fstream> using namespace std; int main() { // Because we will use it to create a new file and write in it a file named fstream. Here we have created an object from the class fstream file; // and open it "demo.txt" to create a new file called open() here we called the function file.open("demo.txt"); // it has no problems before dealing with it file here we made sure that the connection to the file that the object refers to if(file) { // file Here we have added text in the file that the object refers to file << "This is a line.\n"; file << "This is another line.\n"; // Here we go back to the first file because we will read its content from the beginning file.seekg(0); // We will use this variable to temporarily store each newline we fetch from the file in before it is displayed string line; // line finds a newline, it will put it temporarily in the variable getline() as long as the while function is here for each cycle of the loop while (getline (file, line)) { // Then we will display it and go down on a new line so that all the content of the file does not appear on one line cout << line << endl; } } // To close the connection with the file opened in memory file from the object close() here we called the function file.close(); return 0; }
• When the program is run, the content of the file will be displayed as demo.txt
follows.
This is a line. This is another line.
How to add text at the end of the text in the file by an object of class ofstream
and constant ios::app
.
Here we have put an example on how to add text at the end of the text in the file by an object of class ofstream
and constantios::app
.
Note: When you try to connect to the file, it will not be created again if it was already there.
In the following example, we passed the constant to the ios::app
function open()
to inform the compiler that we want to open a file whose name append.txt
is present in the same project we are working in in order to add text at the end of it, and if it does not exist, we want to create it and open it also for the same purpose.
Then we made sure that the file exists and that there is no problem connecting to it, and then we add a line to the content in it.
Example
#include <iostream> #include <fstream> using namespace std; int main() { // because we will use it to create a new file and write in it outfile named ofstream here we have created an object from class ofstream outfile; // for the ios::app function, and if it does not exist, it will be created and opened because we passed the constant "append.txt" to open a file called open() here we called the function outfile.open("append.txt", ios::app); // it doesn't have any problems before dealing with it outfile here we made sure that the connection to the file that the object refers to if(outfile) { // outfile Here we have added text in the file the object is pointing to outfile << "This is a new line added at the end.\n"; } // To close the connection with the open file in the outfile of the object close() here we called the function outfile.close(); return 0; }
• When you run the program, a file will be created with its name append.txt
in the same project we are working in, with the following text inside it.
This is a new line added at the end.
• Close the file append.txt
if you have opened it, then run the program again and note how the text will be added "This is a new line added at the end."
again at the end of it as follows.
This is a new line added at the end. This is a new line added at the end.
We advise you to close the file append.txt
and change the text we put in the line to 18
any text you want and then run the program to see how the text you wrote will be added at the end of the file.
How to add text in the beginning of the text in the file by an object of class ofstream
and constant ios::app
.
Here we put an example on how to add text in the beginning of the text in the file by an object of class ofstream
and constantios::app
.
Note: When you try to connect to the file, it will not be created again if it was already there.
To add text at the beginning of the file without deleting the rest of the content in it, we must read the content of the file and store it temporarily in a text variable.
Then we delete the original file.
Then we create a new empty file with the same name as the original file.
Finally, we add the new text in the new file, followed by the text that we stored in the variable.
You can do this in another way if you like, since you can create a new file in which you put the text you want to add in the file.
Then you read the content of the original file and add it to it.
In the following example we have implemented the first method that can be used to add text at the beginning of the file.
For this, we created a class object to ifstream
read the content of the original file we want to add text in the beginning of.
And an object from the class ofstream
to create a new file with the same name and add the new text in it, followed by the text that was in the original file.
Example
#include <iostream> #include <fstream> using namespace std; int main() { // Because we will use it to read the content of a file in the computer called ifstream. Here we have created an object from the class // Because we will use it to write in the same outfile named ofstream and we have created an object from the class // We will temporarily place the text we read from the file in the variable data // in it we put the text we intend to add at the beginning of the file on a special line textToAdd variable ifstream file; ofstream outfile; string data; string textToAdd = "This is a new line added at the beginning.\n"; // "prepend.txt" to open a file called open() here we called the function infile.open("prepend.txt"); // it has no problems before dealing with it infile here we made sure that the connection to the file that the object refers to if(infile) { // We will use this variable to temporarily store each newline we fetch from the file in before it is displayed string line; // line finds a newline, it will put it temporarily in the variable getline() as long as the while function is here for each cycle of the loop while (getline (infile, line)) { // data in the variable line Then the line that was temporarily placed in the variable will be added data += line + "\n"; } // data When the loop ends, all of the file's content will have been put into the variable } // To close the connection with the infile from the close() object, here we called the function infile.close(); // replace the old file and open it also "prepend.txt" to create a new file called open() here we called the function outfile.open("prepend.txt"); // it doesn't have any problems before dealing with it outfile here we made sure that the connection to the file that the object refers to if(outfile) { // outfile In the new file that the textToAdd object points to here we have added the text in the variable outfile << textToAdd; // also the outfile we copied from the original file in the file the data object points to then we added the text in the variable outfile << data; } // To close the connection with the open file in the outfile of the object close() here we called the function outfile.close(); return 0; }
• When you run the program, a file will be created with its name prepend.txt
in the same project we are working in, with the following text inside it.
This is a new line added at the beginning.
• Close the file prepend.txt
if you have opened it, then run the program again and note how the text will be added "This is a new line added at the begining."
again in the beginning as follows.
This is a new line added at the beginning. This is a new line added at the beginning.
We advise you to close the file prepend.txt
and change the text we put in the variable to textToAdd
any text you want, and then run the program to see how the text you typed in the beginning of the file will be added.
How to delete a file from the computer using the function remove()
, as well as how to print errors that may occur when trying to delete the file
Here we have put an example on how to delete a file from the computer using the function remove()
as well as how to print errors that may occur when trying to delete the file.
Functionremove()
To delete a file from the computer, we use a ready-made function whose name remove()
is originally in the package <iostream>
and is defined as follows.
int remove(const char* filename)
So when called, we must pass it the name or path of the file we want to delete as a character array or as a pointer to it, so it returns a greater number than 0
if it successfully deleted the file, and if it failed to delete the file for any reason, it returns0
.
So if the function remove()
returns the value 0
then this is proof that it could not delete the file.
In the following example, we tried to delete a file whose name demo.txt
we assume is in the same project we are working on.
Then we print whether the file has been deleted or not.
Example
#include <iostream> using namespace std; int main() { // fileName Here we have stored the name of the file we want to delete in the character array char fileName[] = "demo.txt"; // fileName To try to delete the file whose name is in the array remove() here we called the function // to see if the file has been deleted or not remove() then we check for the value returned by the function if (remove(fileName) != 0) { // If the file is not deleted, the following sentence will be printed, then two syllables on top of each other, and then the reason for the error perror("File deletion failed"); } else { // If the file has not been deleted successfully, the following print command will be executed, which means that the file has been deleted successfully cout << "File deleted successfully"; } return 0; }
• When you run the program, if there is a file in your project, its name demo.txt
will be deleted and the following sentence will be printed.
File deleted successfully
• When you run the program, if there is no file in your project, the demo.txt
following sentence will be printed.
File deletion failed: No such file or directory
How to use the , , and functions to bad()
check the state of the object used to manipulate the filefail()
eof()
good()
Here we have an example of how to use the , , and functions to bad()
check the state of the object used to manipulate the file.fail()
eof()
good()
In the following example, we created an object from the class ifstream
and then tried to use it to read the content of a file nameddemo.txt
.
So here, a problem may occur if there is no file in the project with its name demo.txt
, and a problem will inevitably occur when trying to read the content of the file because the class ifstream
is designed to write in the file and not read from it.
Then we checked the state of the object to see if there was a problem with the file or not.
#include <iostream> #include <fstream> using namespace std; int main() { // Because we will use it to read the content of a file in the computer called ifstream. Here we created an object from the class ifstream file; // Knowing that there is no file with this name in the project "harmash.txt" to open a file named open() here we called the function infile.open("harmash.txt"); // Here it will print whether we have opened the file and read the characters in it to the last character or not if (infile.eof()) { cout << "You reach the end of file.\n"; } else { cout << "You didn't reach the end of file.\n"; } // Any problem that occurred when trying to work with the file will be printed here if (infile.good()) { cout << "No problem happed till now."; } else { // Then two words on top of each other, then the cause of the error "Error" will print the word perror("Error"); } // to close the connection with the file if it was already opened infile from the close() object here we called the function infile.close(); return 0; }
• We will get the following result when running.
You didn't reach the end of file. Error: No such file or directory
How to find out the file size of any type.
Here we have put an example on how to find out the size of a file of any type.
To find out the file size of any type, you need the following:
in totalIndexThe last character in the file is equal to the file size.
To find outIndexThe character that the compiler is currently standing at, we use a ready-made function named
tellg()
.To move from the first letter in the file to the last letter we use the function
seekg(0, ios::end)
.
In the following example, we created an object from the class ifstream
and then tried to use it to read the content of a file nameddemo.txt
.
After making sure that the file is open, we storeIndexThe first letter in the file is in its name variable begin
, and the last letter in the file is in its name variable, end
because by subtracting them from each other, we will know the size of the file.
#include <iostream> #include <fstream> using namespace std; int main() { // the last character in the index file to store the end variable streampos end; // Because we will use it to read the content of a file on the computer myFile called ifstream here we created an object from the class ifstream myFile; // suppose it is in the project "demo.txt" to open a file named open() here we called the function myFile.open("demo.txt"); // it doesn't have any problems before dealing with it myFile Here we made sure that the connection to the file that the object refers to if(myFile) { // its to make the compiler go to the last character in the file ios::end and pass the constant seekg() here we called the function myFile.seekg(0, ios::end); // end The current character that the compiler stands at in memory and then stored in the index variable to store tellg() here we called the function end = myFile.tellg(); // the last character in the file and the output will be the size of the index file here we have printed cout << "Size is: " << end << " bytes."; } else { // Then two words on top of each other, then the cause of the error "Error" If there is an error, the word . will be printed perror("Error"); } // to close the connection with the file if it was already opened myFile from the close() object here we called the function myFile.close(); return 0; }
• When you run the program, if there is a file in your project whose name demo.txt
will be printed as follows, indicating that the file size will be the same as the size of your real file.
Size is: 95 bytes.
• When you run the program, if there is no file in your project, the demo.txt
following sentence will be printed.
Error: No such file or directory
How to create a copy of a non-text file (Binary File) Such as audio files, videos, etc.
Here we put an example on how to create a copy of a non-text file(Binary File)Such as audio files, videos, etc..
Note: We deal with non-text files in a special way.
There are special ways to deal with non-text files, which makes the process of dealing with them faster and more efficient.
So we will not use symbols >>
and <<
or function getline()
when dealing with non-text files.
Now, to read the content of a non-text file we use a ready function named read()
and to write in a non-text file we use a ready function namedwrite()
.
The function
read()
returns you the file's content as a character array.The function
write()
also passes the content you want to write to the file as a character array.
construction of functions read()
andwrite()
:
char* write ( char* memory_block, int size ) char* read ( char* memory_block, int size )
In the following example, we create an object from the class to ifstream
read the content of a file named D:/files/logo.PNG
and then create a copy of it with an object from the class ofstream
named logo-copy.PNG
in the same folder in which the original file is located.
Note: We assumed that on the computer there is a file whose name is logo.PNG
in a folder whose name files
is on the diskD
.
If you are going to try the following code, don't forget to put the path of the file you want to make a copy of correctly for you.
#include <iostream> #include <fstream> using namespace std; int main() { // Mainly because we will use it to reserve space in memory in order to put the content in size Here we have prepared the variable streampos size; // It is an array and we will use it to store the characters we read from the file we want to make a copy of memblock char* memblock; // specifying that we will use it to read the content of a non-text file and make the compiler stop at the last character in it when working with it as well as open it ifstream here we create an object of the class ifstream infile ("D:/files/logo.PNG", ios::in|ios::binary); // specifying that we will use it to create a non-text file and write in it as well as open it ofstream here we have created an object from the class ofstream outfile ("D:/files/logo.PNG", ios::binary|ios::out); // Here we have made sure that both files are open and can be handled if (infile.is_open() && outfile.is_open()) { // its to make the compiler go to the last character in the file ios::end and pass the constant seekg() here we called the function infile.seekg(0, ios::end) // size is the last character in the file because it will represent its size in the index variable here it will be stored size = infile.tellg(); // size in memory specifying that the number of characters we will put in it is equal to the number of characters in the file that we have stored in the variable memblock here we define the creation of the array memblock = new char [size]; // Here we have referenced the first character in the original file so that we can read all its content infile.seekg (0, ios::beg); // memblock Here we have read all the content of the file and stored it in the array infile.read (memblock, size); // outfile In the new file represented by the memblock object here we have written all the content of the array outfile.write(memblock, size); // To close the connection with the files opened in the outfile and infile of the two objects close() here we called the function infile.close(); outfile.close(); } else { // If there is any problem while opening the first file or creating and opening the second file, this sentence will be printed cout << "Operation failed!"; } return 0; }
• When the program is run, a copy of the file will be created if any problem occurs and nothing will be printed in the program.
• When the program is running, if there is a problem with the file paths placed or it cannot be created for any reason, the following sentence will be printed.
Operation failed!
How to save what the user enters into a file.
Here we have put an example on how to save what the user enters into a file.
In the following example, we have created a new text file named data.txt
in the same project we are working on.
Then we made sure that the file was created successfully.
Then we asked the user to enter his name and then we stored the name he entered inside the filedata.txt
.
#include <iostream> #include <fstream> using namespace std; int main() { // because we will use it to create a new file and write in it outfile named ofstream here we have created an object from class ofstream outfile; // to store the name that the user will enter when running name we have prepared the variable string name; // and open it "data.txt" to create a new file called open() here we called the function outfile.open("data.txt"); // it doesn't have any problems before dealing with it outfile here we made sure that the connection to the file that the object refers to if(outfile) { // name here the user will be asked to enter his full name and then the name he enters will be stored in the variable cout << "Enter your name: "; getline(cin, name); // outfile Here we have added text in the file the object is pointing to outfile << name; } // To close the connection with the open file in the outfile of the object close() here we called the function outfile.close(); return 0; }
• We marked the data that we waited for the program to be entered from the keyboard in yellow.
• Open the file data.txt
that was created in the same project you are working on, and you will find that what you entered in it has been saved.
.................................................. ...................