I have a list of integers, one number per line and would like to store each of these numbers in an integer array to use later in the program.
For example in java you
#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;
}
Give this a go. You'll 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 also add error checking to this. For example, what happens if Integers.txt does not exist or you don't have permissions to read from it? What about 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);