超详细ofstream和ifstream详细用法

来源:互联网 发布:qq飞车终极麦凯伦数据 编辑:程序博客网 时间:2024/04/29 10:16

  ofstream和ifstream详细用法


ofstream是从内存到硬盘,ifstream是从硬盘到内存,其实所谓的流缓冲就是内存空间(文章最末尾附上了MSDN中关于这两个函数的解释);

在C++中,有一个stream这个类,所有的I/O都以这个“流”类为基础的,包括我们要认识的文件I/O,stream这个类有两个重要的运算符:
       1.插入器(<<)
  向流输出数据。比如说系统有一个默认的标准输出流(cout),一般情况下就是指的显示器,所以,cout<<"Write Stdout"<<'\n';就表示把字符串"Write Stdout"和换行字符('\n')输出到标准输出流。
      2. 析取器(>>)
  从流中输入数据。比如说系统有一个默认的标准输入流(cin),一般情况下就是指的键盘,所以,cin>>x;就表示从标准输入流中读取一个指定类型(即变量x的类型)的数据。
  在C++中,对文件的操作是通过stream的子类fstream(file stream)来实现的,所以,要用这种方式操作文件,就必须加入头文件fstream.h。下面就把此类的文件操作过程一一道来。

一、打开文件

  在fstream类中,有一个成员函数open(),就是用来打开文件的,其原型是:

void open(constchar* filename,int mode,int access);

参数:
filename:  要打开的文件名
mode:    要打开文件的方式
access:   打开文件的属性
打开文件的方式在类ios(是所有流式I/O类的基类)中定义,常用的值如下:
ios::app:   以追加的方式打开文件
ios::ate:   文件打开后定位到文件尾,ios:app就包含有此属性
ios::binary: 以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文
ios::in:    文件以输入方式打开(文件数据输入到内存)
ios::out:   文件以输出方式打开(内存数据输出到文件)
ios::nocreate: 不建立文件,所以文件不存在时打开失败
ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败
ios::trunc:  如果文件存在,把文件长度设为0
  可以用“或”把以上属性连接起来,如ios::out|ios::binary
  打开文件的属性取值是:
0:普通文件,打开访问
1:只读文件
2:隐含文件
4:系统文件
  可以用“或”或者“+”把以上属性连接起来,如3或1|2就是以只读和隐含属性打开文件。
  例如:以二进制输入方式打开文件c:\config.sys
fstream file1;
file1.open("c:\\config.sys",ios::binary|ios::in,0);
  如果open函数只有文件名一个参数,则是以读/写普通文件打开,即:
file1.open("c:\\config.sys"); <=> file1.open("c:\\config.sys",ios::in|ios::out,0);
  另外,fstream还有和open()一样的构造函数,对于上例,在定义的时侯就可以打开文件了:
fstream file1("c:\\config.sys");
  特别提出的是,fstream有两个子类:ifstream(input file stream)和ofstream(outpu file stream),ifstream默认以输入方式打开文件,而ofstream默认以输出方式打开文件。
ifstream file2("c:\\pdos.def");//以输入方式打开文件
ofstream file3("c:\\x.123");//以输出方式打开文件
  所以,在实际应用中,根据需要的不同,选择不同的类来定义:如果想以输入方式打开,就用ifstream来定义;如果想以输出方式打开,就用ofstream来定义;如果想以输入/输出方式来打开,就用fstream来定义。

二、关闭文件

  打开的文件使用完成后一定要关闭,fstream提供了成员函数close()来完成此操作,如:file1.close();就把file1相连的文件关闭。

三、读写文件

  读写文件分为文本文件和二进制文件的读取,对于文本文件的读取比较简单,用插入器和析取器就可以了;而对于二进制的读取就要复杂些,下要就详细的介绍这两种方式
  1、文本文件的读写
  文本文件的读写很简单:用插入器(<<)向文件输出;用析取器(>>)从文件输入。假设file1是以输入方式打开,file2以输出打开。示例如下:
  
file2<<"I Love You";//向文件写入字符串"I Love You"
int i;
file1>>i;//从文件输入一个整数值。
  这种方式还有一种简单的格式化能力,比如可以指定输出为16进制等等,具体的格式有以下一些
