对比ASCII文件和二进制文件
//将short int x=12345写入文本文件 #include <iostream> #include <fstream> #include <cstdlib> using namespace std; int main( ) { short int x=12345; ofstream outfile("binary.dat"); if(!outfile) { cerr<<"open error!"<<endl; exit(1);//退出程序 } outfile<<x<<endl; outfile.close( ); return 0; }
//将short int x=12345写入二进制文件 #include <iostream> #include <fstream> #include <cstdlib> using namespace std; int main( ) { short int x=12345; ofstream outfile("binary.dat",ios::binary); if(!outfile) { cerr<<"open error!"<<endl; exit(1);//退出程序 } outfile.write((char*)&x,2); outfile.close( ); return 0; }
将数据以二进制形式存放在磁盘文件中
#include<iostream> #include <fstream> #include<cstdlib> using namespace std; struct student { char name[5]; int num; int age; char sex; }; int main( ) { student stud[3]= { {"Li",25,18,'f'}, {"Fun",32,19,'m'}, {"Wang",40,17,'f'} }; ofstream outfile("stud.dat",ios::binary); if(!outfile) { cerr<<"open error!"<<endl; exit(1);//退出程序 } for(int i=0; i<3; i++) outfile.write((char*)&stud[i],sizeof(stud[i])); cout<<"任务完成,请查看文件。"<<endl; outfile.close( ); return 0; }
将二进制文件中的数据读入内存
#include<iostream> #include<fstream> #include<cstdlib> using namespace std; struct student { char name[5]; int num; int age; char sex; }; int main( ) { student stud[3]; int i; ifstream infile("stud.dat",ios::binary); if(!infile) { cerr<<"open error!"<<endl; abort( ); } for(i=0; i<3; i++) infile.read((char*)&stud[i],sizeof(stud[i])); infile.close( ); for(i=0; i<3; i++) { cout<<"NO."<<i+1<<endl; cout<<"name:"<<stud[i].name<<endl; cout<<"num:"<<stud[i].num<<endl;; cout<<"age:"<<stud[i].age<<endl; cout<<"sex:"<<stud[i].sex<<endl<<endl; } return 0; }