C getopenfilename getFileName

时间:2013-04-26 03:03:28

标签: c windows file filenames

我有以下代码,问题是,当我打印文件的完整路径名时,我在数组中的每个字符之间得到双倍空格。

// initialization outside any class in .c code
OPENFILENAME ofn;       // common dialog box structure
char szFile[260];       // buffer for file name
HWND hwnd;              // owner window
HANDLE hf;              // file handle
...
...
// inside a function
initializeOpenFile();
GetOpenFileName(&ofn);


            for(i = 0; i < sizeof(szFile)/sizeof(char);i++){
                fprintf(stderr,"%c", szFile[i]);
                }
        }
}

void initializeOpenFile(){
    // Initialize OPENFILENAME
    ZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner = hwnd;
    ofn.lpstrFile = szFile;
    // Set lpstrFile[0] to '\0' so that GetOpenFileName does not 
    // use the contents of szFile to initialize itself.
    ofn.lpstrFile[0] = '\0';
    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;
}

打印我:

enter image description here

我想使用该char数组传递给openFile函数:

FILE* fp = fopen( filename, "r" );

1 个答案:

答案 0 :(得分:1)

看起来它是一个宽字符串,即。一串宽角色。 (参考:wikipedia

所以应声明szFile:

wchar_t szFile[260];

然后你可以用wcstombs()转换它(我认为!)。

char szPath[260];
wcstombs(szPath, szFile, 260);

szPath 现在应包含“普通”(窄)字符串。