【问题标题】:Segmentation fault occurring at very straight-forward part of the code分段错误发生在代码的非常直接的部分
【发布时间】:2011-03-17 09:41:40
【问题描述】:

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

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

【问题讨论】:

  • 您可能希望限制scanf 中的字符串大小以防止缓冲区溢出:scanf("%39s", ptrEmp-&gt;firstname)

标签: c file segmentation-fault


【解决方案1】:

问题可能在于fscanf(fptr, "%c", firstLetter);。 %c 需要一个 char* 作为输入,而你给它一个 char(它是 c 中的一个整数)。

要修复它,请尝试fscanf(fptr, "%c", &amp;firstLetter);

不建议同时在空指针上调用 fclose。

【讨论】:

    【解决方案2】:

    我的错,是这一行:

    68.                fscanf(fptr, "%c", firstLetter);
    

    应该是:

    68.                fscanf(fptr, "%c", &firstLetter);
    

    fscanfscanf 的参数是存储数据的内存位置的地址。

    字符串不需要&amp;,因为字符串已经是地址。

    【讨论】:

    • 为什么会失败?第二次调用fopen 时文件存在。是访问权限问题吗?
    • 谢谢.. 我不敢相信这是我的错误
    猜你喜欢
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2012-09-04
    • 2013-04-12
    相关资源
    最近更新 更多