我有一个文本文件,其中包含信息
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;
}
当我试图编译代码时,一切都很好,但当运行时,它显示了以下错误:
分段故障(核心转储)
我的代码可能有哪些解决方案和错误。
感谢
第页。S:我在IBMAIX上,正在使用CC。别无选择。
使用%d
扫描和打印整数:
sscanf(line, "%d %d", &emp_id, &dept_id);
printf("%d %d", dept_id,dept_id);
(您可能也应该检查sscanf
的返回值,以确保它确实读取了两个整数-将第一行读取为整数是行不通的。)
您正在尝试使用%s
扫描并打印两个整数,它应该是%d
。
您的代码调用未定义的行为,因为您在读取和打印整数时使用了错误的转换说明符。您应该使用%d
而不是%s
。此外,由于默认情况下stdin
流是行缓冲的,因此输出一条换行符以立即将输出打印到屏幕。将while
循环更改为
while(fgets(line, 100, fp) != NULL)
{
// output a newline to immediately print the output
printf("%sn", 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 %dn", dept_id, dept_id);
}