MFC文件操作之CFile

本文讲解怎样利用CFile对文件进行读写操作。

//-----------------------------------------------
// CFile写文件示例
// 实现功能:1.如果文件存在,在文件末尾添加内容
//          2.如果文件不存在,则创建文件并添加内容
//-----------------------------------------------
CString cstrFileFullPath = "D:\\test.txt";

// 判断文件是否存在,如果存在则去掉只读属性
if (PathFileExists(cstrFileFullPath) && !PathIsDirectory(cstrFileFullPath))
{
    DWORD dwAttrs = GetFileAttributes(cstrFileFullPath);
    if (dwAttrs != INVALID_FILE_ATTRIBUTES
        && (dwAttrs & FILE_ATTRIBUTE_READONLY))
    {
        dwAttrs &= ~FILE_ATTRIBUTE_READONLY;
        SetFileAttributes(cstrFileFullPath, dwAttrs);
    }
}

// 打开文件
CFile file;
BOOL ret = file.Open(cstrFileFullPath, 
    CFile::modeCreate | CFile::modeNoTruncate | CFile::modeWrite | CFile::shareDenyWrite);
if (!ret)
{
    AfxMessageBox("打开文件失败");
    return;
}
file.SeekToEnd();

// 写文件
char buffer[100] = "hello kitty\r\nhello kitty";
file.Write(buffer, strlen(buffer));

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

// 注意:
// 1.PathFileExists与PathIsDirectory需要引用头文件:#include "shlwapi.h"
// 2.CFile::modeCreate | CFile::modeNoTruncate的功用:
//   如果文件存在则打开,不清空文件内容
//   如果文件不存在则创建
// 3.CFile是以二进制模式打开文件的,所以写入文件时要换行,需写入"\r\n"

//-----------------------------------------------
// CFile读取文件示例
// 实现功能:打开已存在文件并读取文件内容直到文件结尾
//-----------------------------------------------
CString cstrFileFullPath = "D:\\test.txt";

// 判断文件是否存在
bool bFileExist = PathFileExists(cstrFileFullPath)
    && (!PathIsDirectory(cstrFileFullPath));
if (false == bFileExist)
{
    return;
}

// 打开文件
CFile file;
BOOL ret = file.Open(cstrFileFullPath, 
    CFile::modeRead | CFile::shareDenyNone);
if (!ret)
{
    AfxMessageBox("打开文件失败");
    return;
}
file.SeekToBegin();

// 读取文件
char buffer[1024] = { 0 };
while (1)
{
    memset(buffer, 0, sizeof(buffer));
    UINT nCnt = file.Read(buffer, 1024);

    // 对读取的文内容进行处理的代码
    // ......

    // 读到文件结尾
    if (nCnt < 1024)
    {
        break;
    }
}

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

//-----------------------------------------------
// 打开文件参数项
//-----------------------------------------------
CFile::modeCreate 
    --- 如果文件不存在则创建,如果文件存在则打开文件并清空文件内容
CFile::modeCreate | CFile::CFile::modeNoTruncate
    --- 如果文件不存在则创建,如果文件存在则打开文件并保留文件内容
CFile::shareDenyNone
    --- 允许其它进程对文件读写
CFile::shareDenyRead
    --- 不允许其它进程对文件进行读操作
CFile::shareDenyWrite
    --- 不允许其它进程对文件进行写操作
CFile::shareExclusive
    --- 以独占模式打开文件,不允许其它进程对文件进行读写
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值