Reading a file using fgets and printing its content on screen

这一生的挚爱 提交于 2019-12-10 11:15:14

问题


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.

I also looked at this and this but got no help.


回答1:


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");



回答2:


Couple of things in addition to cnicutar's answer:

#include <stdio.h>
        ^ Please make sure you have a space between your includes and the headers

fgets will read until it's encountered a new line or EOF (whichever comes first), so to read the whole file you'd have to do it in a loop.

I would recommend doing it like this (no need for the pointer assignment as pointed out):

while(fgets(line, MAX_LENGTH, fp))
    printf("%s", line);


来源:https://stackoverflow.com/questions/18532322/reading-a-file-using-fgets-and-printing-its-content-on-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!