Home > Net >  C fscanf giving Segmentation Fault. Says missing file (my file is named lab4.dat and is in the same
C fscanf giving Segmentation Fault. Says missing file (my file is named lab4.dat and is in the same

Time:10-22

It segfaults at my fscanf within my While loop. Says that the file doesn't exist when it clearly does, has data in it, and is in the same location as the .c file. Any help is greatly appreciated!

#include <stdio.h>
#include <stdlib.h>

#define IN_FILE_NAME "lab4.dat"
#define OUT_FILE_NAME "lab4.txt"

int main(void)
{
    double h, s1, s2, area;
    FILE * infile;
    FILE * outfile;

    infile = fopen("lab4.dat" , "r");
    if (infile = NULL){
        printf("Error on fopen input file\n");
        exit (EXIT_FAILURE);
    }

    outfile = fopen("lab4.txt", "w");
    if (outfile = NULL){
        printf("Error on fopen output file\n");
        exit (EXIT_FAILURE);
    }


    while ((fscanf(infile, "%lf%lf%lf", &h, &s1, &s2)) == 3)
    {
        area = 0.5 * h * (s1   s2);
        fprintf(outfile, "%7.2f    %7.2f    %7.2f    .3f", h, s1, s2, area);
    }

    fprintf(outfile, "\nTyler Rice.  Lab 4. \n\n");
    fprintf(outfile, "Area of Trapezoid \n\n");
    fprintf(outfile, " Height      Side1       Side2         Area   \n");
    fprintf(outfile, "--------   ---------   ---------   ---------- \n");
    fprintf(outfile, "\n\n");

    fclose(infile);
    fclose(outfile);

    return EXIT_SUCCESS;

/*---------------------------------------------------*/
}

CodePudding user response:

In your if condition, you are using the assignment operator = to check for equality. Which is wrong. You should use the == operator to compare values.

By the time you reach fscanf, your infile is already NULL.

CodePudding user response:

As @babon posted, the answer here is using assignment (=) rather than an equality test (==).

The problem is that the assignment in the if is perfectly legal code in C, so it compiles without issue. One solution recommended in the comments is to turn on warnings when compiling. This is crucial. Errors stop your code from compiling, but warnings hint at run-time errors just waiting to happen.

In addition to paying attention to warnings, you can reverse the terms in your conditions.

This compiles:

if (infile = NULL) {
}

This does not compile:

if (NULL = infile) {
}

But this does:

if (NULL == infile) {
}
  • Related