Segmentation Error in C program caused by file pointer

66 Views Asked by At

I am fairly new to C programming and trying to properly understand the ins and outs of memory management in C.

I made a simple program that would compile without any issues but whilst debugging gives me a segmentation error after the line printf("The next line gives a segmentation error");

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>      // Here you have the isdigit macro

int main()
{
    FILE *filePtr; 
    char fileStr[150];      // Buffer for reading file.

    filePtr = fopen("ManyRandomNumbersLog.txt", "r");
    
    printf("\n\nNow reading the file:\n");

    while (!feof(filePtr))
    {
        printf("The next line is a segmentation fault!\n");
        // WHYYYY?!?!?!?
        fgets(fileStr, 150, filePtr);
        printf("%s\n", fileStr);
    }

    return 0;
}

The fgets function call seems to be giving this error since the pointer has the following "error?" inside it:

file pointer error

Do you know what is the problem and how to prevent it?

I tried debugging it but could not figure out why the pointer cannot access that memory.

2

There are 2 best solutions below

0
0___________ On BEST ANSWER

Always check if the file has been opened successfully. Also feof does not work the way you think.

int main()
{
    FILE* filePtr; 
    char fileStr[150];      // Buffer for reading file.

    filePtr = fopen("ManyRandomNumbersLog.txt","r");
    
    if(filePtr)
    {
        printf("\n\nNow reading the file:\n");
        while(fgets(fileStr, 150, filePtr))
        {
            printf("%s\n",fileStr);  
            //filestr will also contain '\n' at the end if it was present in the file.
        }
        fclose(filePtr);
    }

    return 0;
}

PS do not look inside the FILE structure as it will not give you nay valuable information.

2
chqrlie On

You should always check for a potential failure of fopen() and report it with meaningful information:

#include <errno.h>
#include <stdio.h>
#include <string.h>

int main()
{
    FILE *filePtr = fopen("ManyRandomNumbersLog.txt", "r");
    if (filePtr == NULL) {
        fprintf(stderr, "cannot open file %s: %s\n", 
                "ManyRandomNumbersLog.txt", strerror(errno));
        return 1;
    }
    
    printf("\n\nNow reading the file:\n");

    char fileStr[150];      // Buffer for reading file.

    // Do not use feof() for this loop:
    //    just try and read a line and stop upon failure to do so.
    while (fgets(fileStr, 150, filePtr)) {
        printf("%s\n", fileStr);
    }
    fclose(filePtr);

    return 0;
}