1

我似乎没有问题从文件中读取然后创建结构,但是打印结构会给我一个分段错误。

员工定义

struct _Employee {
  int salary; // Monthly salary in UK pounds sterling
  char *name; // Pointer to character string holding name of employee.
  char* department;           // MUST be dynamically allocated from the heap.
};

typedef struct _Employee Employee;

从文件中读取的函数

Employee* readfile(FILE* file) {
  Employee* newemployee;
  newemployee = malloc(sizeof(Employee));
  char tempsalary[10];
  int salary;
  char name[20];
  char dept[20];
  char* names = malloc(sizeof(name));
  char* depts = malloc(sizeof(dept));
  char* status; // Returned by fgets(). Will be NULL at EOF


    status = fgets(names, sizeof(name), file);
    if (status == NULL)
      return NULL;
    else {
      newemployee->name = strdup(status);


    fgets(tempsalary, sizeof(name), file);
    sscanf(tempsalary, "%d", &salary);
    newemployee->salary = salary;

    fgets(depts, sizeof(dept), file);
    newemployee->department = strdup(depts);

    return newemployee;
    }
}

打印由 readfile 生成的结构的函数。

void printEmployee(Employee *employee) {
      fprintf(stdout, "Name = %sSalary = %d\nDepartment = %s\n\n", // SEGFAULT HERE
          employee->name, employee->salary, employee->department);
}

主程序

int main() {
  FILE* file;
  file = fopen ("stest2.txt", "r");
  Employee* employees[max_employees];
  int i;
  int c;
  Employee* temp;

    for (i = 0; i < max_employees; i++) {
    employees[i] = readfile(file)   
    printEmployee(employees[i]);
    }
  return 0;
}
4

2 回答 2

0

我将不得不在堆栈上涂鸦 fgets()。改变这个:

 fgets(tempsalary, sizeof(name), file);

对此:

 fgets(tempsalary, sizeof(tempsalary), file);

可能不是问题,但肯定是“一个”问题。

于 2013-02-12T17:58:16.857 回答
0

如果 fgets 错误,readfile() 可以返回 NULL。这种情况主要不处理。作为一个原始建议:

    for (i = 0; i < max_employees; i++) {
        employees[i] = readfile(file);
        if(NULL != employees[i])
        {   
            printEmployee(employees[i]);
        }
        else
        {
            printf("Error reading file");
        }
于 2013-02-12T18:06:03.447 回答