vc++ cfile 文件操作

来源:互联网 发布:php oa办公系统源代码 编辑:程序博客网 时间:2024/06/06 01:01

文件操作是最基本的操作,所以学习文件编程很有必要,今天就写一下文件相关的操作

本来菜鸟一只,写博客就是说明我一直在努力!一直在进步!

cfile里面的函数大家可以去msdn上面看一下

cfile的文件操作一般分为三个步骤(自己分类的,要是大神看见了不要批我)

1.打开文件

2.文件的读写

3.文件的关闭



第一步:文件打开

CFile file;if(0 == file.Open("1.txt", CFile::modeCreate | CFile ::modeNoTruncate | CFile ::modeReadWrite ))          //打开文件{GetDlgItem(IDC_STATIC)->SetWindowText("打开文件失败!");}else{GetDlgItem(IDC_STATIC)->SetWindowText("打开文件成功!");}

CFile::Open

virtual BOOL Open( LPCTSTR lpszFileName, UINTnOpenFlags, CFileException*pError= NULL );

Return Value   返回值

Nonzero if the open was successful; otherwise 0. The pError parameter is meaningful only if 0 is returned.

Parameters 

lpszFileName    文件路径

A string that is the path to the desired file. The path can be relative, absolute, or a network name (UNC).

nOpenFlags        打开文件方式

A UINT that defines the file’s sharing and access mode. It specifies the action to take when opening the file. You can combine options by using the bitwise-OR (| ) operator. One access permission and one share option are required; themodeCreate and modeNoInherit modes are optional. See theCFile constructor for a list of mode options.

pError     错误信息

A pointer to an existing file-exception object that will receive the status of a failed operation.

上面是MSDN上面的,红色的是我自己加的一点注释


主要看文件打开的方式

详情参考下面的网址:CFile打开文件模式总结 

open函数里面的模式一般是 CFile::modeCreate | CFile ::modeNoTruncate | CFile ::modeReadWrite


第二步:文件的读写

CString s;s = "hello, word !";file.SeekToEnd();            //指针移到文件末尾file.Write(s , s.GetLength());      //写入内容file.SeekToEnd();file.Write("\n 江山如此多娇,引无数英雄竞折腰!",sizeof("\n 江山如此多娇,引无数英雄竞折腰!"));   


下面看看程序下面是不是有一个“1.txt”的文档

点击看看里面的内容

第三步:文件关闭

只有一句

file.Close();

好了cfile的文件操作就完成了 。



原创粉丝点击