对二进制文件的操作(c++ 程序设计 by 谭浩强 课本实例)
生活随笔
收集整理的這篇文章主要介紹了
对二进制文件的操作(c++ 程序设计 by 谭浩强 课本实例)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
//將一批數據以二進制形式存放在磁盤文件中
#include<iostream>
#include<fstream>
using namespace std;
struct student
{char name[20];int num;int age;char sex;
};
int main()
{student stud[3]={"Li",1001,18,'f',"Fun",1002,19,'m',"Wang",1004,17,'f'};//定義輸出文件流對象outfile,以輸出方式打開二進制文件ofstream outfile("stud.dat",ios::binary); if(!outfile){cout<<"open error!"<<endl;abort(); //退出程序與exit(1)作用相同}for(int i=0;i<3;i++)//第一個形參要用(char *)進行強制轉換為字符指針//第二個形參是指定一次輸出的字節數outfile.write(( char *)&stud[i],sizeof(stud[i]));outfile.close(); //關閉文件system("pause");return 0;
}//將剛才以二進制形式存放在磁盤文件的數據讀入內存并在顯示器上顯示
#include<iostream>
#include<fstream>
using namespace std;
struct student
{char name[20];int num;int age;char sex;
};int main()
{student stud[3];int i;//定義輸入文件流對象infile,以輸入方式打開磁盤文件stud.datifstream infile("stud.dat",ios::binary);if(!infile) //打開失敗{cerr<<"open error!"<<endl;abort();}for(i=0;i<3;i++)//調用成員函數read來讀二進制文件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;cout<<endl;}system("pause"); return 0;
}
轉載于:https://www.cnblogs.com/wwj9413/archive/2011/11/27/2638675.html
總結
以上是生活随笔為你收集整理的对二进制文件的操作(c++ 程序设计 by 谭浩强 课本实例)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gridview排序加箭头(二)
- 下一篇: s3c2440移植MQTT