{"type": "session", "harness": "opencode", "id": "polyglot-0003", "name": "UTF-8 file stats in C++"} {"type": "message", "message": {"role": "system", "content": "You are an expert software engineer. You give correct, idiomatic, runnable code with brief explanations."}} {"type": "message", "message": {"role": "user", "content": "How do I count lines, words, characters and bytes of a UTF-8 text file? Show me the C++ version."}} {"type": "message", "message": {"role": "assistant", "content": "In C++17 there is no Unicode-aware string: `std::string::size()` is bytes. Count UTF-8 lead bytes (any byte that is not a `10xxxxxx` continuation) to get code points.\n\n```cpp\n#include \n#include \n#include \n#include \n#include \n\nint main() {\n const std::string text = \"Olá mundo! Ação, coração.\\nSegunda linha: Straße, 你好.\\n\";\n {\n std::ofstream out(\"sample.txt\", std::ios::binary);\n out << text;\n }\n std::ifstream in(\"sample.txt\", std::ios::binary);\n std::ostringstream ss;\n ss << in.rdbuf();\n const std::string data = ss.str();\n const long bytes = static_cast(data.size());\n long chars = 0;\n for (unsigned char c : data) {\n if ((c & 0xC0) != 0x80) ++chars; // count lead bytes only\n }\n long words = 0, lines = 0;\n { std::istringstream ws(data); std::string w; while (ws >> w) ++words; }\n { std::istringstream ls(data); std::string l; while (std::getline(ls, l)) ++lines; }\n std::cout << \"lines=\" << lines << \" words=\" << words\n << \" chars=\" << chars << \" bytes=\" << bytes << \"\\n\";\n assert(lines == 2 && words == 8);\n assert(bytes > chars);\n return 0;\n}\n```"}}