操纵符 功能 输入/输出
dec 格式化为十进制数值数据 输入和输出
endl 输出一个换行符并刷新此流 输出
ends 输出一个空字符 输出
hex 格式化为十六进制数值数据 输入和输出
oct 格式化为八进制数值数据 输入和输出
setpxecision(int p) 设置浮点数的精度位数 输出
  比如要把123当作十六进制输出:file1<<hex<<123;要把3.1415926以5位精度输出:file1<<setpxecision(5)<<3.1415926。
  2、二进制文件的读写
①put()
  put()函数向流写入一个字符,其原型是ofstream &put(char ch),使用也比较简单,如file1.put('c');就是向流写一个字符'c'。
②get()
  get()函数比较灵活,有3种常用的重载形式:
  一种就是和put()对应的形式:ifstream &get(char &ch);功能是从流中读取一个字符,结果保存在引用ch中,如果到文件尾,返回空字符。如file2.get(x);表示从文件中读取一个字符,并把读取的字符保存在x中。
  另一种重载形式的原型是: int get();这种形式是从流中返回一个字符,如果到达文件尾,返回EOF,如x=file2.get();和上例功能是一样的。
  还有一种形式的原型是:ifstream &get(char *buf,int num,char delim='\n');这种形式把字符读入由 buf 指向的数组,直到读入了 num 个字符或遇到了由 delim 指定的字符,如果没使用 delim 这个参数,将使用缺省值换行符'\n'。例如:
  
file2.get(str1,127,'A');    //从文件中读取字符到字符串str1,当遇到字符'A'或读取了127个字符时终止。
③读写数据块
  要读写二进制数据块,使用成员函数read()和write()成员函数,它们原型如下:
    
read(unsignedchar *buf,int num);
write(const unsignedchar *buf,int num);
  read()从文件中读取 num 个字符到 buf 指向的缓存中,如果在还未读入 num 个字符时就到了文件尾,可以用成员函数 int gcount();来取得实际读取的字符数;而 write() 从buf 指向的缓存写 num 个字符到文件中,值得注意的是缓存的类型是 unsigned char *,有时可能需要类型转换。
例:
    
unsignedchar str1[]="I Love You";    
int n[5];    
ifstreamin("xxx.xxx");    
ofstreamout("yyy.yyy");    
out.write(str1,strlen(str1));//把字符串str1全部写到yyy.yyy中    
in.read((unsignedchar*)n,sizeof(n));//从xxx.xxx中读取指定个整数,注意类型转换    
in.close();out.close();
四、检测EOF
  成员函数eof()用来检测是否到达文件尾,如果到达文件尾返回非0值,否则返回0。原型是int eof();
例:  if(in.eof())   ShowMessage("已经到达文件尾!");
五、文件定位
  和C的文件操作方式不同的是,C++ I/O系统管理两个与一个文件相联系的指针。一个是读指针,它说明输入操作在文件中的位置;另一个是写指针,它下次写操作的位置。每次执行输入或输出时,相应的指针自动变化。所以,C++的文件定位分为读位置和写位置的定位,对应的成员函数是seekg()和seekp()。seekg()是设置读位置, seekp是设置写位置。它们最通用的形式如下:
    istream &seekg(streamoff offset,seek_dir origin);
    ostream &seekp(streamoff offset,seek_dir origin);
  streamoff定义于 iostream.h 中,定义有偏移量 offset 所能取得的最大值,seek_dir 表示移动的基准位置,是一个有以下值的枚举:
ios::beg:  文件开头
ios::cur:  文件当前位置
ios::end:  文件结尾
  这两个函数一般用于二进制文件,因为文本文件会因为系统对字符的解释而可能与预想的值不同。例:
   
file1.seekg(1234,ios::cur);    //把文件的读指针从当前位置向后移1234个字节
file2.seekp(1234,ios::beg);    //把文件的写指针从文件开头向后移1234个字节


这是MSDN中ofstream和ifstream的解释:

ofstream::ofstream

ofstream();

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

ofstream( filedesc fd );

ofstream( filedesc fd, char* pch, intnLength);

Parameters

szName

The name of the file to be opened during construction.

nMode

An integer that contains mode bits defined as ios enumerators that can be combined with the bitwise OR (| ) operator. ThenMode parameter must have one of the following values:

  • ios::app   The function performs a seek to the end of file. When new bytes are written to the file, they are always appended to the end, even if the position is moved with theostream::seekp function.

  • ios::ate   The function performs a seek to the end of file. When the first new byte is written to the file, it is appended to the end, but when subsequent bytes are written, they are written to the current position.

  • ios::in   If this mode is specified, then the original file (if it exists) will not be truncated.

  • ios::out   The file is opened for output (implied for all ofstream objects).

  • ios::trunc   If the file already exists, its contents are discarded. This mode is implied ifios::out is specified andios::ate, ios::app, andios:in are not specified.

  • ios::nocreate   If the file does not already exist, the function fails.

  • ios::noreplace   If the file already exists, the function fails.

  • ios::binary   Opens the file in binary mode (the default is text mode).

