0

Probelm_1 : Make a program that receives the employee's name, ID, age, and salary on the keyboard and stores them in the binary file expire.bin However, employee information should be expressed in structure, name is defined as a string, and the rest of the information is defined as an integer. And it is estimated that the number of inputs is unknown.

Contents to enter (currently, the number of employees is 6, but the program is created so that it can be stored more than that)

ex) example input:

tom 10331 21 24000000
eric 10333 23 28000000
jane 40234 26 40000000
mary 30022 46 65000000
kim 90032 25 38000000
Lee 90038 24 30000000

After that, Write a program that reads the contents of the employment.bin file generated in question 1 and outputs it to the screen.



and I wrote a simple code about only one input but, it didn't work,, Can you explain why this program doesn't work?

#include <stdio.h>

typedef struct{
        char *name;
        int id, age, salary;
} Employee;

int main(){
        char tmp[1000];
        Employee e;

        FILE* fout;
        FILE* fin;
        fout = fopen("employee.bin", "wb");

        printf("Name, ID, age, salary: ");
        scanf("%s %d %d %d", e.name, &e.id, &e.age, &e.salary);
        fwrite(&e, sizeof(e), 1, fout);
        fclose(fout);
        fin = fopen("employee.bin", "rb");
        fread(tmp, sizeof(char), 100, fin);

        printf("%s",tmp);
        fclose(fin);
}
y J.
  • 131
  • 4
  • 2
    `e.name` is an uninitialized pointer variable. You are reading a string directly into whatever memory it happens to be pointing at. Furthermore, even if you _did_ allocate it correctly, you cannot hope to store a retrievable string like that because when you write `e` as binary data, you are writing the _pointer_ value, not the actual string. You'll need a smarter output routine, or declare `name` as a fixed-size char array in the structure. – paddy Nov 17 '21 at 07:54
  • 1
    BTW this looks more like C code than C++. If so, please re-tag it to C. – kiner_shah Nov 17 '21 at 08:37
  • `fwrite(&e, sizeof(e), 1, fout)` -- This could never work if you understand what the second parameter, `sizeof(e)` means. The `name` pointer could point to a buffer that had a1000 characters, and `sizeof(e)` would be maybe 20 or 24 bytes. So how are you going to write 1000 bytes if you only specify 20 bytes? Ergo, that line of code could never work correctly. That in a nutshell is why the program didn't and cannot work. How to fix such a program is a different story. – PaulMcKenzie Nov 17 '21 at 09:13
  • You can't store pointers on disk for later use. Read about "serialization". – molbdnilo Nov 17 '21 at 09:31

0 Answers0