2015-09-06 45 views
1

我剛剛開始使用二進制文件。我嘗試了一個簡單的程序:閱讀C++中的二進制文件2

class student 
{ 
    int rno; 
    char sname[20]; 
    public: 
    void input(); 
    void output(); 
}; 

void main() 
{ 
    clrscr(); 
    student s; 
    char reply; 
    fstream fil; 

    fil.open("stu.dat",ios::binary|ios::app); 
    do 
    { 
     s.input(); 
     fil.write((char*)&s,sizeof(s)); 
     cout<<"more (Y/N)\n"; 
     cin>>reply; 
    } 
    while(toupper(reply)=='Y'); 
    fil.close(); 
} 

void student::input() 
{ 
cout<<"enter the roll\n"; 
cin>>rno; 
cout<<endl; 
cout<<"enter the name\n"; 
gets(sname); 
cout<<endl; 
} 

void student::output() 
{ 
cout<<" the roll\n"; 
cout<<rno; 
cout<<endl; 
cout<<"the name\n"; 
puts(sname); 
cout<<endl; 

但是,當我讀到這(說我已經加入3名學生)只剩下最後學生的詳情。爲什麼? 閱讀代碼:

#include<fstream.h> 
    #include<conio.h> 
    #include<stdio.h> 
    #include<ctype.h> 

    class student 
    { 
    int rno; 
    char sname[20]; 
    public: 
    void input(); 
    void output(); 
    }; 

    void main() 
    { 
    clrscr(); 
    student s; 
    fstream fil; 
    fil.open("stu.dat",ios::binary|ios::in); 

    while(fil.read((char*)&s,sizeof(s))); 
    { 
    s.output(); 
    getch(); 
    } 
    fil.close(); 
    } 

    void student::input() 
    { 
    cout<<"enter the roll\n"; 
    cin>>rno; 
    cout<<endl; 
    cout<<"enter the name\n"; 
    gets(sname); 
    cout<<endl; 
    } 

    void student::output() 
    { 
    cout<<" the roll\n"; 
    cout<<rno; 
    cout<<endl; 
    cout<<"the name\n"; 
    puts(sname); 
    cout<<endl; 
    } 

但是,當我讀到這(說我已經加入3名學生)只剩下最後學生的詳情。爲什麼?

我哪裏錯了?

+0

既然你不顯示閱讀代碼誰可以說?你似乎認爲錯誤出現在編寫代碼中,但對我來說,這看起來或多或少。 – john

+0

將對象轉儲爲二進制文件並將其讀回來是不安全的。您必須使用函數來單獨讀取/寫入字段。 –

+0

@NeilKirk在某些有限的情況下是安全的,如果這些情況覆蓋了OP的課程,現在不能記得。 – john

回答

0

我建議讓學生寫自己的文件

void student::Write(fstream & fil) 
{ 
    fil.write((char*)&rno,sizeof(rno)); 
    fil.write((char*)&sname,20); 
} 

這樣,如果你的類屬性改變你不需要重寫任何東西,但學生實現代碼。

+0

但是,你能告訴我爲什麼我得到一個錯誤?我也嘗試將兩個程序合併到一個程序中,但仍然出現相同的錯誤 – yasir

+0

嘗試更改,代碼會更好,並且「錯誤」可能已消失。僅僅盯着代碼是毫無意義的,花時間去改進它,直到你修復問題或者注意到造成它的原因,因爲你的代碼非常乾淨。現在你的代碼非常混亂,很難知道發生了什麼。 – ravenspoint