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
Use strtol()
to parse each line:
#include
#include
#include
int main(void)
{
static char buffer[1024];
static long values[256];
while(fgets(buffer, sizeof buffer, stdin))
{
char *current = buffer;
size_t i = 0;
while(*current && *current != '\n' &&
i < sizeof values / sizeof *values)
{
char *tail = NULL;
errno = 0;
values[i] = strtol(current, &tail, 0);
if(errno || tail == current)
{
fprintf(stderr, "failed to parse %s\n", current);
break;
}
++i, current = tail;
}
// process values
printf("read %i values\n", i);
}
}