How to save a file with GetSaveFileName in win32?

I am writing this code to get fileName to save my file:

#include "stdafx.h" #include <windows.h> int _tmain(int argc, _TCHAR* argv[]) { OPENFILENAME ofn; char szFileName[MAX_PATH] = ""; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = NULL; ofn.lpstrFilter = (LPCWSTR)L"Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0"; ofn.lpstrFile = (LPWSTR)szFileName; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; ofn.lpstrDefExt = (LPCWSTR)L"txt"; GetSaveFileName(&ofn); printf("the path is : %s\n", ofn.lpstrFile); getchar(); return 0; } 

But the way out:

  the path is : H 

why? Am I something wrong? I am using Visual Studio 2008 on Windows 7.

+8
c ++ winapi savefiledialog
source share
3 answers

This line:

 printf("the path is : %s\n", ofn.lpstrFile); 

should use the wide char print version.

 wprintf(L"the path is : %s\n", ofn.lpstrFile); 
+8
source share

The root problem in these lines is:

 char szFileName[MAX_PATH] = ""; ... ofn.lpstrFile = (LPWSTR)szFileName; ofn.nMaxFile = MAX_PATH; 

This creates the MAX_PATH character buffer, but it tells the GetSaveFileName function that it is the MAX_PATH character buffer. This could probably lead to a crash (or quiet memory loss) when someone selects a long path name.

Brushstroke is the cast. Do not lie to the compiler or libraries. They do not like it, and in the end they will always take revenge. Replace these lines as follows:

 WCHAR szFileName[MAX_PATH] = L""; ... ofn.lpstrFile = szFileName; // no cast needed ofn.nMaxFile = MAX_PATH; 

Now the selected file name will be returned as a string with wide characters. Tony Lion's answer is correct in that you need to use wprintf instead of printf to print wide character strings:

 wprintf(L"the path is : %s\n", ofn.lpstrFile); // though I'd use szFileName at this point 

If you need a string in 8-bit characters instead of wide characters, you can use WideCharToMultiByte. But I would just stick with the broad character APIs in general.

Never give up if you do not know exactly what he is doing and why it is necessary in your particular case.

+8
source share

You are both mistaken, this is a simple C pointer / stack issue.

 // WRONG: char szFileName[MAX_PATH] = ""; 

This confuses arrays and pointers, you declare an array on the stack, but then change its memory address to point to an empty string in the data section. In other words, buffer overflow.

 // RIGHT: char szFileName[MAX_PATH]; ZeroMemory(szFileName, MAX_PATH); 

This declares an array of characters on the stack and initializes all elements with a null terminator.

Hope this helps!

-one
source share

All Articles