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

Lab # 11 Data File Handling in C++

Uploaded by

alizarizwan006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Lab # 11 Data File Handling in C++

Uploaded by

alizarizwan006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

University of Management and Technology

Department of Artificial Intelligence


CC1021L Programming Fundamentals Lab
Fall 2023
Participant ID: Participant Name:

Date: Total Marks: Obtained Marks:

Lab # 11: Data File Handling in C++


Learning Objectives
 Implement a C++ program that reads data from a text file, processes the information, and
writes the modified data back to a new file.
 Understand the fundamental concepts of data file handling in C++, including the roles of
ifstream and ofstream, file opening modes, and the implications of using different file
stream flags.
File Handling in C++
C++ provides the <fstream> library to handle file operations. The common classes used for file
handling are:
 ifstream (input file stream)
 ofstream (output file stream)
 fstream (file stream, which can be used for both input and
output)
These classes are derived directly or indirectly from the classes istream and ostream. We
have already used objects whose types were these classes:
 cin is an object of class istream
 cout is an object of class ostream.
Therefore, we have already been using classes that are related to our file streams. And in fact, we
can use our file streams the same way we are already used to use cin and cout, with the only
difference that we have to associate these streams with physical files. Let's see an example:
include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream myfile("example.txt");

if (myfile.is_open()) {
myfile << "Hello, file handling in C++!";
myfile.close();
} else {
cout << "Unable to open file.";
}
return 0;}
This code creates a file called example.txt and inserts a sentence into it in the same way we
are used to do with cout, however the file stream myfile instead.

Why file reading and writing?


In C++, file handling is an essential concept that allows you to read from and write to files using
the <fstream> library. There are various scenarios where file handling is useful:
1. Data Persistence: Store data persistently, such as user preferences or application
configuration, for retrieval across sessions.
2. Data Analysis: Efficiently process large datasets by reading data from files, enabling
line-by-line or chunk-based operations.
3. Logging: Log events and errors to a file for easier issue tracing and debugging in
applications.
4. File Transformation: Read from one file, process data, and write results to another,
facilitating data transformation tasks.
5. Configuration Files: Use file handling to read settings from configuration files and
configure the program accordingly.

Type of files C++ can generate


In C++, the <fstream> library provides the capability to generate various types of files using the
ofstream class for output file stream operations. Some common types of files that C++ can
generate using the ofstream class include:
1. Text Files: C++ can easily generate plain text files by using ofstream to write textual
data. Text files are human-readable and can be edited with a simple text editor.
2. Binary Files: With the ofstream class, C++ can generate binary files by writing binary
data directly. Binary files contain non-textual data and are more efficient for storing
complex data structures.

CSV (Comma-Separated Values) Files: C++ can generate CSV files, which are
commonly used for storing tabular data. CSV files use commas or other delimiters to
separate values.

3. Log Files: C++ can generate log files by using ofstream to write log messages. Log files
are useful for recording events, errors, and debugging information during the execution of
a program.
4. Configuration Files: Configuration files, often in a plain text format, can be generated
by C++ to store settings and parameters for an application.

5. HTML or XML Files: C++ can generate HTML or XML files, which are commonly
used for web development and data interchange. These files follow specific markup
structures.
Open a file
The first operation generally performed on an object of one of these classes is to associate it to a
real file. This procedure is known as to open a file. An open file is represented within a program
by a stream (i.e., an object of one of these classes; in the previous example, this was myfile)
and any input or output operation performed on this stream object will be applied to the physical
file associated to it.
In order to open a file with a stream object we use its member function open:
object_name.open(filename, mode);
where filename is a string representing the name of the file to be opened, and mode is an optional
parameter with a combination of the following flags:
ios::in Open for input operations.
ios::out Open for output operations.
ios::binary Open in binary mode.
ios::ate Set the initial position at the end of the file. If this flag is not set, the
initial position is the beginning of the file.
ios::app All output operations are performed at the end of the file, appending the
content to the current content of the file.
ios::trunc If the file is opened for output operations and it already existed, its
previous content is deleted and replaced by the new one.
All these flags can be combined using the bitwise operator OR (|). For example, if we want to
open the file example.bin in binary mode to add data we could do it by the following call to
member function open:
ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);
Each of the open member functions of classes ofstream, ifstream and fstream has a
default mode that is used if the file is opened without a second argument:

class default mode parameter


ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out
For ifstream and ofstream classes, ios::in and ios::out are automatically and
respectively assumed, even if a mode that does not include them is passed as second argument to
the open member function (the flags are combined). For fstream, the default value is only
applied if the function is called without specifying any value for the mode parameter. If the
function is called with any value in that parameter the default mode is overridden, not combined.
File streams opened in binary mode perform input and output operations independently of any
format considerations. Non-binary files are known as text files, and some translations may occur
due to formatting of some special characters (like newline and carriage return characters). Since
the first task that is performed on a file stream is generally to open a file, these three classes
include a constructor that automatically calls the open member function and has the exact same
parameters as this member. Therefore, we could also have declared the previous myfile object
and conduct the same opening operation in our previous example by writing:
ofstream myfile ("example.bin", ios::out | ios::app |
ios::binary);

