浏览文件位置并将wstring保存到文件

时间:2016-04-01 08:54:56

标签: c++ string file

我正在尝试创建一个文件对话框,用户可以通过选择位置并输入名称来选择现有文件或创建新文件。浏览工作正常,但是当我尝试保存文件时,它会给我以下错误

  

失败:文件!= NULL。

我还必须将要写入文件的文本从std::wstring转换为char *,从而转换为sprint。我无法弄清楚我做错了什么。

以下是我目前正在使用的代码:

HMODULE hModule = GetModuleHandleW(NULL);
OPENFILENAME ofn;
char szFile[260];       // buffer for file name
HWND hwnd = NULL;              // owner window
HANDLE hf;              // file handle

// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrTitle = TEXT("Select a location to save the information");
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = TEXT("All\0*.*\0Text\0*.TXT\0");
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

if(GetSaveFileName(&ofn)==TRUE)
{
    wchar_t hostName[2048] = L"";
    DWORD sz = 2048;

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

    char * buffer = new char[242];
    //sprintf(buffer, "%ls", hostInfo.c_str());
    _snprintf_s(buffer,242, _TRUNCATE, "%ls", hostInfo.c_str());

    std::ofstream stream(ofn.lpstrFile, std::ofstream::binary);
    stream.write(buffer, 243);

    //delete[] buffer;
    stream.close();
}

编辑: 发现了问题。我没有为lpstrFile设置指针,导致所选路径为NULL,因此File != NULL断言失败

0 个答案:

没有答案