Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Why this code don't function?

19 views
Skip to first unread message

Bertram

unread,
May 24, 2013, 5:47:37 AM5/24/13
to

Hi all

This code is compiling with MinGW on WinXp.

Why this code don't function?

The file Myfile.txt, is not created and saved.

OPENFILENAME ofn;
HANDLE hf;
HWND hwnd = NULL;

char FileName[1024]="MyFile.txt";

memset(&ofn, 0, sizeof(ofn));
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = FileName;
ofn.nMaxFile = sizeof(FileName);
ofn.hInstance = NULL;
ofn.lpstrFilter = TEXT("All\0*.*\0Text\0*.TXT\0");
ofn.nFilterIndex = 1;
ofn.lpstrInitialDir = "K:\\";

if (GetSaveFileName(&ofn)==TRUE)
hf = CreateFile(ofn.lpstrFile, GENERIC_READ,
0, (LPSECURITY_ATTRIBUTES) NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
(HANDLE) NULL);

return 1;
};



Paul N

unread,
May 24, 2013, 6:43:06 AM5/24/13
to
In what way doesn't it fuction? Does it not compile, or does it
compile but then go wrong when you use it? And please give a few more
details.

At a guess, it won't work as it stands in Unicode mode as you are
using chars for some of it. You could make it work in both Unicode and
non-Unicode modes by using TCHARs, but you would also have to change
the line sizeof(FileName).

ScottMcP [MVP]

unread,
May 24, 2013, 8:48:37 AM5/24/13
to
Comparing the return value of GetSaveFileName to TRUE is unreliable. It returns "non zero" but TRUE is only one of many possible non-zero values. Just do

if (GetSaveFileName(&ofn))

You have not asked CreateFile for write access (use GENERIC_READ | GENERIC_WRITE), so it will not open the file for writing. Also, by specifying OPEN_EXISTING you can open the file only if it already exists. This is not consistent with letting the user edit the file name.

Also, if these issues were fixed you have to write some data and then close the handle.

Geoff

unread,
May 24, 2013, 11:37:54 AM5/24/13
to
On Fri, 24 May 2013 11:47:37 +0200, "Bertram" <nos...@nospam.or>
wrote:
If it compiles it probably malfunctions because CreateFile with
GENERIC_READ and OPEN_EXISTING will NEVER create a file.

You must use GENERIC_WRITE or GENERIC_READ | GENERIC_WRITE along with
CREATE_ALWAYS or it will fail.

You also don't check to see if CreateFile succeeded, hf != NULL.

Ex:

// this will always overwrite the output file.
hf= CreateFile(ofn.lpstrFile, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

if (!hf)
{
swprintf_s(s, L"Unable to open file %s", ofn.lpstrFile);
MessageBox(hWnd, s, NULL, NULL);
return true;
}

...
0 new messages