Closing a file
When we are finished with our input and output operations on a file we shall close it so that the
operating system is notified and its resources become available again. For that, we call the
stream's member function close. This member function takes flushes the associated buffers and
closes the file:
myfile.close();
Once this member function is called, the stream object can be re-used to open another file, and
the file is available again to be opened by other processes. In case that an object is destroyed
while still associated with an open file, the destructor automatically calls the member function
close. Combining object construction and stream opening in a single statement. Both forms to
open a file are valid and equivalent.
It is important to close file for certain reasons, however, two important reasons have been
discussed below:
1. Data Integrity: Closing a file ensures that all the data is properly written to the file. File
I/O operations often involve buffering, and data may not be written immediately to the
file. Closing the file flushes the buffer and guarantees that all changes are saved.
2. Resource Management: Open files consume system resources, and there is usually a
limit to the number of files a program can have open simultaneously. Failing to close files
may lead to resource exhaustion and can cause the program to behave unpredictably or
crash.
Functions associated with <fstream>
1. seekp: seekp is a function associated with output file streams (ofstream). It allows you to
set the position of the put pointer (used for writing) within the file.
Example: outFile.seekp(6, std::ios::beg);
2. tellp: tellp is a function associated with output file streams (ofstream). It returns the
current position of the put pointer within the file.
Example: streampos position = outFile.tellp();
3. seekg: seekg is a function associated with input file streams (ifstream). It allows you to
set the position of the get pointer (used for reading) within the file.
Example: inFile.seekg(10, std::ios::beg);
4. tellg: tellg is a function associated with input file streams (ifstream). It returns the current
position of the get pointer within the file.
Example: std::streampos position = inFile.tellg();
Example # 1: Writing a sentence to a text file.
#include <iostream>
#include <fstream>

using namespace std;

int main() {
ofstream outFile("text_file.txt", ios::out);

if (outFile.is_open()) {
outFile << "This line is written to the text file." << endl;

outFile.close();
} else {
cout << "Unable to open text file for writing." << endl;
}

return 0;
}

Example 2: Reading from a Text File


#include <iostream>
#include <fstream>

using namespace std;

int main() {
ifstream inFile("text_file.txt", ios::in);

if (inFile.is_open()) {
string data;
while(getline(inFile, data)){

cout << "Read from text file: " << data << endl;
}

inFile.close();
} else {
cout << "Unable to open text file for reading." << endl;
}

return 0;
}
We have created a while loop that reads the file line by line, using getline. The value returned
by getline is a reference to the stream object itself, which when evaluated as a boolean
expression (as in this while-loop) is true if the stream is ready for more operations, and false if
either the end of the file has been reached or if some other error occurred. To check if a file
stream was successful opening a file, you can do it by calling to member is_open. This member
function returns a bool value of true in the case that indeed the stream object is associated with
an open file, or false otherwise.
Example # 3: Writing to a Text File with ios::ate Flag:
#include <iostream>
#include <fstream>
using namespace std;

int main(){
ofstream myfile("practice.txt", ios::out);
if(myfile.is_open()){
myfile << "THis is text interested by C++ program\n";
myfile << "This is second line";
cout<<"The file has been written successfully\n";
myfile.close();
}
else
cout<<"The file is not opened";
string line;
ifstream inFile ("practice.txt", ios::in);
if(inFile.is_open()){
while(getline(inFile, line)){
cout<<line<<endl;
}
inFile.close();
}
else
cout<<"The file is not opened";

fstream ateFile("practice.txt", ios::in | ios::out | ios::ate );


if(ateFile.is_open()){
//Move the file pointer 100 byte location
ateFile.seekp(100, ios::beg);
ateFile.seekg(100, ios::beg);
ateFile.seekp(ateFile.tellg());
ateFile << "This is inserted at 100 byte\n";
ateFile.close();
}
else
cout<<"The file is not opened";

return 0;
}
Example # 4: Appending to a Text File:
#include <iostream>
#include <fstream>

using namespace std;

int main() {
ofstream outFile("text_file.txt", ios::out | ios::app);

if (outFile.is_open()) {
outFile << "This line is appended to the text file." << endl;

outFile.close();
} else {
cout << "Unable to open text file with app flag for writing."
<< endl;
}

return 0;
}

Example # 5: Truncating a Text File:


#include <iostream>
#include <fstream>

using namespace std;

int main() {
ofstream outFile("truncate_text_file.txt", ios::out | ios::trunc);

if (outFile.is_open()) {
outFile << "This content will replace any existing content in
the text file." << endl;

outFile.close();
} else {
cout << "Unable to open text file with trunc flag for
writing." << endl;
}

return 0;
}

You might also like