Anyone got anything about reading a sequential number from text file per line and parsing it to an array in C?
What I have in a file:
12 3 45 6 7 8
3
What I would do is to make a function like this:
size_t read_em(FILE *f, int **a);
In the function, allocate some memory to the pointer *a
, then start reading numbers from the f
and storing them in *a
. When you encounter a newline character, simply return the number of elements you've stored in *a
. Then, call it like this:
int *a = NULL;
FILE *f = fopen("Somefile.txt", "r");
size_t len = read_em(f, &a);
// now a is an array, and len is the number of elements in that array
Useful functions:
malloc()
ed arrayfgets()
) into other variables (such as an int
array created by malloc()
- hint hint)