C/C++文件操作(三):CFile/CStdioFile类

CFile
//创建/打开文件
CFile file;
file.Open(_T("test.txt"),CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite);

文件打开模式可组合使用,用“|”隔开,常用的有以下几种:
CFile::modeCreate:以新建方式打开,如果文件不存在,新建;如果文件已存在,把该文件长度置零,即清除文件原有内容。
CFile::modeNoTruncate:以追加方式打开,如果文件存在,打开并且不将文件长度置零,如果文件不存在,会抛出异常。一般与CFile::modeCreate一起使用,则文件不存在时,新建一个文件;存在就进行追加操作。
CFile::modeReadWrite:以读写方式打开文件。
CFile::modeRead:只读。
CFile::modeWrite:只写。

//写入数据
CString strValue = "Hello World!";
file.Write(strValue,strValue.GetLength());

//追加数据
file.SeekToEnd(); //将指针移至文件末尾进行追加
file.Write(strValue,strValue.GetLength());

//关闭文件
file.Close();

CStdioFile
CStdioFile是CFile的派生类,对文件进行流式操作,对于文本文件的读写很有用处,可按行读取写入。

//写入数据
CString strValue = "Hello World!";
file.WriteString(strValue);

//读取数据
CString strRead;
file.ReadString(strRead);

当文件存在多行数据需要逐行读取时,可用函数BOOL CStdioFile::ReadString(CString& rString),当遇到"/n "时读取截断,如果文件未读完,返回true,否则返回false。

//逐行读取文件内容,存入strRead
while(file.ReadString(strRead))
{
 ...;
}

 

文章出处:http://www.diybl.com/course/3_program/c++/cppsl/2008121/96889.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这段代码是 MFC 框架下的 C++ 代码,主要实现了一个分精度评价指标 Kappa 的计算。根据错误提示信息,代码中的变量 "m_file1" 没有被声明,导致编译错误。 解决方法: 可以在代码的开头部分声明变量 "m_file1" 和 "m_file2",如下所示: ```cpp void CBsqViewView::OnKappa() { // TODO: Add your command handler code here int ImgClass = 4; //分别数 CString m_pathname1, m_pathname2; //文件路径/文件路径 CFile m_file1, m_file2; // 声明文件变量 BYTE *ClassImg; BYTE *TestImg; ClassImg = new BYTE[Height*Width]; TestImg = new BYTE[Height*Width]; CWnd a; a.MessageBox("选择分后的文件", NULL, MB_OK); CFileDialog m_opendlg(TRUE); if(m_opendlg.DoModal() == IDOK) //激活文件公用对话框,用来打开选择文件对话框 { m_pathname1 = m_opendlg.GetPathName(); //得到文件的路径名 } if(!m_file1.Open(m_pathname1, CStdioFile::modeRead | CStdioFile::typeBinary)) { AfxMessageBox("打开分后的文件失败!"); return; } m_file1.Read(ClassImg, Height*Width); a.MessageBox("选择参考文件", NULL, MB_OK); CFileDialog m_opendlg1(TRUE); if(m_opendlg1.DoModal() == IDOK) //激活文件公用对话框,用来打开选择文件对话框 { m_pathname2 = m_opendlg1.GetPathName(); //得到文件的路径名 } if(!m_file2.Open(m_pathname2, CStdioFile::modeRead | CStdioFile::typeBinary)) { AfxMessageBox("打开参考文件失败!"); return; } m_file2.Read(TestImg, Height*Width); CKappa Kappa; Kappa.kappa(ImgClass, Height, Width, ClassImg, TestImg); } ``` 需要注意的是,为了避免重复声明变量,需要在代码的其他部分检查是否已经声明过了,如果已经声明过,则不需要再次声明。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值