C++ Files
C++ Files
Facilitator :
Mr. Luyima Alex Cedric
[email protected]
C++ Files
The fstream library allows us to work with files.
To use the fstream library, include both the standard <iostream> AND the <fstream> header file:
Example
#include <iostream>
#include <fstream>
There are three classes included in the fstream library, which are used to create, write or read files:
Class Description
fstream A combination of ofstream and ifstream: creates, reads, and writes to files
Example:
Understanding the Code: A Deeper Dive
The C++ code above provides a concise yet powerful illustration of how to interact with files using
the standard fstream library. Let's break down the key components and concepts step-by-step.
• #include <iostream>: This line incorporates the input/output stream library, granting us
access to standard input and output operations. Though not directly utilized in this specific
example, it's a common inclusion in C++ programs, often facilitating interactions with the
user through the console.
• #include <fstream>: This line is pivotal for our file handling endeavors. It introduces the file
stream library, equipping us with classes like ofstream (output file stream), ifstream (input
file stream), and fstream (for both input and output) to seamlessly manage file operations.
2. using namespace std;: While convenient, it is generally recommended to avoid this in larger
projects to prevent potential naming conflicts. You can replace it with std::ofstream, std::cout,
etc., to explicitly specify the namespace.
3. The main Function: The Heart of the Program
• int main() { ... }: This marks the entry point of our C++ program. All code execution
commences within the curly braces of this function.
o It attempts to open a file named "filename.txt" in output mode. If the file doesnot
exist, it is thoughtfully created for you. If it already exists, its contents are cleared,
making way for fresh data.
• MyFile << "Files can be tricky, but it is fun enough!";: This line employs the stream
insertion operator (<<), often referred to as the "put to" operator. It elegantly directs the text
string "Files can be tricky, but it is fun enough!" into the file represented by the MyFile
object. In essence, this writes the text into "filename.txt."
• MyFile.close();: This seemingly simple line plays a crucial role. It severs the connection
between your program and the file. This ensures that any data lingering in the buffer is
diligently transferred to the physical file on your storage device. Additionally, it releases any
system resources that were allocated for file handling, promoting efficient resource
management.
7. return 0;
• This statement signals the successful completion of your program to the operating system.
Appending a file
In the C++ program below, a second argument ios::app to the constructor of the ofstream
class. This tells the stream to open the file in append mode.
if (!my_file) {...}
This method checks if the file is in an error state by evaluating the file object itself.
• If the file has been opened successfully, the condition evaluates to true.
• If there's an error, it evaluates to false, and you can handle the error accordingly.
For example,
if (!MyFile) { ... }:
• This if statement checks if there was an error opening the file.
• !MyFile evaluates to true if there was an error (e.g., the file could not be created due
to permissions issues).
• If there is an error:
else { ... }:
• This block executes if the file was opened successfully.
Read From a File
Reading from text files is done by opening the file using the ifstream class. For example,
ifstream my_file("example.txt");
Then, we need to read the file line-by-line. To do this, we need to loop through each line of
the file until all the lines are read, i.e., until we reach the end of the file.
Here, the while loop will run until the end of the file. In each iteration of the loop,
• getline(my_file, line); reads the current line of the file and stores it in
the line variable.
• Then, it prints the line variable.
Next, let us clarify this with a working example.
Example 1: Using while loop with eof( )
Example 2: Using while loop
The constructor for fstream allows you to specify the file name and the mode for file
operations.
Mode Description
ios::app Opens the file and appends new content to itat the end.
Please Note: Using ifstream and ofstream explicitly signifies the intention of reading or
writing, respectively, making the code more readable and less prone to errors.
Using fstream for both might lead to ambiguity or unintended operations if not handled
carefully.
Web Resources
https://www.w3schools.com/cpp/cpp_files.asp
https://www.programiz.com/cpp-programming/file-handling
https://www.geeksforgeeks.org/file-handling-c-classes/