C++文件读写操作

1、文件写入

  ofstream类:

  ofstream( const char* szName, int nMode = ios::out, int nProt = filebuf::openprot );

    szName:指定将要打开的文件名;

    nMode:指定文件打开的模式,包括:

      ios::app  --先执行一个定位,将文件指针移动至文件末尾,当向文件写入新数据时,将总是添加到文件的末尾处;

      ios::ate  --先执行一个定位,将文件指针移动至文件末尾,当向文件写入第一个新的字节数据时,将在文件的末尾处添加,但随后写入的其它字节数据,将被写入到当前位置;

      ios::in   --指定该模式时,已存在的原始文件将不会被截断;

      ios::out  --打开文件,用于存放所有的ofstream对象的输出数据;

      ios::trunc  --如果文件已存在,将被清空;如果指定了ios::out模式而没有指定ios::app/ios::ate/ios::in模式,则默认执行该模式清空文件中的数据内容;

      ios::nocreate  --如果文件不存在,则函数调用失败;

      ios::noreplace  --如果文件已存在,则函数调用失败;

      ios::binary  --以二进制方式打开文件(默认以文本方式);

    nProt:指定文件保护规则,包括:

      filebuf::sh_compat  --兼容共享模式;

      filebuf::sh_none  --排他独占模式,不共享;

      filebuf::sh_read  --允许读共享;

      filebuf::sh_write  --允许写共享;

2、文件读取

  ifstream类:

  ifstream( const char* szName, int nMode = ios::in, int nProt = filebuf::openprot );

    构造方法同ofstream类

3、须包含头文件:#include <fstream.h>

 

例:

#include <fstream.h>

ofstream ofs("1.txt");
ofs.write("hello world!", strlen("hello world!"));
ofs.close();
ifstream ifs("1.txt");
char ch[100];
memset(ch, 0, 100);
ifs.read(ch, 100);
ifs.close();
MessageBox(ch);

 

posted @ 2017-05-29 18:38  Autumn_n  阅读(451)  评论(0编辑  收藏  举报
TOP