2014-04-29 34 views
0

我有以下代碼從文件讀取列表中的數字,但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); 

}

+1

無關:除非*最後*''\ n''是* *最後字符的文件,你的行數將是關閉的一。相關:您剛剛將'in'發送至EOF。你認爲這會是'fscanf()' - 什麼? – WhozCraig

+0

輸入,預期行爲,觀察到的行爲和錯誤行。 – luk32

+0

@WhozCraig,我指望它,該文件是爲此準備的。 –

回答

1

你讀整個文件來查找行數..所以在最後文件指針已經到達結尾..當你再次調用'fscanf'時,你會怎麼想呢?

您需要重置文件指針重新開始

printf("%d lines\n",lines); 
rewind(in); 
int i = 0; 
1

你已經所以,當你調用fscanf讀出指針已經在文件的結尾時讀取完全使用fgetc文件。

,您可以手動在循環前使用

fseek(in, 0, SEEK_SET); 

放置在開始讀指針。

+0

非常感謝! –