Reading a .dat file two bytes at a time

I have a .dat file, for example:

NUL NUL NUL ...

Thus, each entry inside this .dat file is a 16-bit signed integer. I want to use C ++ to read two bytes at a time. This is currently my code to read it

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;
}

But that gives me an error because

input.read(&h1, sizeof(short));

reads a byte at a time. I want to read 2 bytes at a time. Anyway, can I do this? Or what is the best way to read a .dat file inside which there is a bunch of 16-bit signed int? Thanks

+3
source share
2 answers

readwill read, however, a lot of bytes that you ask to read. But you do not put data in your array pData. And you need to pass the first argument char *.

+3

input.read(&h1,2);  //the number 2 indicates the
                    //number of bytes you are 
                    //reading at a time    

 input.read(&h1, sizeof(short));  

eof(),
( , ... )

-2

All Articles