I experienced a case that I was not familiar with the files input and output stream during a competitive programming contest. LeetCode provides a platform that handles input and out for you so you can save time and focus on solving the main problem. It took me quite a time to google it during the contest so I decided to dig a bit deep into files input and output in C++. In addition, I will also cover some advanced topics including reading and writing Binary files, file parsing and structs, and padding in files in the future.
Streams are objects (class) that allow us to write and read data. We can use the stream library in std::fstream to help us. Consider the following code to write to a file.
When we use ofstream to write a file, we must use .open() and .close() to open the file and to close the file when the operation is finished. fstream will create a file in the .open() method if the file name does not exist in the current C++ files’ running directory. If the file exists, it will directly open the existing file without creating any files. .is_open() is also a method from the fstream class that returns a bool type to check if the file is opened successfully.
If we do not include a path, the files will be the working directory of the current running program.
We can also use fstream to open and close the file with the same method. However, we have to add ios::out when we open a file. Consider the following code.
Reading files works similar to writing files. The ifstream is an input files stream that we are going to use in our case. Consider the following example, code, and result from the console.
- If we want to read the string until we reach the first space, we can simply use >> operator.
- If we want to read the file text line by line, we can use the .getline() method in the fstream.
- If we want to read all the text content inside the files, we have to use a while operation together with .getline(), as well as a method called .eof() in fstream, where .eof() stands for “end of file” and it returns a bool type to check if the file is reached to the end.
💡 Additionally, we do not have to use .eof() as ifstream has a couple of very exposed overloaded operators and we can overload operators like = or +. In our case, the ! (not), bool operator can overload and the variable name itself can directly overload and return the bool type to check if the file has reached the end or not.
I have mentioned ways to read and write to files in C++ in short with examples. Soon I will also further talk about more files operation in C++ like what I mentioned at the very beginning.