0

I would like to know if writing to the same file with std::string and std::wstring objects is safe for sure. I have a snippet like this:

void foo(std::string&& msg) {
    std::ofstream file{ "log.txt", std::ios_base::app };
    file << msg << '\n';
}

void foo(std::wstring&& msg) {
    std::wofstream file{ "log.txt", std::ios_base::app };
    file << msg << '\n';
}

int main() {
    foo(std::string{ "sample string text" });
    foo(std::wstring{ L"sample wstring text" });
}

I am not sure if there are no problems with encoding when using this code or these problems may occur in specific situations. Has anyone an idea for dangers associated with it?

Evelekk
  • 159
  • 7
  • What you mean by "safe"? It does not crash but it is unlikely to be useful file log.txt in unknown directory with two nonsense strings in it. . – Öö Tiib Dec 17 '19 at 19:53
  • 1
    Your file has a `.txt` extension, which implies that programs opening it should be decoding the binary data inside it with some sort of binary-to-text encoding... like UTF-8, or UTF-16. If you write both wide (16-bit) characters and 8-bit characters to a *text* file, you are not likely to be forming a text file that is compliant with any standard text encoding scheme. It's still a perfectly valid *binary* file (*with a misleading extension*), but only useful if you have written some code to read it back correctly. – Romen Dec 17 '19 at 20:36

0 Answers0