ostream_iterator for Binary Output

后端 未结 3 830
时光取名叫无心
时光取名叫无心 2021-01-22 06:47

I want to be able to use an ostream_iterator to stream to a binary file. But the ostream_iterator uses a FormattedOuputFunction so it will write ASCII, not binary:<

3条回答
  •  青春惊慌失措
    2021-01-22 07:34

    For algorithms that only use an InputIterator or ForwardIterator for the input, a simple cast is sufficient. For more complex algorithms writing a wrapper, writing a specialized iterator, or using Boost functionality may be necessary. Provided the algorithm input aligns with those conditions, something like this will work:

    ofstream foo("foo.txt", ios_base::binary);
    vector bar = {13, 42};
    
    copy(reinterpret_cast(&*bar.cbegin()), reinterpret_cast(&*bar.cend()), ostreambuf_iterator(foo));
    

    Obviously this needs to be round trip certified before it can be considered dependable. Validating that the values in output are consecutive can be tedious so code was hijacked from here to do that:

    ofstream foo("foo.txt", ios::binary);
    vector bar(numeric_limits::max() + 1);
    
    iota(bar.begin(), bar.end(), 0);
    
    copy(reinterpret_cast(&*bar.data()), reinterpret_cast(&*bar.data() + bar.size()), ostreambuf_iterator(foo));
    foo.close();
    
    ifstream file_read("foo.txt", ios::binary);
    vector output(bar.size());
    
    copy(istreambuf_iterator(file_read), istreambuf_iterator(), reinterpret_cast(&*output.data()));
    
    cout << "First element: " << output.front() << "\nLast element: " << output.back() << "\nAny non-consecutive elements: " << (output.cend() == mismatch(output.cbegin(), prev(output.cend()), next(output.cbegin()), [](auto first1, auto first2) { return first1 + 1 == first2; }).second ? "no\n" : "yes\n");
    

    The output from this demonstrates that this method is actually successful:

    First element: 0
    Last element: 255
    Any non-consecutive elements: no

    Although not every possible int was tried, every possible char was tried, and since any int can be made up of a collection of chars this demonstrates that any collection of ints is streamable this way.

提交回复
热议问题