2

我想通过win32中的打开文件对话框获得完整的文件路径。我通过这个功能做到这一点:

  string openfilename(char *filter = "Mission Files (*.mmf)\0*.mmf", HWND owner = NULL)      {
  OPENFILENAME ofn  ;
  char fileName[MAX_PATH] = "";
  ZeroMemory(&ofn, sizeof(ofn));
  ofn.lStructSize = sizeof(OPENFILENAME);
  ofn.hwndOwner = owner;
  ofn.lpstrFilter = filter;
  ofn.lpstrFile = fileName;
  ofn.nMaxFile = MAX_PATH;
  ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
  ofn.lpstrDefExt = "";
  ofn.lpstrInitialDir ="Missions\\";

  string fileNameStr;
  if ( GetOpenFileName(&ofn) )
    fileNameStr = fileName;

  return fileNameStr;
}

它工作正常并返回路径。但我不能写入那个文件我用openfilename得到它的路径。

注意:我调用此代码写入文件(序列化):

string Mission_Name =openfilename();
ofstream  ofs ;
ofs =  ofstream ((char*)Mission_Name.c_str(), ios::binary   );
ofs.write((char *)&Current_Doc, sizeof(Current_Doc));
ofs.close();
4

2 回答 2

2

试试这个写:

string s = openfilename();

HANDLE hFile = CreateFile(s.c_str(),       // name of the write
                   GENERIC_WRITE,          // open for writing
                   0,                      // do not share
                   NULL,                   // default security
                   CREATE_ALWAYS,          // Creates a new file, always
                   FILE_ATTRIBUTE_NORMAL,  // normal file
                   NULL);                  // no attr. template
DWORD writes;
bool writeok = WriteFile(hFile, &Current_Doc, sizeof(Current_Doc), &writes, NULL);

CloseHandle(hFile);

...并阅读:

HANDLE hFile = CreateFile(s.c_str(),       // name of the write
                   GENERIC_READ,           // open for reading
                   0,                      // do not share
                   NULL,                   // default security
                   OPEN_EXISTING,          // Creates a new file, always
                   FILE_ATTRIBUTE_NORMAL,  // normal file
                   NULL);                  // no attr. template
DWORD readed;
bool readok = ReadFile(hFile, &Current_Doc, sizeof(Current_Doc), &readed, NULL);

CloseHandle(hFile);

帮助链接:

http://msdn.microsoft.com/en-us/library/windows/desktop/bb540534%28v=vs.85%29.aspx

http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx

于 2013-05-28T13:04:45.590 回答
0

尝试关闭它然后重新打开以进行写作。

于 2013-05-28T12:41:36.107 回答