Working with Files in C++: Reading and Writing Beyond the Screen
Up until now, we’ve been making use of the iostream
standard library, which provides us with the powerful cin
and cout
methods for handlin
fstream
, which introduces new data types for file-based operations. Files and Streams in C++ provide a versatile way to interact with external data sources, enabling reading from and writing to files seamlessly.
C++ fstream introduces three key data types to manage files:
- ofstream: This data type facilitates output file stream operations. It’s used to create and write information to files.
- ifstream: This type handles input file stream operations. It’s used for reading information from files.
- fstream: This versatile type encapsulates both the capabilities of
ofstream
andifstream
. It can create, write to, and read from files.
To dive into file processing in C++, we need to include the header files <iostream>
and <fstream>
in our source code. These libraries pave the way for powerful file handling capabilities.
Opening a File: Setting the Stage
Before we can read from or write to a file, we need to open it. We can use either an ofstream
or fstream
object to open a file for writing. For reading purposes, an ifstream
object comes into play.
The standard syntax for the open()
function, a member of fstream
, ifstream
, and ofstream
objects, is as follows:
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened. The second argument, the openmode
, defines the mode in which the file should be opened. The openmode
can be one of several values, such as ios::app
for append mode, ios::ate
to move the read/write control to the end of the file, ios::in
for reading, ios::out
for writing, and ios::trunc
to truncate the file’s contents if it already exists.
You can combine these values using the OR operator (|
). For instance:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc);
Similarly, you can open a file for both reading and writing:
fstream afile;
afile.open("file.dat", ios::out | ios::in);
Closing a File: Tying Up Loose Ends
When a C++ program reaches its end, it automatically flushes streams, deallocates memory, and closes files. However, it’s good practice for programmers to manually close all opened files before program termination. The standard syntax for the close()
function, a member of fstream
, ifstream
, and ofstream
objects, is as follows:
void close();
Writing to a File: Recording Information
Writing to a file is akin to using the stream insertion operator (<<
) for screen output, but here we use ofstream
or fstream
objects instead of cout
. This enables us to write information directly to a file.
Reading from a File: Gathering Information
Reading from a file uses the stream extraction operator (>>
), just like when taking input from the keyboard. However, we use ifstream
or fstream
objects in place of cin
.
File Operations: A Practical Example
Let’s put these concepts into practice with a simple example. Consider the following C++ program:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
char data[100];
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
outfile << data << endl;
outfile.close();
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
cout << data << endl;
infile >> data;
cout << data << endl;
infile.close();
return 0;
}
When executed, this program captures user input, writes it to a file, reads it back, and displays the content. It showcases advanced functions like getline()
and ignore()
for streamlined file manipulation.
Navigating File Content: File Position Pointers
The istream
and ostream
classes offer member functions to navigate the file-position pointer. seekg
is used with istream
for repositioning the “get” file-position pointer, while seekp
serves the same purpose for the “put” file-position pointer with ostream
. These functions require a long integer argument and an optional seek direction argument like ios::beg
, ios::cur
, or ios::end
.
fileObject.seekg(n); // Position to the nth byte
fileObject.seekg(n, ios::cur); // Move n bytes forward
fileObject.seekg(n, ios::end); // Move n bytes back from the end
By harnessing the power of file processing with C++’s fstream
library, you can seamlessly transition from standard input and output to reading and writing to files. This enhanced capability empowers your programs to manage data across different mediums effectively.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.