我有以下代碼從文件讀取列表中的數字,但fscanf返回-1。我是否做錯了?從C中的文件解析雙重
在此先感謝
#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);
}
無關:除非*最後*''\ n''是* *最後字符的文件,你的行數將是關閉的一。相關:您剛剛將'in'發送至EOF。你認爲這會是'fscanf()' - 什麼? – WhozCraig
輸入,預期行爲,觀察到的行爲和錯誤行。 – luk32
@WhozCraig,我指望它,該文件是爲此準備的。 –