【发布时间】:2017-06-16 05:43:55
【问题描述】:
我正在尝试从以下格式的 csv 文件中读取数据:
a_x,a_y,v_x,o_rear,o_front,theta,type
-0.040,10.206,-0.000,0.000,-0.000,-0.002,plane
1.269,9.813,0.011,0.043,0.091,-0.002,plane
1.266,9.985,0.021,0.086,0.177,-0.002,plane
1.257,10.002,0.032,0.130,0.265,-0.002,plane
1.256,10.004,0.043,0.173,0.353,-0.002,plane
1.257,10.003,0.053,0.216,0.440,-0.002,plane
1.258,10.002,0.064,0.259,0.527,-0.002,plane
1.258,10.002,0.074,0.302,0.615,-0.002,plane
我写了以下代码:-
FILE *in_file = fopen(argv[1], "r");
int i=0, s=0;
char *temp;
fscanf(in_file,"%s",temp);
printf("%s\n",temp);
while(i<100){
float a_x,a_y,v_x,o_rear,o_front,theta;
char *type;
if((s = fscanf(in_file,"%f,%f,%f,%f,%f,%f,%[^,]",&a_x,&a_y,&v_x,&o_rear,&o_front,&theta,type))!=7)
printf("%7d,%d,%f,%f,%f,%f,%f,%f,%s\n",++i,s,a_x,a_y,v_x,o_rear,o_front,theta,type);
else{
printf("ALL GOOD: %7d\n",++i);
}
}
我遇到了分段错误。在运行 gdb 时,我发现它发生在 fscanf(in_file,"%s",temp); 行并出现以下错误:-
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff71c6f64 in _IO_vfscanf_internal (s=<optimized out>, format=<optimized out>, argptr=argptr@entry=0x7fffffffda48, errp=errp@entry=0x0)
at vfscanf.c:1107
1107 vfscanf.c: No such file or directory.
堆栈跟踪:-
#0 0x00007ffff71c6f64 in _IO_vfscanf_internal (s=<optimized out>, format=<optimized out>, argptr=argptr@entry=0x7fffffffda48,
errp=errp@entry=0x0) at vfscanf.c:1107
#1 0x00007ffff71cce47 in ___vfscanf (s=<optimized out>, format=<optimized out>, argptr=argptr@entry=0x7fffffffda48) at vfscanf.c:3066
#2 0x00007ffff71d47b7 in __fscanf (stream=<optimized out>, format=<optimized out>) at fscanf.c:31
#3 0x0000555555555186 in main (argc=2, argv=0x7fffffffdc58) at data_handler.cpp:23
令人惊讶的是,当我使用type 变量转储第一行时,我没有遇到任何段错误。相反,fscanf 第一次返回 7,然后返回 0。因此我可以正确读取第二行,但不能正确读取其他行。我究竟做错了什么?我想了解为什么会发生这种行为。
【问题讨论】:
-
char *temp; fscanf(in_file,"%s",temp);-- 这是错误的。您正在读取一个未初始化的指针。 -
你给
temp赋值了吗?如果不是,为什么要将其(无意义的)值传递给fscanf? -
但是当我在循环外声明
type变量并使用它时会发生什么? -
我纠正了它,它仍然在发生 -- 你的程序有几个问题,因为你在其他地方使用未初始化的指针变量时犯了同样的错误,即其他
fscanf电话。反正你用的是C++,那你为什么要写C代码呢? -
如果您使用 C++ 流,则无需为您要读取的内容使用格式说明符。C++ 流知道您要读取的类型——无需告诉编译器
%f或%s,
标签: c++ io segmentation-fault scanf