重複の可能性:
EOFが最後の行を繰り返すまでテキストファイルから読み取る
次のコードを使用してファイルにデータを書き込んでいます
//temp is class object
fstream f;
f.open ("file", ios::in|ios::out|ios::binary);
for(i=0;i<number_of_employees ;++i)
{
temp.getdata();
f.write( (char*)&temp,sizeof(temp));
}
f.close();
temp は次のクラスのオブジェクトです
class employee
{
char eno[20];
char ename[20];
char desg[20];
int bpay;
int ded;
public:
void getdata();
void displaydata();
}
しかし、このコードを使用してデータを書き込むと、最後にファイルに書き込まれたオブジェクトが 2 回書き込まれることがわかりました。
ファイルから読み取る私の機能は
fstream f;
f.open ("file", ios::in|ios::out|ios::binary);
while(f)
{
f.read((char*)&temp, sizeof(temp));
temp.displaydata();
}
f.close();
以下は、eofまで読み取られたときのファイルを示しています
Number :1
Name :seb
Designation:ceo
Basic Pay :1000
Deductions :100
Number :2
Name :sanoj
Designation:cto
Basic Pay :2000
Deductions :400
Number :2
Name :sanoj
Designation:cto
Basic Pay :2000
Deductions :400
これの原因は何ですか?どうすれば解決できますか?