分段故障解决方案

时间:2014-04-17 15:08:26

标签: c segmentation-fault

我有一个信息为

的文本文件
Emp_Id  Dept_Id
  1          1
  1          2
  1          3
  2          2
  2          4

我正在尝试使用以下代码通过C读取此文件:

#include "stdio.h"
#include "stdlib.h"

int main()
{
    FILE *fp;
    char line[100];
    char fname[] = "emp_dept_Id.txt";
    int emp_id, dept_id;

    // Read the file in read mode
    fp = fopen(fname, "r");

    // check if file does not exist
    if (fp == NULL)
    {
        printf("File does not exist");
        exit(-1);
    }

    while (fgets(line, 100, fp) != NULL)
    {
        printf("%s", line);
        sscanf(line, "%s %s", &emp_id, &dept_id);
        printf("%s %s", dept_id, dept_id);
    }

    fclose(fp);

    return 0;
}

虽然我正在尝试编译代码,但它在运行时显示以下错误:

分段错误(核心转储)

我的代码可能存在哪些解决方案和错误。

谢谢

P.S:我在IBM AIX上使用CC。没有其他选择可以离开他们。

3 个答案:

答案 0 :(得分:4)

使用%d扫描并打印整数:

sscanf(line, "%d %d", &emp_id, &dept_id);
printf("%d %d", dept_id,dept_id);

(您可能应该检查sscanf的返回值,以确保它确实读取了两个整数 - 将第一行读成整数是行不通的。)

答案 1 :(得分:2)

您正尝试使用%s扫描并打印两个整数,它应为%d

答案 2 :(得分:0)

您的代码调用未定义的行为,因为您使用错误的转换说明符来读取和打印整数。您应该使用%d代替%s。此外,输出换行符以立即将输出打印到屏幕,因为默认情况下stdin流是行缓冲的。将您的while循环更改为

while(fgets(line, 100, fp) != NULL)
{   
    // output a newline to immediately print the output
    printf("%s\n", line);

    // change %s to %d. also space is not needed
    // between %d and %d since %d skips the leading 
    // whitespace characters
    sscanf(line, "%d%d", &emp_id, &dept_id);

    // sscanf returns the number of input items 
    // successfully matched and assigned. you should
    // check this value in case the data in the file 
    // is not in the correct format

    // output a newline to immediately print the output
    printf("%d %d\n", dept_id, dept_id);
}