How to use Win32 API to specify directory to write file to using WriteFile?

727 Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

The _T() macro can only be used with literals (same with the TEXT() macro). And you are not escaping the slashes in your literal.

The C runtime uses the _T() macro. The Win32 API uses the TEXT() 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 calling WriteFile().

Use this instead:

LPTSTR filePathAndName = TEXT("C:\\Projects\\pic.bmp");
HANDLE hFile = CreateFile(filePathAndName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 
...
WriteFile(hFile, &bmfHeader, sizeof(BITMAPFILEHEADER), &dwBytesWritten, NULL);
WriteFile(hFile, &bi, sizeof(BITMAPINFOHEADER), &dwBytesWritten, NULL);
WriteFile(hFile, lpbitmap, dwBmpSize, &dwBytesWritten, NULL);

With that said, typically you should be prompting the user for the output filename, either with GetSaveFileName() or IFileSaveDialog. Or at least prompt for the destination folder using SHBrowseForFolder() (or IFileSaveDialog, which also supports picking a folder) if you want to use your own filename.

0
On

This is your problem:

char *filePathAndName = "C:\Projects\pic.bmp";

Backslash in a string or character literal indicates a special character. For example, \t for tab or \n for newline. The compiler should have complained that \P and \p aren't valid.

If you have a string that contains real backslashes, you need to double them:

char *filePathAndName = "C:\\Projects\\pic.bmp";