0% found this document useful (0 votes)
14 views

C++ Files

Uploaded by

rachealmwubaha8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

C++ Files

Uploaded by

rachealmwubaha8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

2102 Object Oriented Programming C++

C++ Files: ofstream(), ifstream() & fstream()

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

ofstream Creates and writes to files

ifstream Reads from files

fstream A combination of ofstream and ifstream: creates, reads, and writes to files

Create and Write to a File


To create a file, use either the ofstream or fstream class, and specify the name of the file.

To write to the file, use the insertion operator (<<).

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.

1. Header Files: The Foundation

• #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.

4. Creating and Opening the File

• ofstream MyFile("filename.txt");: This line accomplishes two critical tasks:

o It declares an object named MyFile of type ofstream. Think of MyFile as a conduit


or channel through which your program will communicate with the file.

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.

5. Writing to the File

• 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."

6. Closing the File

• 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.

Contents of filename.txt after running the two programs.

Check the File for Errors


In file handling, it's important to ensure the file was opened without any error before we can
perform any further operations on it.

By Checking the File Object


Notice the condition in the if statement:

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,

In the C++ program above:

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:

o An error message is printed to the console using cout.


o The program returns 1, indicating an error occurred.

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.

We use the eof( ) function for this purpose, which returns


• true - if the file pointer points to the end of the file
• false - if the file pointer doesn't point to the end of the file
For example,

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

File Handling With fstream


Instead of using ifstream to read from a file and ofstream to write to the file, we can
simply use the fstream class for all file operations.

The constructor for fstream allows you to specify the file name and the mode for file
operations.

Mode Description

ios::in Opens the file to read (default for ifstream).

ios::out Opens the file to write (default for ofstream).

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/

You might also like