Reading a file using fgets and printing its content on screen
Try some parentheses:
if((result=fgets(line,MAX_LENGTH,fp)) != NULL)
^ ^
Without those you'll store the result of the comparison instead of a pointer to the string.
Side note: you don't need result
at all. When it succeeds, fgets
returns the pointer you passed in; in other words you can just printf line
:
if(fgets(line, MAX_LENGTH, fp))
printf("The string is %s \n", line);
Second side note: before trying to fgets from the file, you should check whether fopen
succeeded:
if (!fp)
perror("fopen");
shailendra
Trying to learn more of C,C++ and perl and LINUX.Interested in learning server side coding, and AI also.
Updated on June 04, 2022Comments
-
shailendra almost 2 years
I still consider myself as a new webby in C.I am trying to read a file in, file is not binary but its size varies from small size of feb kbs to big size files of feb Mbs.I am using fgets function, i had taken reference from this link but after compilation, i am getting segmentation fault.i tried to debug it with gdb and found that i am able to open file but unable to read.Here is my code.
#include<stdio.h> #define MAX_LENGTH 1048576 int main() { FILE *fp; char *result; char line[MAX_LENGTH]; fp =fopen("/home/shailendra/sampleprograms/C/shail1.txt","r"); if(result=fgets(line,MAX_LENGTH,fp) != NULL) printf("The string is %s \n",result); else printf("Error opening the file"); if(fclose(fp)) printf("fclose error"); }
This Segmentation fault really sucks your blood.I understand that it is due to insufficient memory allocation but i had used MAX_LENGTH 1048576, so i don't think that it must create any problem.I had tried it with both small files with only one line and a big file with multiple lines but i am unable to figure out why i am getting segmentation fault.