0

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);
}
6
  • 1
    What's the file format? Check that store < 7 in your loop, and if input is NULL, not only print an error message, also exit(1). And if fscanf fails to read an int without getting an input error, its return value will be 0, so check fscanf(...) == 1. Commented Mar 20, 2013 at 23:50
  • There seems to be no guard in the for loop preventing you from overflowing line[]. What if there are more than 7 numbers in your file? Commented Mar 20, 2013 at 23:50
  • Okay thanks! 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. This help my case at all? (Also, if you know, how do I read the next line and so on?) Commented Mar 20, 2013 at 23:52
  • Oh, well there are lines of seven integers per line there but I don't know why I can't show it like that. Commented Mar 20, 2013 at 23:53
  • The commas are in the file? Then your fscanf will never manage to consume the first comma and return 0 until the programme segfaults because store is 1347 or whatever. Commented Mar 21, 2013 at 0:32

1 Answer 1

0

Change your while loop condition into:

while( store < sizeof(line)/sizeof(int) && fscanf(input, "%d", &read) != EOF)

looks like you have more numbers in the input then you have space for.

Sign up to request clarification or add additional context in comments.

1 Comment

So this will prevent my line[] from overflowing?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.