如何将值传递给结构变量 我正在尝试从用户那里获取员工信息,然后将其写入文件,但在输入员工姓名后我得到了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 IDn");
scanf("%d",&id);
employee.id=id;
printf("nEnter Employee Namen");
scanf("%s",name);
employee.name=name;
printf("nEnter Employee Salaryn");
scanf("%d",&salary);
employee.salary=salary;
printf("nEnter Employee Agen");
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;
}
输出(取自评论):
Fatmahs-MacBook-Air:~ fatmah$ gcc -o em em.cFatmahs-MacBook-Air:~ fatmah$ ./em输入员工编号88输入员工姓名UU分段错误:11
更改
scanf("%s",name);
employee.name=name;
自
scanf("%s",name);
strcpy(employee.name, name);
的,更好的是,正如Dukeling和hmjd所建议的那样。
scanf("%19s", employee.name);
这是一个主要问题:
scanf("%s",name);
employee.name=name;
成员name
是一个数组,您无法分配给它。而是使用strcpy
复制到它。
-
创建一个 typedef 结构
record_t
,使内容更短、更易于理解。typedef struct { int id; char name[20]; int salary; int age; } record_t;
-
首先创建文件并格式化。
void file2Creator( FILE *fp ) { int i; // Counter to create the file. record_t data = { 0, "", 0, 0 }; // A blank example to format the file. /* You will create 100 consecutive records*/ for( i = 1; i <= 100; i++ ){ fwrite( &data, sizeof( record_t ), 1, fp ); } fclose( fp ); // You can close the file here or later however you need. }
-
编写函数以填充文件。
void fillFile( FILE *fp ) { int position; record_t data = { 0, "", 0, 0 }; printf( "Enter the position to fill (1-100) 0 to finish:n?" ); scanf( "%d", &position ); while( position != 0 ){ printf( "Enter the id, name, and the two other values (integers):n?" ); fscanf( stdin, "%d%s%d%d", &data.id, data.name, data.salary, data.age ); /* You have to seek the pointer. */ fseek( fp, ( position - 1 ) * sizeof( record_t ), SEEK_SET ); fwrite( &data, sizeof( record_t ), 1, fp ); printf( "Enter a new position (1-100) 0 to finish:n?" ); scanf( "%d", &position ); } fclose( fPtr ); //You can close the file or not, depends in what you need. }
您可以将其用作参考 比较和检查两个文件中的列