nProt

The file protection specification; defaults to the static integerfilebuf::openprot that is equivalent tofilebuf::sh_compat. The possiblenProt values are:

  • filebuf::sh_compat   Compatibility share mode.

  • filebuf::sh_none   Exclusive mode; no sharing.

  • filebuf::sh_read   Read sharing allowed.

  • filebuf::sh_write   Write sharing allowed.

    To combine the filebuf::sh_read and filebuf::sh_write modes, use the logical OR (|| ) operator.

fd

A file descriptor as returned by a call to the run-time function_open or_sopen; filedesc is atypedef equivalent toint.

pch

Pointer to a previously allocated reserve area of length nLength. ANULL value (ornLength = 0) indicates that the stream will be unbuffered.

nLength

The length (in bytes) of the reserve area (0 = unbuffered).

Remarks

The four ofstream constructors are:

ConstructorDescriptionofstream()Constructs an ofstream object without opening a file.ofstream( const char*, int, int )Contructs an ofstream object, opening the specified file.ofstream( filedesc )Constructs an ofstream object that is attached to an open file.ofstream( filedesc, char*, int )Constructs an ofstream object that is associated with afilebuf object. Thefilebuf object is attached to an open file and to a specified reserve area.

All ofstream constructors construct a filebuf object. The first three use an internally allocated reserve area, but the fourth uses a user-allocated area. The user-allocated area is not automatically released during destruction.


ofstream::ofstream

ofstream();

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

ofstream( filedesc fd );

ofstream( filedesc fd, char* pch, intnLength);

Parameters

szName

The name of the file to be opened during construction.

nMode

An integer that contains mode bits defined as ios enumerators that can be combined with the bitwise OR (| ) operator. ThenMode parameter must have one of the following values:

  • ios::app   The function performs a seek to the end of file. When new bytes are written to the file, they are always appended to the end, even if the position is moved with theostream::seekp function.

  • ios::ate   The function performs a seek to the end of file. When the first new byte is written to the file, it is appended to the end, but when subsequent bytes are written, they are written to the current position.

  • ios::in   If this mode is specified, then the original file (if it exists) will not be truncated.

  • ios::out   The file is opened for output (implied for all ofstream objects).

  • ios::trunc   If the file already exists, its contents are discarded. This mode is implied ifios::out is specified andios::ate, ios::app, andios:in are not specified.

  • ios::nocreate   If the file does not already exist, the function fails.

  • ios::noreplace   If the file already exists, the function fails.

  • ios::binary   Opens the file in binary mode (the default is text mode).

nProt

The file protection specification; defaults to the static integerfilebuf::openprot that is equivalent tofilebuf::sh_compat. The possiblenProt values are:

  • filebuf::sh_compat   Compatibility share mode.

  • filebuf::sh_none   Exclusive mode; no sharing.

  • filebuf::sh_read   Read sharing allowed.

  • filebuf::sh_write   Write sharing allowed.

    To combine the filebuf::sh_read and filebuf::sh_write modes, use the logical OR (|| ) operator.

fd

A file descriptor as returned by a call to the run-time function_open or_sopen; filedesc is atypedef equivalent toint.

pch

Pointer to a previously allocated reserve area of length nLength. ANULL value (ornLength = 0) indicates that the stream will be unbuffered.

nLength

The length (in bytes) of the reserve area (0 = unbuffered).

Remarks

The four ofstream constructors are:

ConstructorDescriptionofstream()Constructs an ofstream object without opening a file.ofstream( const char*, int, int )Contructs an ofstream object, opening the specified file.ofstream( filedesc )Constructs an ofstream object that is attached to an open file.ofstream( filedesc, char*, int )Constructs an ofstream object that is associated with afilebuf object. Thefilebuf object is attached to an open file and to a specified reserve area.

All ofstream constructors construct a filebuf object. The first three use an internally allocated reserve area, but the fourth uses a user-allocated area. The user-allocated area is not automatically released during destruction.




0 0
原创粉丝点击