使用同一个对象写入宽字符和字符写入同一个文件

Using same object to write wide char and char to write to the same file

我尝试将 C 代码转换为 C++。总结一段C语言的代码如下:

    FILE *fp = fopen("temp.bin", "wb");
    wchar_t* wide_word = _T("wide char");
    char* word = "char";
    fwprintf(fp, _T("%s"), wide_word);
    fprintf(fp, "%s", word);

在 C 案例中的优势是我们可以继续使用相同的 fp 指针通过简单地传递指针来打印 char 和 wide char。我们能否在 C++ 中实现相同的功能而无需初始化对象 ofstreamwofstream 以写入同一文件并获得与上述 C 实现完全相同的输出?

我在 C++ 中尝试了以下内容(以及许多其他内容)

    auto os = std::ofstream("temp_cpp.bin", std::ios::binary | std::ios::out);
    wchar_t* wide_word = _T("wide char");
    char* word = "char";
    std::wstring st(wide_word);
    std::string str(st.begin(),st.end());
    os.write(reinterpret_cast<const char*>(str.c_str()), sizeof(str));
    os.write(reinterpret_cast<const char*>(word), sizeof(word));

是的,您可以使用相同的 write 函数将 ANSI 字节或宽字符字节写入文件。代码中有一些错误。 sizeof(str) 将 return std::string 对象的大小,而不是字符串的长度,并且 sizeof(word) 将 return 指针的大小,同样不是长度字符串的长度(尽管在指针大小与字符串长度匹配的 32 位系统上,您可能很幸运)。此外,您正在编写两次 ANSI 字符,而不是先编写宽字符,然后按照您的 fprintf 示例可能打算编写 ANSI 字符。你想写的可能是:

auto os = std::ofstream("temp_cpp.bin", std::ios::binary | std::ios::out);
const wchar_t* wide_word = L"wide char";
const char* word = "char";
std::wstring st(wide_word);
std::string str(st.begin(), st.end());
os.write((const char*)(st.c_str()), st.length() * sizeof(wchar_t));
os.write(word, strlen(word));

这应该会产生与您的 fprintf 示例相同的文件内容(但不能保证,因为它可能取决于 setLocale)。或者,不使用 std::wstring:

auto os = std::ofstream("temp_cpp.bin", std::ios::binary | std::ios::out);
const wchar_t* wide_word = L"wide char";
const char* word = "char";
os.write((const char*)wide_word, wcslen(wide_word) * sizeof(wchar_t));
os.write(word, strlen(word));

将不同的文本编码写入同一个文件是否可取是另一个问题。