打开窗口进行选择文件(txt文件),打开所选文件,读入文件

时间:2022-12-30 09:51:57

用mfc编写项目的时候往往需要调用窗口,允许用户通过窗口进行选择文件操作

    TCHAR szBuffer[MAX_PATH] = { 0 };
OPENFILENAME ofn = { 0 };
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = m_hWnd;
ofn.lpstrFilter = _T("txt文件(*.txt)\0");//要选择的文件后缀
char buf[80];
getcwd(buf, sizeof(buf));
ofn.lpstrInitialDir = _T(buf);//默认的文件路径
ofn.lpstrFile = szBuffer;//szBuffer是存放的选择的文件路径
ofn.nMaxFile = sizeof(szBuffer) / sizeof(*szBuffer);
ofn.nFilterIndex = 0;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER;
//标志如果是多选要加上OFN_ALLOWMULTISELECT
BOOL bSel;
bSel = GetOpenFileName(&ofn);//实际打开窗口的语句
int i = 0,l=0;
int len = strlen(szBuffer) ;
TCHAR filename[MAX_PATH];
//路径变换,变换为..\\..\\...
while (i < len) {
filename[l++] = szBuffer[i];
if (szBuffer[i++] == '\\')
filename[l++] = '\\';
}
filename[l++] = '\0';
FILE *fp;
if ((fp = fopen(filename, "r")) == NULL)
{
printf("无法打开此文件\n");
return;
}
char *miwen = new char[1024];
i = 0;
while (!feof(fp)) {
miwen[i++] = fgetc(fp);
}
miwen[i - 1] = '\0';
fclose(fp);