Continuing from the comment, you want to consume an entire line of input with each read, then parse the first integer from the line into your array. Using fgets()
to read each line into a buffer and then parse with sscanf
is a simple solution, e.g.
#include <stdio.h>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
#define MAXI 256
int main (int argc, char **argv) {
char buf[MAXC];
int array[MAXI], n = 0;
/* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}
while (n < MAXI && fgets (buf, MAXC, fp)) /* read each line into buf */
if (sscanf (buf, "%d", &array[n]) == 1) /* parse 1st int from buf to array */
n++; /* increment counter */
if (fp != stdin) /* close file if not stdin */
fclose (fp);
for (int i = 0; i < n; i++)
printf ("array[%2d] : %d\n", i, array[i]);
}
Example Input File
$ cat dat/arr_1st_num.txt
120 test 123
101 test1 132
126 test2 140
150 test3 150
(note: blank lines or lines not beginning with an integer value are simply read and discarded and do not impact your read and storage of data)
Example Use/Output
$ ./bin/array_1st_num dat/arr_1st_num.txt
array[ 0] : 120
array[ 1] : 101
array[ 2] : 126
array[ 3] : 150
Look things over and let me know if you have further questions.