12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
#include <iostream.h> #include <conio.h> #include <stdio.h> const char *fn = "data.dat"; class Student { private: char name[31]; int age; float mark; public: // Initalization method Student() { for(int i=0; i<30; ++i) name[i] = '\0'; age = 0; mark = 0; } // Input data void input() { cout <<endl; cout <<" Name: "; cin.getline(name, 30); cout <<" Age: "; cin >> age; cout <<" Mark: "; cin >> mark; } // Output data void output() { cout <<endl; cout <<" Name: " << name; cout <<" Age: " << age; cout <<" Mark: " << mark; } }; void writeToFile() { Student s; s.input(); char *c = (char*)(&s); FILE *fo = fopen(fn, "w"); for(int i=0; i<sizeof(s); ++i) putc(c[i], fo); fclose(fo);s.output(); } void readFromFile() { Student *s; int len = 0; // lenght of the file char *c; // Array byte FILE *fi = fopen(fn, "r"); fseek(fi, 0, SEEK_END); // get variable len len = ftell(fi); c = new char[len]; for(int i=0; i<len; ++i) c[i] = getc(fi); fclose(fi); s = (Student*)c; s->output(); } int main() { cout <<" 1. Write to file" <<endl; cout <<" 2. Read from file" <<endl; cout <<" Select: "; switch(getche()) { case '1': writeToFile(); break; case '2': readFromFile(); break; } getch(); return 0; }