ostream_iterator for Binary Output

后端 未结 3 761
时光取名叫无心
时光取名叫无心 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:39

    It works, but you will have to explicitely use an ostream_iterator.

    Example (includes omitted for brievety):

    int main(int argc, char **argv) {
        std::vector arr;
    
        std::ofstream fd("foo.txt", std::ios::binary | std::ios::out);
    
        for (int i=0; i<256; i++) arr.push_back(i);
    
        std::ostream_iterator oi(fd);
        std::copy(arr.begin(), arr.end(), oi);
        fd.close();
        return 0;
    }
    

    will write the 256 bytes for 0 to 255 in foo.txt.


    Above assumed that you wanted to write directly the value of the int as a char to the file. From your comment, you want to write the int value as a 4 bytes value (assuming int32_t) in native host endianness. I would use an auxilliary class to do the job:

    class bint {
    private:
        char c[sizeof(int)];
    
    public:
        bint(const int i) { // allows bint b = 5;
            ::memcpy(c, &i, sizeof(c));
        }
        operator int() const {  // allows : bint b = 5; int i=b => gives i=5
            int i;
            ::memcpy(&i, c, sizeof(int));
            return i;
        }
        const char *getBytes() const { // gives public read-only access to the bytes
            return c;
        }
    };
    
    std::ostream& operator <<(std::ostream& out, const bint& b) {
        out.write(b.getBytes(), sizeof(int));
        return out;
    }
    
    int main(int argc, char **argv) {
        std::vector arr;
    
        std::ofstream fd("foo.txt", std::ios::binary | std::ios::out);
    
        for (int i=0; i<256; i++) arr.push_back(i);
    
        std::ostream_iterator oi(fd);
        std::copy(arr.begin(), arr.end(), oi);
        fd.close();
        return 0;
    }
    

    This one writes 1024 bytes (for integer of size 4) containing the representations of the 256 first integers. It would automatically adapts to other sizes of int.

提交回复
热议问题