当我尝试使用菜单中的案例1将文件读取到结构中时,程序将退出。
我试图将两个文件作为单独的函数读入结构中,但是两者似乎都结束了我的函数,当我尝试将它们放到主目录中时,又发生了同样的情况。 在这个阶段,我几乎没有想法了,因为我对C语言还很陌生,只花了几周的时间。
FILE* fp;
/* structured type definition */
typedef struct empl
{
char name[20];
char surn[20];
char PPS[20];
char nat[20];
int age;
int mar;
int cld;
} empl_type;
typedef struct benf
{
char PPS[20];
int sal;
int pen;
int hlt;
int all;
} benf_type;
/* 1-dimensional array that stores benefits related data for all registered employees*/
benf_type benf[5000];
/* 1-dimensional array that stores employees related data */
empl_type empl[5000];
/* no current registered empl (no records) */
int noempl = 0;
/* no current benefits (no records) */
int nobenf = 0;
/* main function */
int main()
{
int ans = 1;
/* welcome message */
printf("Welcome to the program!\n");
while(ans != 6)
{
printf("Menu\n");
printf("1-Read data from files\n");
printf("2-Apply allowance\n");
printf("3-Search\n");
printf("4-Print to screen\n");
printf("5-Write data in files\n");
printf("6-Exit\n");
scanf("%d", &ans);
switch(ans)
{
case 1: read_files(); break;
case 2: apply_allow(benf, nobenf); break;
case 3: search_PPS(); break;
case 4: print_screen(); break;
case 5: write_file(); break;
}
}
printf("Goodbye!\n");
return (EXIT_SUCCESS);
}
void read_files()
{
noempl = read_empl_file("e.txt", empl);
nobenf = read_benf_file("b.txt", benf);
}
int read_empl_file(char* file_name, empl_type empl[])
{
char ch;
/* open file */
fp = fopen(file_name, "r");
while(!feof(fp))
{
/* read on record from file */
fscanf(fp,"%s%c%s%c%s%c%s%c%d%c%d%c%d%c", empl[noempl].name, &ch, empl[noempl].surn, &ch, empl[noempl].PPS, &ch, empl[noempl].nat, &ch, &empl[noempl].age, &ch, &empl[noempl].mar, &ch, &empl[noempl].cld, &ch);
/* increase the number of records read*/
noempl++;
}
/* close file */
fclose(fp);
return noempl;
}
int read_benf_file(char* file_name, benf_type benf[])
{
char ch;
/* open file */
fp = fopen(file_name, "r");
while(!feof(fp))
{
/* read on record from file */
fscanf(fp,"%s%c%d%c%d%c%d%c%d%c", benf[nobenf].PPS, &ch, &benf[nobenf].sal, &ch, &benf[nobenf].pen, &ch, &benf[nobenf].hlt, &ch, &benf[nobenf].all, &ch);
/* increase the number of records read*/
nobenf++;
}
/* close file */
fclose(fp);
return nobenf;
}