📄 sy0502.htm
字号:
<html>
<HEAD>
<TITLE>Visual C++与计算机接口</TITLE>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html;charset=gb2312" >
</HEAD>
<body>
<font color="#0000FF">访问磁盘文件</font>
<p>
(一)实验目的:<BR>
访问磁盘文件<BR><BR>
(二)实验内容:<BR>
(1) 利用MFC的CFile类访问二进制文件,该类封装了Windows API中处理二进制文件的函数。<BR>
(2) 利用MFC的CStdioFile类操作文本文件,CStdioFile从CFile类派生,并封装了C、C++语言中用来处理文本文件的函数。<BR><BR>
(三)实验方法:<BR><BR>
1、打开并使用一个二进制文件<BR><BR>
(1) 打开一个二进制文件<BR>
打开一个二进制文件,应首先创建一个CFile类对象,然后利用Open()成员函数打开或创建一个文件对象。<BR>
CFile file;<BR>
file.Open("filename",CFile::modeCreate|CFile::modeWrite);<BR>
或 file.Open("filename",CFile::modeRead);<BR>
mode的不同,表明了文件的不同用途。<BR><BR>
(2) 文件使用完毕后,应关闭文件,销毁文件对象<BR>
file.Close();<BR><BR>
(3) 读写二进制数据:<BR>
file.Write(buf,size);<BR>
nReadBytes=file.Read(buf,size);<BR>
buf为缓冲区指针,通常是一个对象的指针或一段内存的首地址;size为读写的长度。<BR>
若nReadBytes为0或与size不同,表明已到文件结束处。<BR><BR>
(4) 获得文件的长度:<BR>
UINT nBytes=file.GetLength();<BR><BR>
(5) 改变文件读写的当前位置:<BR>
file.SeekToEnd();<BR>
file.SeekToBegin();<BR>
file.Seek(offset,CFile::begin);<BR>
offset为文件指针的移动偏移量<BR><BR>
2、其它文件操作:<BR>
·检查文件是否存在,使用CFile的静态函数GetStatus():<BR>
CFileStatus status;<BR>
CString msg;<BR>
if (!CFile::GetStatus("filename",status))<BR>
{<BR>
msg.Format("%s does not exist",sFile);<BR>
AfxMessageBox(msg);<BR>
}<BR><BR>
·设置文件为只读,使用CFile的静态成员函数SetStatus():<BR>
if (CFile::GetStatus("filename",status))<BR>
{<BR>
status.m_attribute|=0x01;<BR>
CFile::SetStatus("filename",status);<BR>
}<BR><BR>
·删除一个文件,使用CFile的另外一个静态函数Remove():<BR>
CFile::Remove(sFile);<BR><BR>
3、访问文本文件<BR><BR>
·CFile类是不能方便的访问文本文件的,访问文本文件可使用CFile的派生类CStdioFile。<BR>
·CStdioFile类中,可以使用WriteString和ReadString函数方便的读写一行文本。<BR>
·CStdioFile类是从CFile派生的,故CFile中的函数在CStdioFile类中都可使用。<BR><BR>
(1) 打开或创建一个文本文件:<BR>
CStdioFile file;<BR>
if (!file.Open (sFile, CFile::modeCreate | CFile::modeWrite | CFile::typeText))<BR>
{<BR>
CString msg;<BR>
msg.Format("Failed to create %s.",sFile);<BR>
}<BR>
(2) 从一个文本文件中读一行文本:<BR>
CString sRecord;<BR>
file.ReadString(sRecord);<BR>
(3) 写一个文本串到文件中,但不在文本串末尾换行:<BR>
CString sRecord="test file";<BR>
file.WriteString(sRecord);<BR>
(4) 定位到文件的头或尾:<BR>
file.SeekToEnd();<BR>
file.SeekToBegin();<BR>
(5) 关闭文件并销毁创建的文件对象:<BR>
file.Close();<BR><BR>
4、二进制文件访问实例:<BR>
CFile file;<BR>
CString msg;<BR>
CString sFile ("tmp.tmp");<BR>
If (!file.Open (sFile, CFile::modeCreate | CFile::modeWrite))<BR>
{<BR>
msg.Format("Failed to creat %s.",sFile);<BR>
AfxMessageBox(msg);<BR>
}<BR>
CString str("test file");<BR>
file.Write(str,str.GetLength());<BR>
file.Close();<BR>
if (!file.Open(sFile,CFile::modeRead))<BR>
{<BR>
msg.Format(“Failed to open %s.”,sFile);<BR>
AfxMessageBox(msg);<BR>
}<BR>
file.SeekToBegin();<BR>
UINT nBytes=file.GetLength();<BR>
char* buff=new char[nBytes];<BR>
nBytes=file.Read(buffer,nBytes);<BR>
CDC* pDC=GetDC();<BR>
pDC->TextOut(0,0,buff,nBytes);<BR>
ReleaseDC(pDC);<BR>
delete buff;<BR>
file.Close();<BR><BR>
<p></p>
</body>
</html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -