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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?