Search code examples
c++c++17ofstream

Write a sequence of byte data using basic_ofstream


I have a info_list variable of type std::list<std::pair<std::size_t, std::byte*>> that I want to iterate and save data in binary format sequentially into a file. Here is what I tried:

void write_data() {
    std::basic_ofstream<std::byte> file("data.bin", std::ios::binary);
    for (decltype(auto) info : info_list) {
        file.write(info.second, info.first);
    }
}

The first of the std::pair is the size of the data that second pointer points to.

I'm not good with these C++ streams. The file is being saved empty. What am I doing wrong?

I'd like to avoid using C features to achieve this.

EDIT:

I tried using std::ofstream instead of std::basic_ofstream<std::byte> and it worked... Why std::basic_ofstream<std::byte> is not working here? Am I missing something?


Solution

  • Here is what you're missing: When using std::basic_ofstream<std::byte>, you are actually instantiating std::basic_ofstream<std::byte, std::char_traits<std::byte>>.

    The problem lies with std::char_traits, since the Standard specializations (types for which the behavior is well-defined) are:

    std::char_traits<char>
    std::char_traits<wchar_t>
    std::char_traits<char16_t>
    std::char_traits<char32_t>
    std::char_traits<char8_t>
    

    Unlike std::ofstream that uses a specialization defined in the standard library (namely std::char_traits<char>), your code uses std::char_traits<std::byte>. To proceed with such an implementation, you have to provide the missing specialization.