从文件保存对话框返回文件名(windows32)

发布于 2024-10-11 06:24:36 字数 790 浏览 4 评论 0原文

我有一个简单的保存文件对话框,我希望将其用作返回文件路径、名称和扩展名的工具。该函数会产生一个运行时错误,表明文件名周围的堆栈已损坏。我希望像这样使用它:

wchar_t filename[] = L"";
newGradebookDialog( hwnd, filename );

这是我的功能。它按照我的预期修改文件名,但我没有得到运行时堆栈错误。

void newGradebookDialog( HWND hwnd, wchar_t file[] )
{
 OPENFILENAME ofn;

 wchar_t saveFileName[MAX_PATH] = L"";

 ZeroMemory( &ofn, sizeof( ofn ) );

 ofn.lStructSize = sizeof(OPENFILENAME);
 ofn.hwndOwner = hwnd;
 ofn.lpstrFilter = L"Database File (*.db)\0*.db\0";
 ofn.lpstrFile = saveFileName;
 ofn.nMaxFile = MAX_PATH;
 ofn.lpstrDefExt = L"db";
 ofn.Flags  = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
 ofn.lpstrTitle = L"Save New Database";

 if(GetSaveFileName(&ofn))
  wcscpy(file,saveFileName);
}

I have a simple save file dialog that I wish to use as a tool to return the file path, name, and extension. This function produces a runtime error, saying that the stack around filename is corrupted. I wish to use it like so:

wchar_t filename[] = L"";
newGradebookDialog( hwnd, filename );

And here is my function. It modifies filename as I expect it to, but the runtime stack error is what I don't get.

void newGradebookDialog( HWND hwnd, wchar_t file[] )
{
 OPENFILENAME ofn;

 wchar_t saveFileName[MAX_PATH] = L"";

 ZeroMemory( &ofn, sizeof( ofn ) );

 ofn.lStructSize = sizeof(OPENFILENAME);
 ofn.hwndOwner = hwnd;
 ofn.lpstrFilter = L"Database File (*.db)\0*.db\0";
 ofn.lpstrFile = saveFileName;
 ofn.nMaxFile = MAX_PATH;
 ofn.lpstrDefExt = L"db";
 ofn.Flags  = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
 ofn.lpstrTitle = L"Save New Database";

 if(GetSaveFileName(&ofn))
  wcscpy(file,saveFileName);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

寻找我们的幸福 2024-10-18 06:24:36
 wchar_t filename[] = L"";

这是一个只有一个元素的数组。您正在将一个更大的字符串复制到其中,这会损坏堆栈帧。使固定:

 wchar_t filename[MAX_PATH] = {0};
 wchar_t filename[] = L"";

That's an array with one element. You are copying a much bigger string into it, that corrupts the stack frame. Fix:

 wchar_t filename[MAX_PATH] = {0};
简单 2024-10-18 06:24:36

我有一种感觉,您通过 wcscpy 损坏了内存 - 您分配了空的“文件名”并将非空值(从 saveFileName )复制到其中,从而损坏了内存。

另外,通过分配 MAXPATH+1 元素而不是 MAXPATH 来为尾随 \0 保留空间也是一个好主意。尽管在这个特定的地方可能不需要,但多保留一个字符有时可以节省您数小时的内存损坏错误跟踪时间。

I have a feeling that you corrupt memory via wcscpy -- you have allocated empty "filename" and copy the non-empty value (from saveFileName) to it, thus corrupting memory.

Also it's a good idea to reserve space for trailing \0 by allocating MAXPATH+1 elements, and not MAXPATH. Though might be not needed in this particular place, reserving one more char sometimes saves you hours of memory corruption bug tracing.

我做我的改变 2024-10-18 06:24:36

尝试

wchar_t filename[MAX_PATH]

Try

wchar_t filename[MAX_PATH]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文