LoadNumbers() zero or more integers from textFile into pNumberArray. 0 values are skipped but a trailing zero is added to signify end of array. The input file consist of an integer optionally followed by something that is not +, - or a digit.
@ikegami pointed out that you should pass in the size of the array to avoid overflowing pNumberArray. Combine the two scanf() calls, add error handling, and just deal with the sentinel after the loop. (Not fixed) The function could alternatively return how many values are read (i) instead of using the 0 sentinel.
#include <stdio.h>
void LoadNumbers(size_t n, int pNumberArray[n], FILE *textFile) {
if(!n) return;
size_t i = 0;
while(i + 1 < n) {
int rv = fscanf(textFile,"%d%*[^0-9+-]", &pNumberArray[i]);
if(rv == EOF) break;
if(rv != 1) break; // error: no number found
if(pNumberArray[i]) i++;
}
pNumberArray[i] = 0;
}
int main(void) {
FILE *f = fopen("1.txt", "r");
if(!f) {
printf("fopen failed\n");
return 1;
}
int a[100];
LoadNumbers(sizeof a / sizeof *a, a, f);
for(int i = 0; a[i]; i++) {
printf("%d\n", a[i]);
}
}
With the example 1.txt input file:
0 a
1 b
0 charlie charlie
2 d
3 echo
4 f
0 golf
Both the original and the revised function returns:
1
2
3
4