-1
FILE * file = fopen( “in.txt”, “r” );
char line[80];
if( NULL != file ) {
    fgets( line, 40, file );
    fclose( file );
}

Is there anything dangerous in the above code, what i saw here was it got the maximum length 40 string to the buffer line then close the file.

Thai
  • 3
  • 1
  • 3
    no there isn't, why are you thinking that it is dangerous? – Jean-François Fabre Apr 16 '18 at 18:55
  • You mean gets? fgets() is safer if you compare with gets() – danglingpointer Apr 16 '18 at 19:00
  • Are you sure that you understand `fgets()`? Did you read `fgets()` [Manual](https://linux.die.net/man/3/fgets)? What exactly is `40` in your `fgets()`call? – Michi Apr 16 '18 at 19:02
  • @Jean-FrançoisFabre oh okay, it's just a question from a review and i want to make sure if i miss sth or not. – Thai Apr 16 '18 at 19:03
  • @Michi keep calm, i just want to make sure, 40 is just 40, that's the point of the question, whether the size used in fgets less than the buffer size. – Thai Apr 16 '18 at 19:06
  • 4
    For `fgets`, in your example, unless you have a _special_ reason not to, the idiomatic [recommended] call is: `fgets(line,sizeof(line),file)`. Using a shorter length is okay [just wasteful]. Using a longer length is undefined behavior [and will probably segfault] – Craig Estey Apr 16 '18 at 19:06
  • @CraigEstey ah okay, i got it now, tysm. – Thai Apr 16 '18 at 19:14
  • @CraigEstey it segfaults only if some line is longer than the buffer length. – Jean-François Fabre Apr 16 '18 at 19:17
  • the posted code does not compile! it is missing the needed #include statement for the needed header file. When asking a question about a run time problem, as this question is doing, always post a [mcve]. – user3629249 Apr 17 '18 at 05:36
  • @Jean-FrançoisFabre, Having a line in the file that is longer than the length given to `fgets()` will NOT cause a seg fault event. – user3629249 Apr 17 '18 at 05:38

1 Answers1

0

You may be confusing fgets() and gets(). See Why is the gets function so dangerous that it should not be used?

As long as the size param matches the buffer size, fgets is safe. In your case it would be normal to do fgets( line, sizeof(line), file ); Note: fgets() reads at most 1 less than "size" and always 0 terminates.

John3136
  • 28,809
  • 4
  • 51
  • 69