C 分段故障解决方案
我有一个文本文件,其中信息为C 分段故障解决方案,c,segmentation-fault,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";
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;
}
当我试图编译代码时,一切正常,但运行时显示以下错误:
分段故障(堆芯转储)
我的代码可能的解决方案和错误是什么
谢谢
附言:我在IBMAIX上使用CC。您试图使用
%s
扫描和打印两个整数,它应该是%d
,您试图使用%s
扫描和打印两个整数,它应该是%d使用%d
扫描和打印整数:
sscanf(line, "%d %d", &emp_id, &dept_id);
printf("%d %d", dept_id,dept_id);
(您可能还应该检查sscanf
的返回值,以确保它确实读取了两个整数-将第一行读取为整数是行不通的。)使用%d
扫描和打印整数:
sscanf(line, "%d %d", &emp_id, &dept_id);
printf("%d %d", dept_id,dept_id);
(您可能还应该检查sscanf
的返回值,以确保它确实读取了两个整数-将第一行读入整数是行不通的。)您的代码调用未定义的行为,因为您使用了错误的转换说明符来读取和打印整数。您应该使用%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);
}
您的代码调用未定义的行为,因为您在读取和打印整数时使用了错误的转换说明符。您应该使用%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);
}
您正在使用%s
扫描整数,这是用于扫描字符串的格式字符串。您必须使用%s
格式分别读取第一行,然后使用%d
读取后续行,因为标题项是字符串,数据将被读入整数。您正在使用%s
扫描整数,这是用于扫描字符串的格式字符串您必须使用%s
格式分别读取第一行,然后使用%d
读取后续行,因为标题项是字符串,数据被读取为整数。他还使用%s
扫描它们。他还使用%s
扫描它们。