Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to use iostreams with int as character-type?

Tags:

c++

iostream

When trying to come up with an answer to this question, I wrote this little test-program:

#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>

void writeFile() {
    int data[] = {0,1,2,3,4,5,6,7,8,9,1000};

    std::basic_ofstream<int> file("test.data", std::ios::binary);
    std::copy(data, data+11, std::ostreambuf_iterator<int>(file));
}

void readFile() {
    std::basic_ifstream<int> file("test.data", std::ios::binary);
    std::vector<int> data(std::istreambuf_iterator<int>(file),
        (std::istreambuf_iterator<int>()));

    std::copy(data.begin(), data.end(), 
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;
}


int main()
{
    writeFile();
    readFile();

    return 0;
}

It works as expected, writing the data to the file, and after reading the file, it correctly prints:

0 1 2 3 4 5 6 7 8 9 1000

However, I am not sure if there are any pitfalls (endianess issues aside, you always have these when dealing with binary data)? Is this allowed?

like image 750
Björn Pollex Avatar asked Mar 31 '11 08:03

Björn Pollex


1 Answers

It works as expected.

I'm not sure what you are expecting...

Is this allowed?

That's probably not portable. Streams relies on char_traits and on facets which are defined in the standard only for char and wchar_t. An implementation can provides more, but my bet would be that you are relying on a minimal default implementation of those templates and not on a conscious implementation for int. I'd not be surprised that a more in depth use would leads to problems.

like image 84
AProgrammer Avatar answered Oct 02 '22 21:10

AProgrammer