ifstream不读取文件中存在的`0a`字节

ifstream does not read `0a` byte existing in the file

本文关键字:0a 字节 存在 读取 文件 ifstream      更新时间:2023-10-16

我想读取文件的前7个字节。这是我文件的数据:

42 4d b6 fc 0a 00 00

我使用此代码来做到这一点:

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int main()
{
    ifstream r("TestFile.abc", ios::binary);
    unsigned char info[7];
    for(int i = 0 ; i < 7; i++){
        r >> info[i];
    }
    for(int i = 0 ; i < 7; i++){
      std::stringstream ss;
      ss << std::hex << (int) info[i]; // int decimal_value
      std::string res ( ss.str() );
      cout << i << setw(10) << info[i] << setw(10) << res << endl;
    }

   return 0;;
}

这是输出:

0         B        42
1         M        4d
2         ╢        b6
3         ⁿ        fc
4                   0
5                   0
6                   0
Process returned 0 (0x0)   execution time : 0.032 s
Press any key to continue.

为什么0a字节已替换为0

>>跳过空白, 0a是一个withespace字符。尝试这个

info[i] = r.get();

get读取单个字节而无需跳过任何内容(除了可能的线转换之端,但是您已经通过使用ios::binary为此而对此进行了。