Why can't I read fstream's binary data with operator>>?

前端 未结 2 695
余生分开走
余生分开走 2020-12-15 06:32

If I do something like the following:

ifstream file;
file.open(\"somefile\", ios::binary);

unsigned int data;

file >> data;

My stre

2条回答
  •  死守一世寂寞
    2020-12-15 07:24

    It should be done as described by you. However, the C++ standard designers are not very elegant. In fact, there are a lot of flaws in the design of C++, even C++11 and C++14 has lots of defects.

    The ideal C++ design should be that:

    1.For text file:

    ifstream fin_txt("input.txt");
    int i;
    float j;
    double k;
    fin_txt >> i >> j >> k;
    

    This will read in 3 strings and parse into integer, float and double, and store them into i, j, and k respectively.

    2.For binary file:

    ifstream fin_txt("input.bin", ios::binary);
    int i;
    float j;
    double k;
    fin_txt >> i >> j >> k;
    

    This will read in 4/8 bytes (depending on whether int is 32-bit or 64-bit), 4 bytes and 8 bytes binary data and store them into i, j, and k respectively.

    Unfortunately, the current design is to report an error for Case 2. Maybe this can be achieved in C++22.

提交回复
热议问题