Read list of numbers in txt file and store to array C
Consider the following modification to your code:
#include <stdio.h>
int main(void) {
int tek;
int radica[50];
// open file
FILE *myFile = fopen("numbers.txt", "r");
// if opening file fails, print error message and exit 1
if (myFile == NULL) {
perror("Error: Failed to open file.");
return 1;
}
// read values from file until EOF is returned by fscanf
for (int i = 0; i < 50; ++i) {
// assign the read value to variable (tek), and enter it in array (radica)
if (fscanf(myFile, "%d", &tek) == 1) {
radica[i] = tek;
} else {
// if EOF is returned by fscanf, or in case of error, break loop
break;
}
}
// close file
fclose(myFile);
return 0;
}
Any number read by fscanf
will be assigned to tek
, and entered in the array radica
, until fscanf returns EOF
, at which point the loop breaks. As already mentioned, to determine when end of file is reached, it is not the variable tek
that is compared to EOF
but rather the return of fscanf
.