Input/Output (I/O) operations and file processing are essential aspects of C++ programming. They allow interaction with external devices (like keyboards, screens) and the ability to read from or write to files, which are key for persistent data storage.
C++ provides several libraries for handling I/O operations and file processing:
cin, cout, cerr, and clog.fstream, ifstream, and ofstream.Standard I/O is used to interact with the console (screen for output and keyboard for input). C++ provides several predefined streams for console I/O.
The output in C++ is typically done using the cout object, which is part of the <iostream> header. The << operator is used to send data to the console.
#include <iostream>
using namespace std;
int main() {
int number = 5;
cout << "Hello, World!" << endl;
cout << "The number is: " << number << endl;
return 0;
}
Explanation:
cout: The standard output stream.<<: The stream insertion operator that inserts data into the output stream.Output:
Hello, World!
The number is: 5
For input, C++ uses the cin object, which reads input from the keyboard. The >> operator is used to extract data from the input stream.
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
cout << "You entered: " << number << endl;
return 0;
}
Explanation:
cin: The standard input stream.>>: The stream extraction operator that extracts data from the input stream.Output (user input is assumed):
Enter a number: 10
You entered: 10
File I/O in C++ is accomplished using the file stream classes, which allow for reading from and writing to files. The classes are:
ifstream: Input file stream used to read from files.ofstream: Output file stream used to write to files.fstream: A combination of both ifstream and ofstream, used for both reading and writing.These classes are defined in the <fstream> header.
Before performing I/O operations, a file must be opened using the open() method or by directly passing the file name to the constructor of ifstream, ofstream, or fstream.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create an object of ofstream (output file stream)
ofstream outFile("example.txt");
// Check if the file was successfully opened
if (!outFile) {
cout << "File could not be opened!" << endl;
return 1; // Exit if file opening fails
}
// Write to the file
outFile << "This is a line written to the file." << endl;
// Close the file
outFile.close();
return 0;
}
Explanation:
ofstream object outFile opens the file example.txt for writing.close().Output (in example.txt):
This is a line written to the file.
Reading from a file is done using the ifstream class, which reads from an existing file.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create an object of ifstream (input file stream)
ifstream inFile("example.txt");
// Check if the file was successfully opened
if (!inFile) {
cout << "File could not be opened!" << endl;
return 1; // Exit if file opening fails
}
string line;
// Read and display each line from the file
while (getline(inFile, line)) {
cout << line << endl;
}
// Close the file
inFile.close();
return 0;
}
Explanation:
ifstream object inFile opens the file example.txt for reading.getline() reads a line of text from the file and stores it in the string variable line.Output:
This is a line written to the file.
fstream (Reading and Writing)If you need both reading and writing capabilities for the same file, you can use the fstream class.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create an object of fstream (input-output file stream)
fstream file("example.txt", ios::in | ios::out);
// Check if the file was successfully opened
if (!file) {
cout << "File could not be opened!" << endl;
return 1; // Exit if file opening fails
}
string line;
// Read and display the current content of the file
while (getline(file, line)) {
cout << "Reading from file: " << line << endl;
}
// Write a new line to the file
file.clear(); // Clear any EOF flag
file.seekp(0, ios::end); // Move the write pointer to the end
file << "This is a new line added to the file." << endl;
// Close the file
file.close();
return 0;
}
Explanation:
fstream object file is opened with both input and output flags (ios::in | ios::out).seekp() to append new content.clear() function is used to clear any EOF flag set by reading.File operations in C++ are controlled by file modes, which determine the way files are opened. The file mode is specified when opening a file and can be set using the ios flags.
Common file modes include:
ios::in: Open for reading.ios::out: Open for writing.ios::app: Open for appending (writing at the end of the file).ios::ate: Open for reading and writing. The file pointer is at the end when opened.ios::trunc: Truncate the file to zero length when opened (the file is emptied).ios::binary: Open in binary mode (default is text mode).Example of using different file modes:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Open file in append mode
ofstream outFile("example.txt", ios::app);
if (!outFile) {
cout << "Failed to open file!" << endl;
return 1;
}
outFile << "Adding this line at the end." << endl;
outFile.close();
return 0;
}
C++ provides methods to check for file errors, ensuring robust file handling:
is_open(): Checks if the file was successfully opened.eof(): Checks if the end-of-file has been reached.fail(): Checks if an error occurred during the last file operation.clear(): Clears error flags like eof() or fail().Example of checking if a file opens successfully:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream inFile("nonexistent.txt");
if (!inFile) {
cout << "Error: Unable to open file." << endl;
return 1;
}
// Read from the file if it opened successfully
inFile.close();
return 0;
}
cin and cout for reading and writing data to and from the console.ifstream, ofstream, and fstream to handle file reading, writing, and both operations.By understanding and using I/O and file processing efficiently, you can interact with users and work with persistent data in C++ applications.
Open this section to load past papers