OPENFILENAME open dialog

2020-07-25 01:35发布

i want to get a full file path by open file dialog in win32. i do it by this function:

  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;
}

it's work fine and return path . but i can't write into the that file i get path of it with openfilename.

note : i call this code to write to the file (serialization):

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();

标签: c++ file winapi
2条回答
【Aperson】
2楼-- · 2020-07-25 01:45

Try this for write:

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);

... and read:

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);

Help links:

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

查看更多
干净又极端
3楼-- · 2020-07-25 01:53

Try closing it and reopen then for writing.

查看更多
登录 后发表回答