So this is my code and I keep getting segmentation faults. How can I format this code to read a set of numbers from a file?
My input looks like this: 82, 46, 71, 56, 44, 12, 100 62, 67, 64, 65, 62, 39, 68 68, 90, 78, 57, 76, 45, 82 etc
#include <stdio.h>
int main ()
{
FILE *input = fopen("input.txt", "r");
int line[7];
int store = 0, read;
if(!input)
{
printf("Error: Filename \"input.txt\" not found!\n");
}
store = 0;
while(fscanf(input, "%d", &read) != EOF)
{
line[store] = read;
store++;
}
printf("%d %d %d %d %d %d %d\n", line[0], line[1], line[2], line[3], line[4], line[5], line[6]);
return(0);
}
store < 7in your loop, and ifinputisNULL, not only print an error message, alsoexit(1). And iffscanffails to read anintwithout getting an input error, its return value will be 0, so checkfscanf(...) == 1.fscanfwill never manage to consume the first comma and return 0 until the programme segfaults becausestoreis 1347 or whatever.