浅谈文件操作(下)

  上次写了文件操作(上),但这几天都在忙其他东西了,所以今天才来更新。

这次主要说文件的读写:

1.文本文件的读写:

(文本文件又称ASCII文件,它的每个字节存放一个ASCII代码,代表一个字符)

 

一旦文件打开了,从文件中读取文本数据与向文件中写入文本数据都十分容易。看下面例子

#include<iostream>
#include<fstream>
using namespace std;
int main(){
ofstream fout("f1.dat",ios::out);//定义输出文件流对象fout,打开文件f1
if(!fout){      //如果文件打开失败,则fout返回0;
cout<<"cannot open the file<<endl";
return 1;
}
fout<<10<<""<<123.56<<" "<<"this is a file"<<endl;//将整型,浮点数,字符串写进文件
fout.close();

return 0;
}

运行程序后,屏幕是没用什么东西显示的,但打开f1文件时会有刚才的数据。

再看如何读取信息,并输出到屏幕:

#include<iostream>
#include<fstream>
using namespace std;
int main(){
ofstream fout("f2.dat",ios::out);//定义输出文件流对象fout,打开文件f2
if(!fout){      //如果文件打开失败,则fout返回0;
cout<<"cannot open the file<<endl";
return 1;
}
fout<<100<<" "<<"this is a file"<<endl;//将整型,浮点数,字符串写进文件
fout.close();
ifstream fin("f2.dat",ios::in);//定义输入文件流对象fout,打开文件f2
if(!fin){
cout<<"cannot open input file"<<endl;
return 1;
}
char str[80];
int i;
fin>>i>>str; //从文件读取整型,和字符串分别赋给i,str
cout<<i<<" "<<str<<endl;
fin.close();

return 0;
}

运行程序后,此时会显示100  this is a file

 

2.二进制文件的读写:

(二进制文件是把内存中的数据,按其在内存中的存储形式原样写到磁盘)

1)用get函数和put函数读写二进制文件

实例:

#include<iostream>
#include<fstream>
using namespace std;
int test_write(){
    ofstram outf("f3.dat",ios::binary);
    if(!outf){
         cout<<"cannot open output file \n";
         exit(1);
    } 
    char ch='a';
    for(int i=0;i<26;i++){
          outf.put(ch);
          ch++;
    }
    outf.close();
    return 0;
}

int test_read(){
     ifstram inf("f3.dat",ios::binary);
     if(!inf){
            cout<<"cannot open input file \n";
           exit(1);
    } 
    char ch;
    while(inf.get(ch)){
                cout<<ch;
    }
     inf.close();
    return 0;
}             

2)用read函数和write函数读写二进制文件

原形:inf.read(char *buf,int len)         outf.write(const char *buf,int len)

  实例:

#include<iostream>
#include<fstream>
using namespace std;
struct list{
    char course[15];
    int score;
};
int main(){
    list list2[2]={"computer",90,"math",78};
    ifstream in("f4.dat",ios::binary);
    if(!in){
    cout<<"cannot open input file \n";
    abort(); //退出程序,作用和exit相同
    }
    for(int i=0;i<2;i++){
        in.read((char *) &list2[i],sizeof(list2[i]));
        cout<<list2[i].course<<" "<<list2[i].score<<endl;
    }
    in.close();
    return 0;
} 

会显示出: computer 90

     math 78

 

 本文完!

posted @ 2016-10-21 11:02  vinpho  阅读(217)  评论(0编辑  收藏  举报