0

I created a file with content: '12 7 -14 3 -8 10'

I want to output all numbers of type integer. But after compiling and running the program, I get only the first number '12'

Here's my code:

#include <stdio.h>

main(){
    FILE *f;
    int x;
    f=fopen("C:\\Users\\emachines\\Desktop\\ind\\in.txt", "r");
    fscanf(f, "%d", &x);
    printf("Numbers: %d", x);
    fclose(f);
}

What am I doing wrong?

Undo
  • 25,519
  • 37
  • 106
  • 129

1 Answers1

2

You scan one integer from the file using fscanf and print it.You need a loop to get all the integers.fscanf returns the number of input items successfully matched and assigned.In your case,fscanf returns 1 on successful scanning. So just read integers from the file until fscanf returns 0 like this:

#include <stdio.h>

int main() // Use int main
{
  FILE *f;
  int x;

  f=fopen("C:\\Users\\emachines\\Desktop\\ind\\in.txt", "r");

  if(f==NULL)  //If file failed to open
  {
      printf("Opening the file failed.Exiting...");
      return -1;
  }

  printf("Numbers are:");
  while(fscanf(f, "%d", &x)==1)
  printf("%d ", x);

  fclose(f);
  return(0); //main returns int
}
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • Thanks! you used `while(fscanf(f, "%d", &x)==1)`, so I want to ask. Is `while(fscanf(f, "%d", &x)==1)` equivalent to `while(!feof(f))`, or not? – Personal Jesus Nov 08 '14 at 14:01
  • Nope.[`while(!feof(f))` is wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong). – Spikatrix Nov 08 '14 at 14:43