How do I read a bitmap or jpeg file into a byte array in Microsoft unmanaged C++?


It's been many years since I last did any C++ coding.
I'm writing in VS unmanaged C++.

This is probably a pretty basic question.

How do I read either a bitmap or jpeg file into a byte array?
(Byte is typedef'd as "unsigned char")

jxbmaSoftware ConsultantAsked:
Who is Participating?
sarabandeConnect With a Mentor Commented:
the second sample of jkr has a typo and the read statement will not compile because ifstream::read expects a char buffer rather than a byte buffer. normally, you also would call stat function before opening the stream. so when turning jkr's code snippet to a function, it would look like

bool readBinaryFile(const std::string & strFilePath, std::vector<unsigned char>& byteArr)
       struct stat filestat = { 0 };
       if (stat(strFilePath.c_str(), &filestat) != 0)
            return false;    // error, probably 'file not found'.  use errno or GetLastError() to know more

       std::ifstream ifs(strFilePath.c_str(), std::ios::binary | std::ios::in);

       if (!ifs)
            return false; // error probably 'access denied'
       // allocate memory

       if (!*)&byteArr[0], filestat.st_size))
            return false; // the read rarely fails beside you remove the stick while reading
       return true;

Open in new window

you would call the function like

std::string filename = "c:\\temp\\bitmap.bmp";
std::vector<unsigned char> buffer;

if (readBinaryFile(filename, buffer) && !buffer.empty())
        size_t size = buffer.size();
        showBitmap(&buffer[0], size);  // you could pass byte vector as BYTE* to other functions

Open in new window

jkrConnect With a Mentor Commented:
Since you'll end up having to you functions outside the 'std' namespace to obtain e.g. the file's size, why now using the Windows API directly? E.g.

#include <windows.h>
#include <tchar.h>


HANDLE hFile = CreateFile(_T("image.jpg"), FILE_READ,0,NULL, OPEN_EXISTING,0,NULL);

DWORD dwSize = GetFileSize(hFile,NULL);

BYTE* buf = new BYTE[dwSize];

DWORD dwRead = 0;


Open in new window

(error echecking omitted for brevity)

Using STL classes, that could be like

#include <fstream>
#include <sys/stat.h> // for '_stat()'

using namespace std;

//  ...

ifstram is("image.jpg",ios_base::binary);

struct _stat status;


BYTE* buf = new BYTE[status.st_size];,status.st_size);

Open in new window

Of course, you could still do that the C way, but since using 'fopen()/fread()' was your goal, you'd have asked in the C area (and it is basically similar to the above)
jxbmaSoftware ConsultantAuthor Commented:
Thanks man!
All Courses

From novice to tech pro — start learning today.