代码改变世界

c++ ifstream ofstream 文件流

2013-11-12 11:11  youxin  阅读(1219)  评论(0编辑  收藏  举报

 

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

打开文件:

  1. void open ( const char * filename,  
  2.             ios_base::openmode mode = ios_base::in | ios_base::out );  

或ifstream if("data.txt"); 默认构造函数和open原型一样。

本文件的读写

 

类ofstream, ifstream 和fstream 是分别从ostream, istream 和iostream 中引申而来的。这就是为什么 fstream 的对象可以使用其父类的成员来访问数据。

一般来说,我们将使用这些类与同控制台(console)交互同样的成员函数(cin 和 cout)来进行输入输出。如下面的例题所示,我们使用重载的插入操作符<<:

 

判断文件是否结尾

if.eof() 为true即结尾。

 

读取文件并输出:

// reading a text file  
   #include <iostream.h>  
   #include <fstream.h>  
   #include <stdlib.h>  
     
   int main () {  
       char buffer[256];  
       ifstream in("test.txt");  
       if (! in.is_open())  
       { cout << "Error opening file"; exit (1); }  
       while (!in.eof() )  
       {  
           in.getline (buffer,100);  
           cout << buffer << endl;  
       }  
       return 0;  
   }  
   //结果 在屏幕上输出  
    This is a line.  
    This is another line

 

 

读写数据块
  要读写二进制数据块,使用成员函数read()和write()成员函数,它们原型如下:
    
read(unsigned char *buf,int num); 
write(const unsigned char *buf,int num); 
  read()从文件中读取 num 个字符到 buf 指向的缓存中,如果在还未读入 num 个字符时就到了文件尾,可以用成员函数 int gcount();来取得实际读取的字符数;而 write() 从buf 指向的缓存写 num 个字符到文件中,值得注意的是缓存的类型是 unsigned char *,有时可能需要类型转换。
例:
    
unsigned char str1[]="I Love You";    
int n[5];    
ifstream in("xxx.xxx");    
ofstream out("yyy.yyy");    
out.write(str1,strlen(str1));//把字符串str1全部写到yyy.yyy中    
in.read((unsigned char*)n,sizeof(n));//从xxx.xxx中读取指定个整数,注意类型转换    
in.close();out.close();
 
copy一个文件:
#include<iostream>
#include<fstream>
using namespace std;

int main()
{
    ifstream  fin("input.txt");
    ofstream  fout("input2.txt");

    char buf[1024];
    while(!fin.eof())
    {
        fin.read(buf,1024);
        fout.write(buf,fin.gcount());
    }
    fin.close();
    fout.close();
}

 

参考:

http://blog.csdn.net/kingstar158/article/details/6859379