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:
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.
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.