Lab # 11 Data File Handling in C++
Lab # 11 Data File Handling in C++
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.
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:
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>
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;
}
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";
return 0;
}
Example # 4: Appending to a Text File:
#include <iostream>
#include <fstream>
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;
}
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;
}