/* * files.cpp * * Created on: 10.10.2013 * Author: trifon */ #include #include #include "student.h" using namespace std; void testofiles() { ofstream test("test.txt", ios::app); test << "Hello, this is a text file!\n"; test << 1.2 << ' ' << 10 << endl; test.close(); int a[] = { 1, 2, 3, 5, 8, 13 }; ofstream testbin("test.dat", ios::out | ios::binary); testbin.write((const char*)a, 6 * sizeof(int)); testbin.close(); } void testifiles() { ifstream test("test.txt"); char line[100]; test.getline(line, 100); cout << "Read line: " << line << endl; double d; int i; test >> d >> i; cout << "d = " << d << endl; cout << "i = " << i << endl; test.close(); ifstream testbin("test.dat", ios::in | ios::binary); int a[6] = {0}; // !!! testbin.seekg(2); testbin.seekg(sizeof(int)); testbin.read((char*)a, sizeof(int) * 2); testbin.seekg(sizeof(int), ios::cur); testbin.read((char*)(a+2), sizeof(int) * 2); testbin.seekg(sizeof(int) * -2, ios::end); testbin.read((char*)a, sizeof(int) * 2); for(i = 0; i < 6; i++) cout << a[i] << ' '; cout << endl; testbin.close(); } void testiofile() { fstream f("essay.txt", ios::in | ios::out); char line[100]; //f.getline(line, 100); //cout << "Read line: " << line << endl; f << "IGNORE THIS TEXT!\n"; f.close(); } const char STUDENTS_FILE[] = "students.txt"; const char STUDENTS_DATA[] = "students.dat"; void writeStudents() { Student s1("Иван Иванов", 40000, 5.5); Student s2("Мария Георгиева", 40001, 6); ofstream of(STUDENTS_FILE); of << s1 << s2 << Student("Петър Петров", 40002, 4.75); of.close(); } void readStudents() { Student s("", 0, 0); ifstream fi(STUDENTS_FILE); while (fi >> s) cout << s; fi.close(); } void writeBinary() { Student s("", 0, 0); ifstream fit(STUDENTS_FILE); ofstream fob(STUDENTS_DATA, ios::out | ios::binary); while (fit >> s) fob.write((const char*)&s, sizeof(Student)); fit.close(); fob.close(); } void readBinary() { Student s("", 0, 0); ifstream fib(STUDENTS_DATA, ios::in | ios::binary); while (fib.read((char*)&s, sizeof(Student))) cout << s; fib.close(); } Student readStudent(int i) { ifstream fib(STUDENTS_DATA, ios::in | ios::binary); fib.seekg(i * sizeof(Student)); Student s("", 0, 0); fib.read((char*)&s, sizeof(Student)); if (!fib) { cerr << "Няма такъв студент!"; return s; } fib.close(); return s; } void writeStudent(Student const& s, int i) { fstream fob(STUDENTS_DATA, ios::out | ios::in | ios::binary); fob.seekp(i * sizeof(Student)); fob.write((const char*)&s, sizeof(Student)); fob.close(); } int main() { //testofiles(); //testifiles(); //testiofile(); // writeStudents(); // readStudents(); writeBinary(); //readBinary(); // cout << readStudent(4); writeStudent(readStudent(1), 2); writeStudent(readStudent(1), 10); readBinary(); }