0% found this document useful (0 votes)
24 views6 pages

File Operations

The document explains how to use the fstream library in C++ for file operations, including creating, writing, and reading files using ofstream and ifstream classes. It also describes the differences between sequential and random access files, detailing their use cases and providing example code for both methods. The document emphasizes the importance of closing files and managing memory effectively.

Uploaded by

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

File Operations

The document explains how to use the fstream library in C++ for file operations, including creating, writing, and reading files using ofstream and ifstream classes. It also describes the differences between sequential and random access files, detailing their use cases and providing example code for both methods. The document emphasizes the importance of closing files and managing memory effectively.

Uploaded by

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

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
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");

// Write to the file


MyFile << "Files can be tricky, but it is fun enough!";

// Close the file


MyFile.close();
}
Why do we close the file?
It is considered good practice, and it can clean up unnecessary memory space.

Read a File
To read from a file, use either the ifstream or fstream class, and the name of the file.

Note that we also use a while loop together with the getline() function (which
belongs to the ifstream class) to read the file line by line, and to print the content of
the file:

Example
// Create a text string, which is used to output the text file
string myText;

// Read from the text file


ifstream MyReadFile("filename.txt");

// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}

// Close the file


MyReadFile.close();
SEQUENTIAL AND RANDOM ACCESS FILES
Introduction
In C++, sequential and random access files are two different methods of
organizing and accessing data stored in files on a storage medium (such as a hard
drive). Both methods have their advantages and are suitable for different use cases.
The choice between sequential and random access files depends on the specific
requirements of your application. If you need to process data in the order it is stored
and have large datasets, a sequential access file might be more suitable. If you need
quick access to specific records in a database-like scenario, a random access file
could be the better choice. Let’s explore the theory behind each:

Sequential Access File


In a sequential access file, data is stored in a continuous sequence one after
the other. Each record in the file is written after the previous one, and there is no
direct way to access a specific record without traversing through the preceding
records.
Reading and writing data in a sequential access file follows a strict order: you
read or write data from the beginning of the file to the end, or vice versa.
Once you read or write a particular part of the file, you need to move the file
pointer to the next position to read or write the next piece of data. This is the default
file access method in most programming languages.
It is best suited for tasks where data is processed in the order it is stored, like
logs, simple databases, or large data sets that need to be processed sequentially.
In C++, you can work with sequential access files using the fstream class,
which provides both input (ifstream) and output (ofstream) file stream classes.

Example C++ code for writing and reading data sequentially:

#include <iostream>
#include <fstream>
int main() {
// Writing data sequentially
std::ofstream outfile("data.txt");
if (outfile.is_open()) {
outfile << "Record 1\n";
outfile << "Record 2\n";
outfile << "Record 3\n";
outfile.close();
}

// Reading data sequentially


std::ifstream infile("data.txt");
if (infile.is_open()) {
std::string line;
while (std::getline(infile, line)) {
std::cout << line << std::endl;
}
infile.close();
}
return 0;
}

Random Access File


In a random access file, data is stored in a way that allows direct access to any
record in the file without having to read through the preceding records.
Each record has a unique identifier (often called a record number or a key)
that helps locate and access it directly.
Random access files provide faster access to specific records, but they may
require additional overhead to manage the record numbers or keys.
Random access files are more suitable for applications where you need quick
access to specific data, such as databases with indexed records.
You can directly move the file pointer to a particular location in the file and
read or write data from that point.
This method is useful when you need to access specific records or data in a
non-sequential manner.
C++ provides the fstream class with the seekg() (for input) and seekp() (for
output) methods to move the file pointer to a specific position.

Example C++ code for writing and reading data randomly:

#include <iostream>
#include <fstream>
struct Record {
int id;
std::string data;
};
int main() {
// Writing data randomly
std::ofstream outfile("data.bin", std::ios::binary);
if (outfile.is_open()) {
Record record1 = {1, "Record 1"};
Record record2 = {2, "Record 2"};
Record record3 = {3, "Record 3"};
outfile.write(reinterpret_cast<char*>(&record1), sizeof(Record));
outfile.write(reinterpret_cast<char*>(&record2), sizeof(Record));
outfile.write(reinterpret_cast<char*>(&record3), sizeof(Record));
outfile.close();
}

// Reading data randomly


std::ifstream infile("data.bin", std::ios::binary);
if (infile.is_open()) {
int recordNumber; // The record number you want to read (1, 2, 3)
infile.seekg((recordNumber - 1) * sizeof(Record)); // Move the file pointer to the
desired record
Record record;
infile.read(reinterpret_cast<char*>(&record), sizeof(Record));
std::cout << "Record " << record.id << ": " << record.data << std::endl;
infile.close();
}
return 0;

You might also like