简体   繁体   中英

How to read integers from .txt file and store them in a integer type array in C

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;
}

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM