Deepak
Deepak

Reputation: 1545

correct use of fgets?

In this program I am getting segmentation fault due to line:

fgets( string , 50, in );  

If I comment it out the program exits fine but I am not sure what I am doing wrong with it? I checked the declaration of function fgets which seems fine for the program.

//char *fgets(char *str, int n, FILE *stream)


#include <stdio.h>

int main(int argc, char const *argv[])
{
  FILE *in;
  char string[100];

  in = fopen("in.txt", "r" );

  // if i remove this line segmentation fault is no more.
  fgets( string , 50, in );  

  fclose(in);

  return 0;
}

Upvotes: 0

Views: 251

Answers (1)

user376507
user376507

Reputation: 2066

fopen() might not have been successful, check the return value of that before you try to read.

Upvotes: 2

Related Questions