File in C++
In c++,File is an external storage resource on the computer's disk, such as a text file (.txt), CSV file (.csv), or binary file (.bin). These files provide the program with a way to store data in a persistent manner, enabling the data to be preserved even after the application has terminated. On the other hand, data stored in memory (RAM) is transient and is erased when the application terminates.
Types of File
Text File
Data is stored in text files as characters that are readable by humans. They may include numeric data, plain text, or formatted information such as CSV (Comma-Separated Values). Simple text editors make it simple to create, read, and edit text files. Text files are used by programs when users or other programs need to understand or alter the data. Examples of applications include data transfer, logs, and configuration files.
Binary File
Saves information in a raw, machine-level format instead of plain text. These files are typically more compact and efficient than text files, but their data isn’t easily readable or editable with standard text editors.
Two main techniques for reading and writing binary files are sequential access and random access
Sequential Access
- Sequential access processes data from the beginning of the file, moving through it in order. It's ideal for tasks such as reading logs or processing plain text files line by line. However, it's not very efficient when searching for specific data within large files.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream file("hello.txt"); // ofstream is used for writing to files
if (file.is_open()) {
file << "first data.";
cout << "Data written to file.";
file.close();
} else {
cerr << "Error opening file.";
}
return 0;
}
Random Access
-
With random access, you can jump directly to a specific position in a file using functions like
seekg
orseekp
for reading and writing, respectively. This method is faster and more efficient for large files, especially when working with binary data.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream file("bb.txt");
if (file.is_open()) {
file.seekg(5, ios::beg); // Move pointer to the 5th byte from the beginning
char ch;
file.get(ch); // or file >> ch; // Reading a single character
cout << "Character at position 5: " << ch;
file.close();
} else {
cerr << "Error.";
}
return 0;
}
File Handling in C++
File handling is a technique for creating and carrying out read and write operations on a file. By importing the class, we may access several C++ file handling functions. File management makes persistent data storage possible by enabling us to save and retrieve data from secondary storage.
A stream refers to a flow of bytes used to perform input and output operations. In C++, standard input and output are handled by stream objects such as cin
and cout
, which are defined in the <iostream>
library.
For file handling, C++ provides the <fstream>
header,
which includes the following classes:
ifstream
: used for reading data from filesofstream
: used for writing data to filesfstream
: used for both reading and writing data to files
In C++, handling a file involves three primary steps: opening the file, carrying out read/write operations, and closing the file. Before reading or writing may begin, a file must be opened. In C++, files are opened using stream objects, such as fstream file("file.txt", mode); where the mode defines the operation (read, write, etc.).
File opening modes in C++ define how a file is accessed. Common modes include:
- ios::in → Opens the file for reading
- ios::out → Opens the file for writing
- ios::binary → Opens the file in binary mode
- ios::ate → Opens the file and moves the cursor to the end
- ios::app → Opens the file in append mode; data is written at the end
- ios::trunc → Truncates the file if it already exists (clears its contents)
Basic Demonstration of File Opening Modes in C++:
- fstream file("file.txt", ios::in); // Opens the file for reading only
- fstream file("file.txt", ios::out); // Opens the file for writing only (overwrites existing content)
- fstream file("file.txt", ios::in | ios::out); // Opens the file for both reading and writing
Note:ifstream and ofstream are two specific file stream classes in C++ designed for reading from and writing to files, respectively.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("hello.txt");
file << "Welcome to Information System Department.";
file.close(); //to free up resources and avoid data loss
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("hh.txt"); // Open the file in read mode
string line;
if (file.is_open()) {
while (getline(file, line)) { // Read each line from the file and display it
cout << line;
}
file.close(); // Close the file after reading
} else {
cout << "Failed to open the file.";
}
return 0;
}