oldbutnew
oldbutnew

Reputation: 145

If file doesn't exist, program fails in C

This used to work. I don't know what I did to make it stop working but when I enter a file name that does not exist, I get a segment violation error and the program quits.

int main()
{
    File *fr;
    char input_file[32];
    int num_lines, valid;

    do{
        printf("\nEnter the name of the input file: ");
        scanf("%s", input_file);
        fr = fopen(input_file, "r");
        if(fr == NULL){
            valid = 0;
            printf("File does not exist...");
        }
        if(fr != NULL){
            fscanf(fr, "%d", &num_lines);
            numbers = malloc(sizeof(int) * num_lines);
            for(i=0;i<num_lines;i++){
                fscanf(fr, "%[^0123456789]%d", numbers+i);
                printf("%d\n", numbers[i]);
                valid =1;
            }
            free(numbers);
            fclose(fr);
        }

    }while(valid == 0);
}

/edited/

Upvotes: 0

Views: 3015

Answers (5)

templatetypedef
templatetypedef

Reputation: 372784

Notice the following:

fr = fopen(input_file, "r");
fscanf(fr, "%d", &num_lines);
if(fr == NULL){

Here, you're passing the result from fopen directly into fscanf without first testing whether or not the file was opened successfully. If the file can't be opened, fr will be NULL, hence the segmentation fault.

Try reordering the code so that you don't do the fscanf until you've confirmed that fr != NULL. For example:

fr = fopen(input_file, "r");
if(fr != NULL){
    fscanf(fr, "%d", &num_lines);

Hope this helps!

Upvotes: 3

Jarosław Gomułka
Jarosław Gomułka

Reputation: 4995

You should check

if(fr == NULL){
   valid = 0;
   printf("File does not exist...");
}   

before

fscanf(fr, "%d", &num_lines);

Upvotes: 1

Marcos
Marcos

Reputation: 4643

You must check if fr is NULL before call fscanf(fr, "%d", &num_lines) And change the first scanf: scanf("%s", input_file);

Upvotes: 1

thezboe
thezboe

Reputation: 552

You must've moved the fscanf call to before checking if fr==NULL. You need to move the fscanf to after the fr==null check.

Upvotes: 1

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

Well, this line is very, very wrong:

    scanf("%s", input_file[32]);

The second argument ought to be a pointer to a character buffer, but you're passing a character value, which could point to any random location. It might seemingly work OK, but it will corrupt some random spot in memory that you may need for some reason!

Then you go on to pass the result of calling fopen() directly to fscanf() without checking first to see if it's null; that's not going to work out too well either.

Upvotes: 3

Related Questions