c - 在代码非常直接的部分发生段错误

标签 c file segmentation-fault

当我第一次运行程序时(尚未创建输出文件),它工作正常。但是当我再次运行它时(输出文件存在),它在读取最后一个输入后给出了一个段错误。

从问题的角度来看,它似乎与我的文件处理有关,但是当我尝试调试时,我发现我得到了段。 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/

相关文章:

javascript - 在 WebExtensions(JavaScript、Firefox)中读取 LZ4 压缩文本文件 (mozlz4)

Python,如何清空文件中的特定行

c - 矩阵排序段错误

c - c 中的段错误 - 可能与指针有关

c++ - 如何在 Linux 中高效等待 RS232 的 CTS 或 DSR?

C : Function to read a file to a singly linked list and return head pointer?

c - 检索C中组中小数字的最快方法?

c - 迁移到 4.1.23 的 Netfilter 内核模块 - 无法检索 ip header

git - 通过 build.gradle 任务在项目目录中创建 version.txt 文件

linux -/bin/bash 在启动时给出段错误