1

I have a file that contains integers separated with ' '

Example File1

8 7 8 8 7 7 7

Example file2

10 0 3 11 0 2 3 3 2 4 5 6 2 11

I want to read these integers and save them in an integer array.

   -->int array[for example File1]={8,7,8,8,7,7,7}
   -->int array[for example File2]={10,0,3,11,0,2,3,3,2,4,5,6,2,11}

I have done this code so far... Can anyone help here?

#include <stdio.h>
int main() {
  FILE *f1;
  int i,counter=0;
  char ch;
  f1 = fopen("C:\\Numbers.txt","r");

  while((ch = fgetc(f1))!=EOF){if(ch==' '){counter++; }}
  int arMain[counter+1];

  for(i=0; i<counter+1; i++) {
     fscanf(f1, "%d", &arMain[i]);
  }

  for(i = 0; i <= counter+1; i++) {
    printf("\n%d",arMain[i]);
  }

  return 0;
}
savram
  • 500
  • 4
  • 18
Nakos Kotsanis
  • 180
  • 1
  • 15
  • You need [rewind](http://en.cppreference.com/w/c/io/rewind). and `<=` --> `<`, `char` -->. `int`. – BLUEPIXY Oct 25 '17 at 14:49
  • And you need to format your C code correctly. For example like the samples in your C text book. – Jabberwocky Oct 25 '17 at 14:50
  • @BLUEPIXY when u saying char --> int u mean the line char ch; (thats the only line that contains char) Thanks – Nakos Kotsanis Oct 25 '17 at 14:58
  • 1
    BTW to count the numbers without counting bytes, use something like this: `int dummy; while (fscanf(f1, "%d", &dummy) == 1) counter++;` - this code checks the return code from `fscanf`, which will be 1 after successfully reading a number. This will remove spaces automatically, isn't prone to [the `EOF` bug](https://stackoverflow.com/a/8858073/509868), and handles double-digit numbers correctly. – anatolyg Oct 25 '17 at 15:01
  • ^This! Because it counts the elements in the same way that they are read in. Counting spaces in between can only be an estimation; it fails if other kinds of white space are used to separate the data or if there is more than one space character between values. And it gets rid of the silly notation that the actual count of numbers is `count + 1` in the program. – M Oehm Oct 25 '17 at 15:05

1 Answers1

1

Each time you read something from a file, the pointer moves one position. After you've read the file once to count the number of integers, the pointer is pointing to the end of the file.

You have to rewind your FILE pointer, so it goes back to the start and you can scan again to get the numbers.

#include <stdio.h>

int main(){
    FILE *f1;
    int i,counter=0;
    char ch;
    f1 = fopen("nums.txt","r");

    while((ch = fgetc(f1))!=EOF){if(ch==' '){counter++; }}
    int arMain[counter+1];

    rewind(f1); /* Rewind f1 */
    for(i=0; i<counter+1; i++)         {
        fscanf(f1, "%d", &arMain[i]);       
    }

    for(i = 0; i <= counter+1; i++)     {
        printf("\n%d",arMain[i]);       
    }

    return 0;

}
klaus
  • 1,187
  • 2
  • 9
  • 19