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;
}
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?