I've used the following to get a handle to a file:
char *filePathAndName = "C:\Projects\pic.bmp";
HANDLE hFile = CreateFile(_T(filePathAndName),GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
and I've used the following to write the file:
WriteFile(hFile, (LPSTR)&bmfHeader, sizeof(BITMAPFILEHEADER), &dwBytesWritten, NULL);
WriteFile(hFile, (LPSTR)&bi, sizeof(BITMAPINFOHEADER), &dwBytesWritten, NULL);
WriteFile(hFile, (LPSTR)lpbitmap, dwBmpSize, &dwBytesWritten, NULL);
However, the file writes to the project directory (i.e. where the Microsoft Visual Studio Solution file exists) rather than to the C:\Projects\ directory.
How can I write the .bmp file to a specified directory?
The
_T()
macro can only be used with literals (same with theTEXT()
macro). And you are not escaping the slashes in your literal.The C runtime uses the
_T()
macro. The Win32 API uses theTEXT()
macro. You should not mix them, even though they effectively do the same thing. Use the correct macro for the API you are using.And you don't need to type-cast data to
LPSTR
when callingWriteFile()
.Use this instead:
With that said, typically you should be prompting the user for the output filename, either with
GetSaveFileName()
orIFileSaveDialog
. Or at least prompt for the destination folder usingSHBrowseForFolder()
(or IFileSaveDialog, which also supports picking a folder) if you want to use your own filename.