[英]how to pass values to struct variable then write the struct in a file?
如何將值傳遞給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;
}
輸出(來自評論):
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
更改
scanf("%s",name);
employee.name=name;
至
scanf("%s",name);
strcpy(employee.name, name);
更好的是,正如Dukeling&hmjd所建議的那樣
scanf("%19s", employee.name);
創建一個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. }
您可以將此作為參考比較和檢查兩個文件中的列
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.