一次读取两个字节的 .dat 文件

Ono*_*Ono 5 c++ file-io

我有一个 .dat 文件,如下所示:

NUL NUL NUL ...
Run Code Online (Sandbox Code Playgroud)

所以这个 .dat 文件中的每个条目都是一个 16 位有符号整数。我想使用 C++ 一次读取两个字节。这是目前我阅读它的代码

short* ReadData(char* fileName, long imgWidth, long imgHeight, long bytePerPixel)
{
    short * pData = new short[imgWidth*imgHeight*bytePerPixel];
    short h1;
    try
    {       
        std::ifstream input(fileName, std::ios::binary);
        while(!input.eof())    
        {
            //Read file one byte at a time
            input.read(&h1, sizeof(short));
        }
        return pData;
    }
    catch(int i)
    {
        return NULL;
    }

    delete pData;
}
Run Code Online (Sandbox Code Playgroud)

但它给了我错误,因为

input.read(&h1, sizeof(short));
Run Code Online (Sandbox Code Playgroud)

一次读取一个字节。我想一次读取 2 个字节。无论如何我可以做到这一点吗?或者读取其中有一堆 16 位有符号整数的 .dat 文件的最佳方法是什么?谢谢

oog*_*oga 3

read将读取您要求它读取的字节数。但您没有将数据放入pData数组中。并且您需要将第一个参数转换为char *.