Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22037

I get a segmentation fault when trying to read a file

$
0
0

I've looked up on how to use fgets function and hence I wrote this code:

#include <stdio.h>

void main(int argc, char** argv)
{
    if (argc == 2)
    {
       FILE* file = fopen(argv[1], "r");

       if (file != NULL)
       {
           char line[100];
           while (fgets(line, sizeof(line), file))
           {
               printf("%s", line);
           }
       }
    }
}

I compile the program with:

gcc main.c

And run it with:

./a.out textdoc.txt

The file textdoc.txt has some jibberish lines (it is not empty):

ageagea gea g
geagae g g g g
eagae ge g ga a a fea
gea hr hr a faw

What I've noticed is that when I reach the fgets() line of code, I get a segmentation fault.

Can anyone tell me what is the issue?


Viewing all articles
Browse latest Browse all 22037

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>