2013-05-28 114 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打開和關閉? –