File I/O Functions
C++ File I/O Operations
Writing to a File (Output):
- Open a File:
- Write Data to the File:
- Append Data to a File:
#include <fstream>
int main() {
std::ofstream outputFile("example.txt");
// Write data to the file
outputFile.close(); // Close the file when done
return 0;
}
outputFile << "Hello, File I/O!" << std::endl;
std::ofstream outputFile("example.txt", std::ios::app);
Reading from a File (Input):
- Open a File for Reading:
- Read Data from the File:
- Check for End-of-File (EOF):
- Check if File is Open:
#include <fstream>
int main() {
std::ifstream inputFile("example.txt");
// Read data from the file
inputFile.close(); // Close the file when done
return 0;
}
std::string word;
inputFile >> word; // Read a word
std::string line;
std::getline(inputFile, line); // Read a line
while (!inputFile.eof()) {
// Read data from the file
}
if (inputFile.is_open()) {
// File operations
} else {
std::cerr << "Unable to open the file." << std::endl;
}
Error Handling:
- Exception Handling:
try {
// File operations
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
These examples cover the basic operations for file I/O in C++. Depending on your specific requirements, you may need to explore more advanced features, such as binary file I/O, random access, and handling different file formats. Always remember to handle errors appropriately to ensure robust file handling.