8. Basics of File Handling in C++
Hello folks!
Welcome to this blog series. In the previous blog we have studied see how Dynamic memory is allocated in C++.
Now in this blog we will study how to handle files in C++. So why do we need file handling knowledge while designing our system? We require File handling because know when our system is fully build and given to the user to operate it, the user of the system needs to know how much transaction had occurred since past check for various reasons such as to calculate the profit the Cafeteria is making. Number of items sold for the quantity of goods to be purchased etc. So let’s get started with this blog session.
Basics of File Handling in C++
The Basic file handing library in C++ is fstream. The fstream library contains
1. ofstream object/data type which Creates and writes to files,
2. ifstream object/data type which Reads from files
3. fsrteam class which contains file handling functions.
Now if we want to create a file and write into it, we basically use ofstream or fstream object and specify the name of file to be created.
We use insertion operator (<<) to write in the file. Let’s take an example to see how it is done.
Code:
Output:
Text File:
Similarly if we want to just read the file, we use ifstream or fstream object and specify the name of file to be read.
We use extraction operator (>>) to read from the file. Let’s take an example to see how it is done.
We will read from the above created file for understanding purose.
Code:
Output:
Some of us will get a doubt that why did I close the file, because in C++ by default all the files opened are closed and all related data is released, the answer to this question is “as a good programming practice we should write file closing syntax is our code”. Not all the programming languages out there have such functionality.
So now we can do basic file handling in C++.
Some more advance ways of file handling in C++ will be discussed in our next blog.
By-
Ashutosh Bardapurkar (k-05)
Hrishikesh Deshpande (k-16)
Archit Hiwrekar (k-23)
Chinmay Kapkar (k-33)
Very nice!
ReplyDeleteI was looking for this
ReplyDeleteThank you.