vc关于CFile类

来源:百度知道 编辑:UC知道 时间:2024/05/18 02:03:22
我使用mfc的CFile类来读取一个文档

void CDIALOGONE::OnIntro1()
{
// TODO: Add your control notification handler code here
CFile file("cal1.txt",CFile::modeRead);
char *pBuf;
DWORD dwFileLen;
dwFileLen=file.GetLength();
pBuf=new char[dwFileLen+1];
pBuf[dwFileLen]=0;
file.Read(pBuf,dwFileLen);
file.Close();
MessageBox(pBuf);
}
把一个cal1.txt通过MessageBox输出,这个cal1.txt文件放在这个工程目录下

但是我把该程序拷贝到别的电脑上就无法读取cal1.txt了,是不是因为路径变化了啊?要想打开该怎么解决??

可以用打开文件对话框来找到文件。
然后读取,

CFileDialog dlg(TRUE, "txt", "cal1.txt", OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,"文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*||");
if (dlg.DoModal() == IDOK)
{
CString FileName = dlg.GetPathName();
CFile file(FileName ,CFile::modeRead);
char *pBuf;
DWORD dwFileLen;
dwFileLen=file.GetLength();
pBuf=new char[dwFileLen+1];
pBuf[dwFileLen]=0;
file.Read(pBuf,dwFileLen);
file.Close();
MessageBox(pBuf);

}
--------------------
如果要默默地找到文件并读取,
那就要确定文件的位置,如果在程序所在目录下,那不需要目录名,直接用文件名应该可以读取的,
也可以试试用绝对路径,或者查找该文件。
CString szFileName = szFilePath + "*.*";
WIN32_FIND_DATA findData;
HANDLE hFindFile;
hFindFile = ::FindFirstFile(szFileName, &findData);
。。。

CFile file("cal1.txt",CFile::modeRead);
"cal1.txt",使用完整路径。

和程序放在一个目录打开时可以用“.\\cal1.txt”表示当前目录

如果你从编译器上执行,那么