从文件保存对话框返回文件名(windows32)
我有一个简单的保存文件对话框,我希望将其用作返回文件路径、名称和扩展名的工具。该函数会产生一个运行时错误,表明文件名周围的堆栈已损坏。我希望像这样使用它:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个只有一个元素的数组。您正在将一个更大的字符串复制到其中,这会损坏堆栈帧。使固定:
That's an array with one element. You are copying a much bigger string into it, that corrupts the stack frame. Fix:
我有一种感觉,您通过 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.
尝试
Try