使用 ifstream 从C++文件中读取二进制无符号短整型

Reading binary unsigned short from a file in C++ using ifstream

本文关键字:读取 二进制 无符号 短整型 文件 ifstream C++ 使用      更新时间:2023-10-16

我有以下由C语言编写的示例代码。
以下代码的函数从 jpg 图像文件中读取前两个字节。

unsigned short buff;
FILE *file;
file = fopen("image.jpg", "rb");
if(file != NULL){
    fread(&buff, sizeof(unsigned short), 1, file);
    fclose(file);
    printf("%Xn", buff);
}else{
    printf("File does not exists.");
}

结果:
D8FF

这就是我试图在C++中写的:

char fBuff[4];
ifstream file("image.jpg", ios::binary);
if(file.is_open()){
    file.read(fBuff, sizeof(char)*4);
}else{
    cout << "File does not exists." << endl ;
}
for(int i=0;i<4;i++)
    cout << ios_base::hex << fBuff[i];

c ++代码中的问题,它错误地给了我数据。

我想要的是,将fread()更改为C++中相应的相应功能。但是其他函数如fopenfcloseprintf等,我知道C++对应的。

我认为这就是你需要的。

std::ifstream  file;
unsigned short buff;
file.open("image.jpg", std::ios::in | std::ios::binary);
if (file.is_open() == true)
{
    if (file.read(reinterpret_cast<char *>(&buff), sizeof(buff)) != 0)
        std::cout << std::hex << std::uppercase << buff << std::endl;
    file.close();
} else {
    std::cout << "File does not exists" << std::endl;
}

解决方案:

istream& read (char* s, streamsize n)
s - Pointer to an array where the extracted characters are stored.
n - Number of characters to extract.

reinterpret_cast<char *> might be needed for some people

这会像阅读一样读取文件。

istream& get (streambuf& sb, char delim);
istream& getline (char* s, streamsize n );