Read list of numbers in txt file and save array in C

I have a list of integers, one number per line, and would like to store each of those numbers in an array with an integer to be used later in the program.

For example, in java, you would do something like this:

FileReader file = new FileReader("Integers.txt");
int[] integers = new int [100];
int i=0;
while(input.hasNext())
{
   integers[i] = input.nextInt();
   i++;
}
input.close();

      

How do I do this in C?

+3


source to share


2 answers


Give it back. You will be much better off if you read the man pages for each of these functions (fopen (), scanf (), fclose ()) and how to allocate arrays in C. You should add error checking to this as well. For example, what happens if Integers.txt doesn't exist or you don't have read permissions? What if the text file contains more than 100 numbers?



    FILE *file = fopen("Integers.txt", "r");
    int integers[100];

    int i=0;
    int num;
    while(fscanf(file, "%d", &num) > 0) {
        integers[i] = num;
        i++;
    }
    fclose(file);

      

+6


source


#include <stdio.h>

int main (int argc, char *argv[]) {
  FILE *fp;
  int integers[100];
  int value;
  int i = -1; /* EDIT have i start at -1 :) */

  if ((fp = fopen ("Integers.txt", "r")) == NULL)
    return 1;

  while (!feof (fp) && fscanf (fp, "%d", &value) && i++ < 100 )
    integers[i] = value;

  fclose (fp);

  return 0;
}

      



+1


source







All Articles