怎么在MFC中打开一个文件,如单击一个按钮,然后弹出选择文件的框框,我需要打开这个文件!

2025-03-23 20:34:22
推荐回答(5个)
回答1:

//文件属性定义
CString filename;
CString fileext;//文件扩展名
CString filepathname;
//选择文件
CFileDialog fpdlg(TRUE, NULL, NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,"(文件类型)(*.dat)|*.dat|(文件类型)(*.sth)|*.sth|所有文件(*.*)|*.*||",NULL);
if(fpdlg.DoModal() == IDOK)
{
filename = fpdlg.GetFileName();
fileext = fpdlg.GetFileExt();//文件扩展名
filepathname = fpdlg.GetPathName();
//UpdateData(FALSE);
}
//打开文件
CFile fp;
if(filepathname ==_T(""))
{
//AfxMessageBox("请选择文件!");
return ;
}
if(!(fp.Open((LPCTSTR)filepathname,CFile::modeRead)))
{
AfxMessageBox("文件打开失败!");
return ;
}
//读取文件
fp.SeekToEnd();
unsigned long len = fp.GetLength();
char* buff;
buff=new char[len+1];
fp.SeekToBegin();
if(fp.Read(buff,len)<1)
{
fp.Close();
}
fp.Close();

回答2:

打开文件对话框
const char pszFilter[] = _T("EXE File (*.txt)|*.txt|All Files (*.*)|*.*||");
CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
pszFilter, this);

dlg.m_ofn.lpstrInitialDir = "c:\\WINDOWS\\"; //设置对话框默认呈现的路径

if(dlg.DoModal() == IDOK)
{
CString strFilePath = dlg.GetPathName();
/*如果有多个文件,则
for(POSITION pos = dlg.GetStartPosition(); pos!=NULL; )
{
CString strFilePathName = dlg.GetNextPathName(pos);
*/
}

http://www.cppblog.com/zgysx/archive/2006/12/06/16053.html
借花献佛。。

回答3:

LS的方法都可以的。主要是CFileDialog类的功能。

回答4:

得法

回答5:

CFileDialog