简体   繁体   中英

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/

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!

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.

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.

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

You should check

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

before

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM