0% found this document useful (0 votes)
1 views8 pages

C++ - File Handling

File Handling in C++ allows for reading and writing data to files, ensuring data persistence beyond program execution. It is crucial for managing large datasets, facilitating data sharing, logging events, and maintaining user preferences. C++ provides various file stream classes and modes for efficient file operations, including text and binary file handling.

Uploaded by

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

C++ - File Handling

File Handling in C++ allows for reading and writing data to files, ensuring data persistence beyond program execution. It is crucial for managing large datasets, facilitating data sharing, logging events, and maintaining user preferences. C++ provides various file stream classes and modes for efficient file operations, including text and binary file handling.

Uploaded by

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

File Handling in C++

File Handling in C++ refers to reading from and writing to files, enabling permanent storage of data
beyond program execution.
Importance of File Handling in C++
File handling in C++ is essential for storing, retrieving, and managing data efficiently. It allows
programs to read from and write to files, making data persistent beyond program execution. Below
are the key reasons why file handling is important in C++:
1️. Data Persistence
Unlike variables (which store data temporarily in RAM), files store data permanently on
disk.
Ensures that data remains accessible even after the program exits.
Example: Saving user scores in a game so they remain after closing the application.
2️. Large Data Storage & Processing
Memory (RAM) is limited, but files provide virtually unlimited storage.
Allows processing of large datasets that cannot fit into RAM.
Example: A banking system storing thousands of transaction records.
3️. Data Sharing & Communication
Files allow data exchange between different programs or users.
Standard file formats (.txt, .csv, .json, .xml) enable compatibility across platforms.
Example: Exporting a report in CSV format to be opened in Excel.
4️. Logging & Debugging
Programs can log important events and errors in a file for later analysis.
Helps in debugging and monitoring software performance.
Example: Web servers maintain log files to track website requests.

5️. User Preferences & Configuration


Applications can save user settings in files to maintain preferences.
Configuration files (.ini, .cfg, .json) store app settings for future sessions.
Example: A text editor storing font size and theme preferences.

6️. Security & Backups


Data can be encrypted before storing it in a file for security.
Automated backup files prevent data loss in case of crashes.
Example: Password managers encrypt stored credentials.

7️. File Handling is Essential in Databases


Many database management systems (DBMS) use file handling to store records.
Structured files like CSV, JSON, XML serve as lightweight databases.
Example: SQL databases internally store data in files.

Types of Files in C++


In C++, files are mainly classified into two types based on how data is stored and accessed:
1️. Text Files
A text file stores data in a human-readable format using characters (ASCII or Unicode). Each line is
separated by newline (\n), and values may be separated by spaces, commas, or other delimiters.
Characteristics of Text Files
• Stores data in plain text format (e.g., .txt, .csv).
• Can be opened and edited using a basic text editor.
• Requires parsing when reading (converting numbers from text format).
• Larger in size due to extra storage for formatting (spaces, newlines).
• Slower than binary files due to extra conversion between characters and numbers.

Example: Writing & Reading a Text File


#include <iostream>
#include <fstream> // File handling library
using namespace std;

int main() {
ofstream file("example.txt"); // Create and open a text file
file << "Hello, File Handling in C++"; // Write data
file.close(); // Close the file

ifstream readFile("example.txt"); // Open file for reading


string content;
getline(readFile, content);
cout << "File Content: " << content << endl;
readFile.close();

return 0;
}

2️. Binary Files


A binary file stores data in raw binary format (0s and 1s), making it more compact and faster
than text files.
Characteristics of Binary Files
• Not human-readable; data is stored in binary (machine language).
• No need for data conversion (faster read/write operations).
• More efficient storage, as it does not include extra formatting characters.
• Can store complex data structures such as objects, arrays, and multimedia files.

Example: Writing & Reading a Binary File


#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream file("data.bin", ios::binary); // Open file in binary mode
int number = 1️00;
file.write(reinterpret_cast<char*>(&number), sizeof(number)); //
Write binary data
file.close();
ifstream readFile("data.bin", ios::binary); // Open binary file for
reading
int readNumber;
readFile.read(reinterpret_cast<char*>(&readNumber),
sizeof(readNumber));
cout << "Read from file: " << readNumber << endl;
readFile.close();

return 0;
}
File Stream Classes in C++
• C++ provides a set of file stream classes in the <fstream> header for handling file
input and output operations.
• These classes enable programs to read data from files and write data to files,
making file storage and retrieval easy.
• File handling is crucial for storing structured data, saving user input, logging
system activities, and managing databases.
Types of File Stream Classes
C++ provides three main file stream classes for handling different file operations.
Class Purpose Example Usage
ifstream Used for reading from a file ifstream inFile("data.txt");
ofstream Used for writing to a file ofstream outFile("output.txt");
fstream Used for both reading & writing `fstream file("data.txt", ios::in

Basic File Operations in C++


C++ provides file handling through the fstream library, which allows reading from and
writing to files using different modes. The basic file operations include:
1. Opening a File
2️. Writing to a File
3️. Reading from a File
4️. Closing a File
5️. File Opening Modes
1️. Opening a File
Files are opened using the open() function or directly in the constructor.
Example (Using Constructor)
ofstream file("example.txt"); // Opens file for writing
ifstream file("data.txt"); // Opens file for reading
Example (Using open() Method)
ofstream outFile;
outFile.open("output.txt"); // Open file for writing

Example: Opening a File for Writing


#include <iostream>
#include <fstream> // Include file handling library
using namespace std;

int main() {
ofstream file("example.txt"); // Open file for writing
if (file.is_open()) {
cout << "File opened successfully!" << endl;
} else {
cout << "Error opening file!" << endl;
}
file.close(); // Close the file
return 0;
}

2️. Writing to a File


Data can be written to a file using the ofstream or fstream class.
Data can be written using the insertion (<<) operator.
Example (Writing to a File)
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream outFile("output.txt"); // Open file for writing
outFile << "Hello, C++ File Handling!" << endl;
outFile << "Writing data to a file is simple." << endl;

outFile.close(); // Close file


return 0;
}
Note: ofstream overwrites existing content unless ios::app is used.

3️. Reading from a File


Data can be read using the ifstream or fstream class.
Data can be read using extraction (>>) operator or getline() function.
Example (Reading with >> Operator)
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream inFile("data.txt"); // Open file for reading
string word;
while (inFile >> word) { // Read word by word
cout << word << " ";
}
inFile.close(); // Close file
return 0;
}
Note: >> operator stops reading at spaces or newlines.
Example (Reading a Full Line with getline())
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream inFile("data.txt"); // Open file for reading
string line;

while (getline(inFile, line)) { // Read line by line


cout << line << endl;
}
inFile.close();
return 0;
}
Note: Use getline() for multi-word strings.

4️. Closing a File


After performing operations, always close the file using file.close() to free system resources.
Why is it important?
• Prevents data corruption.
• Ensures all data is saved properly.
• Avoids file locking issues in multi-threaded environments.

File Opening Modes


File opening modes in C++ determine how a file is accessed (read, write, append, etc.).
These modes are used with ifstream, ofstream, and fstream classes from the <fstream>
library. They define whether data is preserved, overwritten, or modified when a file is
opened
Mode Description
ios::in Open file for reading (default for ifstream).
ios::out Open file for writing (default for ofstream).
ios::app Open file in append mode (adds data to the end).
ios::ate Open file and move pointer to the end (useful for modification).
ios::trunc If file exists, delete content before writing.
ios::binary Open file in binary mode (for non-text data).
Examples of File Opening Modes
1️. Read Mode (ios::in)
Used to read an existing file. If the file does not exist, the operation fails.
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream file("data.txt", ios::in); // Open file for reading
if (!file) {
cout << "Error: File does not exist!" << endl;
return 1;
}

string content;
while (getline(file, content)) {
cout << content << endl;
}

file.close();
return 0;
}

2️. Write Mode (ios::out)


Used to write to a file. If the file exists, its content is erased before writing.
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream file("output.txt", ios::out); // Open file for writing (overwrite mode)
file << "This is a new file.\n";
file << "Previous content (if any) is erased!\n";

file.close();
return 0;
}
Note: Existing data is deleted when the file is opened.

3️. Append Mode (ios::app)


Used to add data at the end of a file without erasing previous content.
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream file("output.txt", ios::app); // Open file in append mode
file << "New line added at the end.\n";

file.close();
return 0;
}
Note: Existing content is preserved, and new data is added at the end.

4️. Truncate Mode (ios::trunc)


Clears the file’s content before writing. This mode is the default when ios::out is used.
ofstream file("output.txt", ios::trunc); // Clear content before writing
file << "Only this text remains in the file.";
file.close();
Note: Use this mode when you want to delete old content before writing.

5️. Binary Mode (ios::binary)


Opens a file in binary mode (used for images, audio, etc.).
ofstream file("data.bin", ios::binary | ios::out); // Open file in binary mode for writing
int num = 100;
file.write((char*)&num, sizeof(num)); // Write binary data
file.close();
Note: Use binary mode for non-text files like images, videos, or serialized objects.

6️. At End Mode (ios::ate)


Opens a file and moves the cursor to the end, allowing modification.
ifstream file("data.txt", ios::ate); // Open file and move pointer to the end
cout << "File size: " << file.tellg() << " bytes"; // Get file size
file.close();
Note: Useful when you need to determine the file size.

Example
C++ program to copy the contents of one file into another using file handling:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
string sourceFile, destinationFile;

// Get filenames from user


cout << "Enter source file name: ";
cin >> sourceFile;
cout << "Enter destination file name: ";
cin >> destinationFile;

// Open source file for reading


ifstream inFile(sourceFile, ios::in);
if (!inFile) {
cout << "Error: Cannot open source file!" << endl;
return 1;
}

// Open destination file for writing


ofstream outFile(destinationFile, ios::out);
if (!outFile) {
cout << "Error: Cannot open destination file!" << endl;
return 1;
}
// Copy content line by line
string line;
while (getline(inFile, line)) {
outFile << line << endl;
}
cout << "File copied successfully!" << endl;
// Close files
inFile.close();
outFile.close();
return 0;
}

You might also like