小编fat*_*mah的帖子

如何将值传递给struct变量然后在文件中写入结构?

如何将值传递给struct变量我试图从用户那里获取员工信息,然后将其写入文件中,但我segmentation fault输入了员工姓名.这是我的代码.

#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;
    }
Run Code Online (Sandbox Code Playgroud)

输出(来自评论):

Fatmahs-MacBook-Air:~ fatmah$ …

c struct file fwrite segmentation-fault

2
推荐指数
1
解决办法
4027
查看次数

标签 统计

c ×1

file ×1

fwrite ×1

segmentation-fault ×1

struct ×1