I have the following code to read tabulated numbers from a file, but fscanf returns with -1. Whar am I doing wrong?

Thanks in advance

#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);

}

有帮助吗?

解决方案

You read entire file to find the number of lines..so at the end file pointer has reached the end.. What do you think happens when you call 'fscanf' again ??

You need to reset your file pointer to start again

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

其他提示

You already read the file completely using fgetc so by the time you call fscanf the reading pointer is already at the end of the file.

You can manually place the read pointer at the beginning by using

fseek(in, 0, SEEK_SET);

in front of your loop.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top