閱讀程式指出功能:
#include<iostream>#include <fstream>using namespace std;class Student//定義Student類{public:Student(void){}Student(int n, char nam[20], float s):num(n),score(s){strcpy(name,nam);}//字串複製void setNum(int n){num=n;}void setName(char nam[20]){strcpy(name,nam);}void setScore(float s){score=s;}void show() {cout<<num<<" "<<name<<" "<<score<<endl;} //顯示通過<<的重載實現更自然private:int num;char name[20];float score;};int main( ){ Student stud[5]={Student(1001,"Li",85),Student(1002,"Fun",97.5),Student(1004,"Wang",54),Student(1006,"Tan",76.5),Student(1010,"ling",96)};fstream iofile("stud.dat",ios::in|ios::out|ios::binary);//用fstream類定義輸入輸出二進位檔案流對象iofileif(!iofile){ cerr<<"open error!"<<endl;abort( );//退出程式}cout<<"(1)向磁碟檔案輸出個學生的資料並顯示出來"<<endl;for(int i=0;i<5;i++){iofile.write((char *)&stud[i],sizeof(stud[i]));//將資料寫入檔案stud[i].show();//顯示當前對象的資料}cout<<"(2)將磁碟檔案中的第,3,5個學生資料讀入程式,並顯示出來"<<endl;Student stud1[5];//用來存放從磁碟檔案讀入的資料for(int i=0;i<5;i=i+2){ iofile.seekg(i*sizeof(stud[i]),ios::beg);//定位於第0,2,4學生資料開頭iofile.read((char *)&stud1[i/2],sizeof(stud1[0]));//先後讀入3個學生的資料,存放在stud1[0],stud[1],stud[2]中stud1[i/2].show();}cout<<endl;cout<<"(3)將第個學生的資料修改後存回磁碟檔案中的原有位置"<<endl;stud[2].setNum(1012);//修改第3個學生的資料stud[2].setName("Wu");stud[2].setScore(60);iofile.seekp(2*sizeof(stud[0]),ios::beg);//定位於第3個學生資料的開頭iofile.write((char *)&stud[2],sizeof(stud[2]));//更新第3個學生的資料iofile.seekg(0,ios::beg);//重新置放於檔案開頭cout<<"(4)從磁碟檔案讀入修改後的個學生的資料並顯示出來"<<endl;for(int i=0;i<5;i++){ iofile.read((char *)&stud[i],sizeof(stud[i]));//讀入五個學生的資料stud[i].show();}iofile.close( );system("pause");return 0;}
運行結果;
(1)向磁碟檔案輸出個學生的資料並顯示出來
1001 Li 85
1002 Fun 97.5
1004 Wang 54
1006 Tan 76.5
1010 ling 96
(2)將磁碟檔案中的第,3,5個學生資料讀入程式,並顯示出來
1001 Li 85
1004 Wang 54
1010 ling 96
(3)將第個學生的資料修改後存回磁碟檔案中的原有位置
(4)從磁碟檔案讀入修改後的個學生的資料並顯示出來
1001 Li 85
1002 Fun 97.5
1012 Wu 60
1006 Tan 76.5
1010 ling 96
請按任意鍵繼續. . .
不能用ifstream,ofstream類定義輸入輸出的二進位檔案流對象,而應當用fstream類
檔案流與檔案指標有關的成員函數
| 成員函數 |
作用 |
gcount() tellg() seekg(檔案中的位置) seekg(位移量,參照位置) tellp() seekp(檔案中的位置) seekp(位移量,參照位置) |
返回最後一次輸入所讀入的位元組數 返回輸入檔案指標的當前位置 將輸入檔案中指標移到指定的位置 以參照位置為基礎移動若干位元組 返回輸出檔案指標當前的位置 將輸出檔案中指標移到指定的位置 以參照位置為基礎移動若干位元組 |