c++:打开选择文件夹,记录选择的文件的名称


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//头文件是从项目文件拷贝的,看不需要的自己删除(多字节环境下)
#include <Windows.h>
#include <memory>
#include <iostream>
#include <numeric>
#include <list>
#include <cmath>

string   Select_file();


int main()
{
    string openfilename;

    openfilename = Select_file();

    return 0;
}
string   Select_file()
{
#ifdef  _UNICODE
    TCHAR szBuffer[MAX_PATH] = { 0 };
    OPENFILENAME ofn = { 0 };
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner = NULL;
    ofn.lpstrFilter = _T("All(*.*)\0*.*\0Text(*.txt)\0*.TXT\0\0");//要选择的文件后缀
                                                                  //ofn.lpstrInitialDir = _T("D:\\Program Files");//默认的文件路径
    ofn.lpstrFile = szBuffer;//存放文件的缓冲区
    ofn.nMaxFile = sizeof(szBuffer) / sizeof(*szBuffer);
    ofn.nFilterIndex = 0;
    ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER;//标志如果是多选要加上OFN_ALLOWMULTISELECT
                                                                     //BOOL bSel = GetOpenFileName(&ofn);
    if (GetOpenFileName(&ofn))
    {
        //wprintf(L"%s\n", ofn.lpstrFile);  //ofn.lpstrFile  是地址

        /*locale loc("chs");   //输出到控制台
        wcout.imbue(loc);
        wcout << ofn.lpstrFile << endl;
        */

        char szcConv[200];
        memset(szcConv, 0, 200 * sizeof(char));

        size_t wLen = wcslen(ofn.lpstrFile) + 1;  // 宽字符字符长度,+1表示包含字符串结束符
        int aLen = WideCharToMultiByte(CP_ACP, 0, ofn.lpstrFile, wLen, NULL, 0, NULL, NULL);

        LPSTR lpa = new char[aLen];
        WideCharToMultiByte(CP_ACP, 0, ofn.lpstrFile, wLen, lpa, aLen, NULL, NULL);
        strcpy_s(szcConv, 200, lpa);
        delete[] lpa;
        lpa = NULL;
        //wcout << szcConv << endl;
        //string FileName;
        //FileName = szcConv;
        //return szcConv;

    }

#endif
#ifdef  _MBCS

    char szFileName[MAX_PATH] = { 0 };
    OPENFILENAME openFileName = { 0 };
    openFileName.lStructSize = sizeof(OPENFILENAME);
    openFileName.nMaxFile = MAX_PATH;  //这个必须设置,不设置的话不会出现打开文件对话框
    openFileName.lpstrFilter = "(*.MV)\0*.mv\0(*.DLV)\0*.dlv\0All(*.*)\0*.*\0\0";
    //此处参考
    //https://www.shuzhiduo.com/A/VGzlVpvy5b/
    //https://www.cnblogs.com/lkpp/p/OPENFILENAME-lpstrFilter.html
    openFileName.lpstrFile = szFileName;
    openFileName.nFilterIndex = 1;
    openFileName.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
    string FileName;
    if (::GetOpenFileName(&openFileName))
    {
        //::MessageBoxA(NULL, openFileName.lpstrFile, "", MB_OK);
        //cout << szFileName << endl;

        FileName = szFileName;
        //cout << FileName << endl;
        return FileName;
    }

#endif

}