从C中的文件解析为double

时间:2014-04-29 21:44:16

标签: c parsing scanf

我有以下代码从文件中读取列表数字,但fscanf返回-1。我做错了吗?

提前致谢

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <errno.h>
int main(int argc, char** argv) {
FILE *in;
if (argc != 2) {
  fprintf(stderr,"Wrong number of parameters.\n");
  fprintf(stderr,"Please give the path of input file.\n");
  return 1;
}
if((in = fopen(argv[1],"r")) == NULL) {
    fprintf(stderr,"\'%s\' cannot be opened.\n",argv[1]);
}
int lines = 0;
char c;
while( (c=fgetc(in)) != EOF) {
    if(c == '\n') {lines++;}
}
printf("%d lines\n",lines);
int i = 0;
double a, b;
double x[lines], y[lines];
for(i; i < lines; i++) {
    if(fscanf(in,"%lf %lf", &a, &b) != 2) {
        fprintf(stderr,"Wrong input format.\n");
    }
    printf("%lf %lf",a,b);
}
return (EXIT_SUCCESS);

}

2 个答案:

答案 0 :(得分:1)

您已经使用fgetc完全阅读了该文件,因此当您调用fscanf时,读取指针已经位于文件的末尾。

您可以使用

手动将读取指针放在开头
fseek(in, 0, SEEK_SET);
在你的循环前面

答案 1 :(得分:1)

你读完整个文件以找到行数。所以在结尾文件指针已经到了结尾..当你打电话给&#39; fscanf&#39;又一次?

您需要将文件指针重置为重新开始

printf("%d lines\n",lines);
rewind(in);
int i = 0;
相关问题