How do I handle file encodings safely in C++?

Handling file encodings safely in C++ involves using appropriate libraries and techniques to read and write files. Special care should be taken to ensure that files are opened in binary mode and that any necessary encoding conversions are performed.

#include <iostream> #include <fstream> #include <string> void writeFile(const std::string& filename, const std::string& content) { std::ofstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Unable to open file for writing"); } file << content; file.close(); } std::string readFile(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Unable to open file for reading"); } std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); file.close(); return content; } int main() { try { std::string filename = "example.txt"; std::string content = "Hello, World! This is a test with UTF-8 encoding."; writeFile(filename, content); std::string readContent = readFile(filename); std::cout << "File content: " << readContent << std::endl; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; }

C++ file encoding UTF-8 file handling binary mode