2013-05-28 117 views
0

我想通过在win32中打开文件对话框来获取完整的文件路径。 我这样做是通过这个功能:OPENFILENAME打开对话框

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

做你检查'fileNameStr'的价值? – Zigma

+0

'LPCSTR'演员给我带来了一些毛骨悚然......什么是MyfilePath的声明? –

+0

我认为(不确定)这将是你的字符串转换中的'\ 0'的问题。 – Zigma

回答

1

试试这个写:

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

0

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

+0

如何?通过ifstream打开和关闭? –