Lect12
.pdfДвоичныефайлыиструктуры
int _tmain(int argc, _TCHAR* argv[]) { struct student s1, s2;
cout << "NZ:"; cin >> s1.nz; cout << "Course:"; cin >> s1.course; cin.ignore(); cout << "Name:";
cin.getline(s1.name, 40);
cout << "Number of bad marks:"; cin >> s1.numNeud;
Двоичныефайлыиструктуры
ofstream |
f1("student.bin",ios::binary); |
if (!f1) |
{ |
cerr << |
"Cannot open file" << endl; |
return |
1; |
}
f1.write((const char*)&s1, sizeof(struct student));
f1.close();
Двоичныефайлыиструктуры
ifstream |
f2("student.bin",ios::binary); |
if (!f2) |
{ |
cerr << |
"Cannot open file" << endl; |
return |
1; |
}
f2.read((char*)&s2, sizeof(struct student));
int rdNum = f2.gcount(); f2.close();
Двоичныефайлыиструктуры
cout << "Student read from file (" << rdNum << "bytes):" << endl;
cout << s2.nz << endl; cout << s2.course << endl; cout << s2.name << endl; cout << s2.numNeud << endl; return 0;
}
Результатработы
NZ:222333
Course:2 Name:John Smith
Number of bad marks:3
Student read from file (50bytes): 222333
John Smith 2 3
Программа№2
Отдельнаяпрограмма,котораясчитываетданные изэтогофайла.
#include "stdafx.h" #include <iostream> #include <fstream> using namespace std; struct student {
int nz;
char name[40]; unsigned short course; int numNeud;
};
Программа№2
int _tmain(int argc, _TCHAR* argv[]) { struct student s2;
ifstream f2("student.bin", ios::binary);
if (!f2) {
cerr << "Cannot open file" << endl; return 1;
}
f2.read((char*)&s2, sizeof(struct student));
int rdNum = f2.gcount(); f2.close();
Программа№2
cout << "Student read from file (" << rdNum << "bytes):" << endl;
cout << s2.nz << endl; cout << s2.course << endl; cout << s2.name << endl; cout << s2.numNeud << endl;
}
Программа№2(результаты)
Student read from file (50bytes): 222333
John Smith 2 -859045888
Откудастолькодолгов??? ~8-[ ]
"Разборполётов"
Очевиднаяпроблема:неверноечтение двоичногофайла.Добавимвывод информацииоструктуревкаждую программу:
cout << "Student size is " << sizeof(struct student)
<< endl;