Chinaunix首页 | 论坛 | 博客
  • 博客访问: 443036
  • 博文数量: 142
  • 博客积分: 3000
  • 博客等级: 中校
  • 技术积分: 1861
  • 用 户 组: 普通用户
  • 注册时间: 2005-06-03 21:00
文章分类

全部博文(142)

文章存档

2011年(3)

2010年(32)

2009年(107)

我的朋友

分类: C/C++

2010-03-23 11:30:38

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))
{
 ...;
}
 
阅读(1864) | 评论(0) | 转发(0) |
0

上一篇:万峰经典语录

下一篇:J2ME环境配置笔记

给主人留下些什么吧!~~