C++文件读写(ifstream、ofstream)

  1. #include <fstream>  
  2. ofstream         //文件写操作 内存写入存储设备   
  3. ifstream         //文件读操作,存储设备读区到内存中  
  4. fstream          //读写操作,对打开的文件可进行读写操作

打开文件的方式在ios类(所以流式I/O的基类)中定义,有如下几种方式:

ios::in 为输入(读)而打开文件
ios::out 为输出(写)而打开文件
ios::ate 初始位置:文件尾
ios::app 所有输出附加在文件末尾
ios::trunc 如果文件已存在则先删除该文件
ios::binary 二进制方式
这些方式是能够进行组合使用的,以“或”运算(“|”)的方式:例如
[cpp]  view plain  copy
  1. ofstream out;  
  2. out.open("Hello.txt", ios::in|ios::out|ios::binary)                 //根据自己需要进行适当的选取  
  1. ofstream out("...", ios::out);  
  2. ifstream in("...", ios::in);  
  3. fstream foi("...", ios::in|ios::out);  

1.写入文件:

使用重载的插入操作符<< 

  1.  // writing on a text file  
  2.  #include <fiostream.h>  
  3.  int main () {  
  4.      ofstream out("out.txt");  
  5.      if (out.is_open())   
  6.     {  
  7.          out << "This is a line.\n";  
  8.          out << "This is another line.\n";  
  9.          out.close();  
  10.      }  
  11.      return 0;  
  12.  }  
  13. //结果: 在out.txt中写入:  
  14. This is a line.  
  15. This is another line 

2.从文件中读入数据:

[cpp]  view plain  copy
  1. // reading a text file  
  2.    #include <iostream.h>  
  3.    #include <fstream.h>  
  4.    #include <stdlib.h>  
  5.      
  6.    int main () {  
  7.        char buffer[256];  
  8.        ifstream in("test.txt");  
  9.        if (! in.is_open())  
  10.        { cout << "Error opening file"; exit (1); }  
  11.        while (!in.eof() )  
  12.        {  
  13.            in.getline (buffer,100);  
  14.            cout << buffer << endl;  
  15.        }  
  16.        return 0;  
  17.    } 

eof():如果读文件到达文件末尾,返回true。

3.二进制文件

在二进制文件中,使用<< 和>>,以及函数(如getline)来操作符输入和输出数据,没有什么实际意义,虽然它们是符合语法的。

文件流包括两个为顺序读写数据特殊设计的成员函数:write 和 read。第一个函数 (write) 是ostream 的一个成员函数,都是被ofstream所继承。而read 是istream 的一个成员函数,被ifstream 所继承。类 fstream 的对象同时拥有这两个函数。它们的原型是:

write ( char * buffer, streamsize size );
read ( char * buffer, streamsize size );

这里 buffer 是一块内存的地址,用来存储或读出数据。参数size 是一个整数值,表示要从缓存(buffer)中读出或写入的字符数。

  1. // reading binary file  
  2.     #include <iostream>  
  3.     #include <fstream.h>  
  4.       
  5.     const char * filename = "test.txt";  
  6.       
  7.     int main () {  
  8.         char * buffer;  
  9.         long size;  
  10.         ifstream in (filename, ios::in|ios::binary|ios::ate);  
  11.         size = in.tellg();  
  12.         in.seekg (0, ios::beg);  
  13.         buffer = new char [size];  
  14.         in.read (buffer, size);  
  15.         in.close();  
  16.           
  17.         cout << "the complete file is in a buffer";  
  18.           
  19.         delete[] buffer;  
  20.         return 0;  
  21.     }  
  22.     //运行结果:  
  23.     The complete file is in a buffer  

猜你喜欢

转载自blog.csdn.net/xiuxiuxiuyuan/article/details/80069117