How do I read and write text and binary files in C++?

In C++, you can read and write text and binary files using file streams provided by the STL (Standard Template Library). The main classes used for file handling are ifstream for reading files, ofstream for writing files, and fstream for both reading and writing.

Below are examples demonstrating how to read from and write to both text and binary files:

// Example of writing to a text file #include #include int main() { std::ofstream outFile("example.txt"); outFile << "Hello, World!" << std::endl; outFile.close(); // Example of reading from a text file std::ifstream inFile("example.txt"); std::string line; while (std::getline(inFile, line)) { std::cout << line << std::endl; } inFile.close(); // Example of writing to a binary file std::ofstream outBin("example.bin", std::ios::binary); int num = 12345; outBin.write(reinterpret_cast(&num), sizeof(num)); outBin.close(); // Example of reading from a binary file std::ifstream inBin("example.bin", std::ios::binary); int readNum; inBin.read(reinterpret_cast(&readNum), sizeof(readNum)); std::cout << "Read from binary file: " << readNum << std::endl; inBin.close(); return 0; }

C++ file handling text files binary files ifstream ofstream fstream file streams STL