当我第一次运行程序时(尚未创建输出文件),它工作正常。但是当我再次运行它时(输出文件存在),它在读取最后一个输入后给出了一个段错误。
从问题的角度来看,它似乎与我的文件处理有关,但是当我尝试调试时,我发现我得到了段。 main()
中退出 for 循环之前的错误。
#include <stdio.h>
#define EMPS 3
struct employee
{
char firstname[40];
char lastname[40];
int id;
};
typedef struct employee Employee;
/* Input the employee data interactively from the keyboard */
void InputEmployeeRecord(Employee *ptrEmp);
/* Display the contents of a given Employee record */
void PrintEmployeeRecord(const Employee e);
/* Save the contents of the employee record list to the newly
created text file specified by FileName */
void SaveEmployeeRecord(const Employee e[], const char *FileName);
int id = 0;
int main()
{
Employee employees[EMPS];
for(int i = 0; i < EMPS; i++)
{
InputEmployeeRecord(&(employees[i]));
PrintEmployeeRecord(employees[i]);
}
SaveEmployeeRecord(employees, "employee.dat");
return 0;
}
void InputEmployeeRecord(Employee *ptrEmp)
{
printf("Enter first name\n");
scanf("%s", ptrEmp->firstname);
printf("Enter last name\n");
scanf("%s", ptrEmp->lastname);
ptrEmp->id = ++id;
}
void PrintEmployeeRecord(const Employee e)
{
printf("Employee %d: %s %s\n", e.id, e.firstname, e.lastname);
}
void SaveEmployeeRecord(const Employee e[], const char *FileName)
{
FILE* fptr = fopen(FileName, "r");
/* File doesn't exist */
if(fptr == NULL)
{
fclose(fptr);
// Create the file
FILE* fptr2 = fopen(FileName, "w");
fclose(fptr2);
// continue reading
fptr = fopen(FileName, "r");
}
char firstLetter;
int headerExists = 0;
if(!feof( fptr ))
{
fscanf(fptr, "%c", firstLetter);
if(firstLetter == 'I')
headerExists = 1;
}
fclose(fptr);
FILE* fptr2 = fopen(FileName, "a");
if(!headerExists)
fprintf(fptr2, "ID FIRSTNAME LASTNAME");
for(int i = 0; i < EMPS; i++)
fprintf(fptr2, "\n%d %s %s", e[i].id, e[i].firstname, e[i].lastname);
fclose(fptr2);
}
[代码最初在http://pastebin.com/tLefJhEH ]
最佳答案
问题可能出在 fscanf(fptr, "%c", firstLetter);
上。 %c 需要一个 char* 作为输入,而你给它一个 char(在 c 中是一个整数)。
要修复它,请尝试 fscanf(fptr, "%c", &firstLetter);
也不推荐在空指针上调用 fclose。
关于c - 在代码非常直接的部分发生段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5337303/