Write and read file again

My code is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#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;
}


Why after I write data (eg a Student) to a file, I read again, but the infomations of the Student which was written, is wrong !

Can anybody debug for me?
Thanhs a lot
1. Never, EVER, read or write the in-memory image of a class from or to a file.
2. On line 66, you're not setting the file pointer back to the beginning of the file.
Can you tell me the detail, please
Topic archived. No new replies allowed.