Search code examples
cfilestructsegmentation-faultfwrite

how to pass values to struct variable then write the struct in a file?


How can I pass values to struct variable I'm trying to get the employee information from the user then write them in a file, but I got a segmentation fault after entering employee name. This is my code.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct record_em{
    int id;
    char name[20];
    int salary;
    int age;
};

int main( void )
{
    struct record_em employee;
    FILE *fp;
    int id, salary, age;
    char name[20];
    int n=1;

    fp = fopen("empRecord.dat","a");
    while(n==1){
        printf("\nEnter Employee ID\n");
        scanf("%d",&id);
        employee.id=id;
        printf("\nEnter Employee Name\n");
        scanf("%s",name);
        employee.name=name;
        printf("\nEnter Employee Salary\n");
        scanf("%d",&salary);
        employee.salary=salary;
        printf("\nEnter Employee Age\n");
        scanf("%d",&age);
        employee.age=age;
        fwrite(&employee,sizeof(employee),1,fp);
        printf("Enter 1 to add new record \n");
        scanf("%d",&n);
    }

    fclose(fp);

    return 0;
    }

Output (taken from comment):

Fatmahs-MacBook-Air:~ fatmah$ gcc -o em em.c
Fatmahs-MacBook-Air:~ fatmah$ ./em
Enter Employee ID
88
Enter Employee Name
uu
Segmentation fault: 11 

Solution

  • Change

    scanf("%s",name);
    employee.name=name;
    

    to

    scanf("%s",name);
    strcpy(employee.name, name);
    

    Of, better still, as suggested by Dukeling & hmjd

    scanf("%19s", employee.name);