The Best Way to Handle Files
The steps below must be taken to handle files:
- Give a name to file
- Open a file.
- Enter information into the file.
- Take data out of the file.
- Shut down a file.
Streams in C++
We provide input to the source code and the existing code returns the output. The term “stream” refers to both the stream of bytes that are provided to the main program as input and the series of bytes that have been returned by the source code. In other words, streams are more than just a succession of data flowing.
“Console Input and output operation” refers to the input and output between the program that is running and the input and output devices, such as the keyboard and monitor. “Disk Input and output operation” refers to the outputs and inputs between both the currently running software and files.
File Stream Procedures Classes
A collection of classes in the C++ Input and output modules specify the file handling techniques. It would contain the classes’ ifstream, ofstream, and fstream. Such classes are descended from the fstream class and its related iostream class. Any application that utilizes files should include the fstream file since it contains the declarations for the classes used to handle the storage files.
ios
This category is the main module for all other classes in this hierarchical system. ios indicates input-output stream.
The resources required for input and output functions utilized by all other subclasses are provided in this class.
istream
The input stream is referred to as istream. This type is a descendant of the ‘ios’ class. Stream input is managed by this category.
This class has overridden the extraction operator (>>) to manage input streams for the implementation of a code.
The get(), getline(), and read() input methods are specified in this module.
ostream
Ostream refers to the output stream. The class ‘ios’ is a descendant of this one. The output stream is controlled by this component.
streambuf
The buffer utilized to control the input and output flows is referred to through a pointer in this module.
fstreambase
This class offers functions that are prevalent to file streams. It acts as the foundation for the categories: fstream, ifstream, and ofstream.
The open() and close() methods are included in this module.
ifstream
Input operations are offered by this type. The open() method is present and the input option is usual. It acquires the methods read(), seek(), tell(), get(), and getline() from the istream.
ofstream
This class contains functions for output. It includes the standard output method for the open() method. It handles the ostream’s put(), write(), seek(), and tell() methods.
fstream
The capability for multiple input and output functions is handled by this class. By iostream, it imports every method from the istream and ostream interfaces.
filebuf
Setting the file buffers to read and to write the text is its function. The file buffer component method could be utilized to compute the file’s size as well. Three classes—fstream, ifstream, and ofstream—are present in the fstream template and are mostly utilized in C++ to deal with files.
- ofstream: A file-writing stream type.
- Ifstream: It is a class for reading files from streams.
- Fstream: It is a kind of stream that can read and write to/from files.
Operation of C++ ofstream
The iostream header file, which has the methods cin and cout, would be utilized to read from the input source and write to the output file. Similarly, the C++ header file fstream is used to read content from files and write information into files. The three data classes’ ofstream, ifstream, and fstream are offered by the header file fstream. We utilize ofstream by integrating the module <fstream> in the code even when it is important to represent the output file stream, generate a file, and write data to the file. The class ostream is a descendant of ofstream.
Syntax
The syntax for C++ ofstream is as follows:
var_name.open(file_name);
The name of the required variable is represented by the ‘var_name’. The file that will be accessed is termed ‘file_name’.
The Output Stream Open Method
An output file stream (ofstream) should be linked to a particular file system in the constructor or open method so that it can be utilized. Users may utilize the identical stream instance with several files if we utilize the open method. The parameters used to identify the file are similar to all scenarios.
Normally, an open mode parameter is specified whenever opening a file connected to an output stream. These attributes, which have been enumerators in the input-output stream module, could be paired by using the bitwise OR operator.
The Put Method
One letter is written to the output stream by the put method.
The Write Method
A memory block is written to an output file stream through the write method. The number of bytes presented is provided by the size parameter. The whole class structure is written because the write method does not terminate when it encounters a NULL element. A char command and the number of characters to write are the two inputs the function requires. Just before the reference of the structure element, take note of the appropriate conversion to char *.
The seekp and tellp Methods
An intrinsic pointer that identifies the path of the upcoming data write is maintained by an output file stream. This port is created by the seekp function call which also returns random-access storage files. The file address is obtained by the tellp function call.
The Close Function
The output file stream’s storage file is terminated by using the close method call. To finish all output to the system, the file should be shut. If required, the ofstream destructor terminates the file for you. However, if we want to open a new file for the same stream class, we will utilize the close method. If the constructor or open member method opens the file, would the output stream destructor stop functioning in the stream’s file? We must manually shut the file if we utilize the attach method call or supply a file name for an open file to the constructor.
Member Constants
Different member constants use for the ofstream functions are:
Member constant: in *
It represents the input.
File accessible for reading. Input operations are provided by the intrinsic stream buffer.
Member constant: out
It represents output.
File accessible for written form: output operations are handled by the underlying stream buffer.
Member constant: binary
It shows the binary value.
Instead of using text, operations are carried out in binary mode.
Member constant: ate
It denotes at the end.
The endpoint of the file is where the output place begins.
Member constant: app
It represents append.
The file’s current data is added to every output operation, which takes place.
Member constant: trunc
It indicates truncation.
Just before the file was opened, all its data was removed.
Example 1
In this example, we would see how to create a file in C++.
At the start of this code, we add libraries that are <iostream> and <fstream> that are responsible for managing the files like creating, adding, updating, and deleting the files. Then, add namespace standard. After that, we start our main() function. In the main() function we get our file by using the ofstream() function that is used to create the new file in the C++ file system. In the parameters of this function, we pass our file by giving the right name of the file.
Remember that the code file and the text file must be placed in the same location. Here, we write the condition that if the file exists then do not enter in the statement and execute the else statement where we show a message that the file exists. When the file will not be present, we create the file and write some text in this file. Then, we close the file by calling the close() function with the file name as you can see in the two outputs below. We run the code for the first time and the file is created but when we run the code the second time it gives us the message that the file exists.
If the defined file exists, we acquire this type of outcome.
Example 2
In this instance, we would write the data in the file.
As we know, the ofstream function is also used to write, update, or edit the text file in the file system of C++. So, here we write a code to write some text to a document file. For this purpose, we have our necessary libraries that <iostream> and <fstream> the first library containing the definition of input-output functions. Then, we utilize the standard of the namespace and write out the main() function.
After that, get the file that we created with the help of our last code. Again, by using the ofstream() function, the function will manage all our operations related to the filing in this language. We initialize a file and pass our text file to it by using the open() function and passing the text file in the parameters of this function. Then, we pass a sentence to the file and display a message that is ‘file write successfully’. Then, call the close() function with the file name to close our text file that was opened at the start of the code to add some text in this file.
Example 3
In this case, we see how to check whether the file is empty or not.
In the previous file, we added our text in the file but did not display. So, we can also check first whether our file is empty or not by displaying the content of the file. If it is empty, we add some text and again display the data in the console. The first line includes our header files that support our different functions related to the input and output, as well as related to our files. We add our namespace standard. In the next line, we start the main() function where we perform all our functionalities by writing the code.
First, we call the ofstream() function and initialize the file. Then, call the open() function to pass the file by giving the file name to the parameters. Then, give it to the file variable that we created earlier. Next, we display the data of the file by using the ‘while’ loop because the C++ language reads the text file word by word, so we use a while loop. In the condition of a while loop, we call the get line function that is used to read the text file. In the parameters, if this function we send our file as well as a string that saves all the data. In the while loop, we display our file and close the file by calling the close() function.
Example 4
In this illustration, let’s edit the data of the file.
In the previous code, as you can see, we display our file but there was no data in that file so here we add some data in the form of text. Then, we try to display that data. First, we write our libraries. These libraries help us to call functions to perform some action in the place of some complex code or algorithms to do some complicated function in all fields of code. These libraries were <iostream> and <fstream>. Then, we add namespace standards. Before starting the code, we invoke the main() function because we must write all our code in this function. In the main() function, the first thing we did was to initialize the file by using our ofstream() function.
Then, we pass our text file to this file variable by calling the open() function. When we call this function, we did do things. First, we pass our text file to the file variable as well as open the text file. In the next line, we add some text data to the text file that we opened earlier. After putting the data, we close our file by adding the close() function with the text file variable. Here, we initialized a string. The purpose of this string is to get the data from the file that we create and update above. So, we call our ifstream() function that is responsible for displaying the data that is in the form of text in the file as well as by using this function we also initialize another file variable and pass our text file to this file variable.
Now, we are displaying the data. So, for this purpose, we use a ‘while’ loop. We call the getline() function to fetch the lines from our text file that we pass in the parameters of this function. In this loop, we utilize ‘cout’ to print the string that we pass in the getline() function. When the display is complete, the loop ends after closing the file by calling the close() function with our text file.
Conclusion
In the first section of this article, we discussed what file handling in the C++ programming language involves. We also talked about the appropriate method to manage files and the file stream classes’ functions. The ofstream() method has then been used in a variety of programs that we have implemented. In the first program, a file has been created. Then, in the next instance, the content is written to the file. Next, we determine whether the file is empty. We must update the file at the end.