第十七周任務0

來源:互聯網
上載者:User

閱讀程式指出功能:

#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(位移量,參照位置)
返回最後一次輸入所讀入的位元組數
返回輸入檔案指標的當前位置
將輸入檔案中指標移到指定的位置
以參照位置為基礎移動若干位元組
返回輸出檔案指標當前的位置
將輸出檔案中指標移到指定的位置
以參照位置為基礎移動若干位元組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.