Does fgets naturally set trailing zero in C?

struct DVDInfo  *ReadStruct( void ) {
    struct DVDInfo  *infoPtr;
    int             num;
    char            line[ kMaxLineLength ];
    char            *result;

    infoPtr = malloc( sizeof( struct DVDInfo ) );

    if ( NULL == infoPtr ) {
        printf( "Out of memory!!!  Goodbye!\n" );
        exit( 0 );
    }

    printf( "Enter DVD Title:  " );
    result = fgets( line, kMaxLineLength, stdin );
    line[ strlen( line ) - 1 ] = '\0';
    infoPtr->title = MallocAndCopy( line );

    printf( "Enter DVD comment:  " );
    result = fgets( line, kMaxLineLength, stdin );
    line[ strlen( line ) - 1 ] = '\0';
    infoPtr->comment = MallocAndCopy( line );

    do {
        printf( "Enter DVD Rating (1-10):  " );
        scanf( "%d", &num );
        Flush();
    }
    while ( ( num < 1 ) || ( num > 10 ) );

    infoPtr->rating = num;

    printf( "\n----------\n" );

    return( infoPtr );
}

I asked another question about this code in another thread in stackoverflow, but did not want to double it - why does the zero end at the end of these files read by fgets end? fgets adds trailing zero anyway, is this not redundant?

+5
source share
5 answers

fgets writes nul terminator to the buffer you specify (if you specify a buffer size greater than 0). Otherwise, you could not call strlen () on it, strlen () expects a string, and if it is not nul completed, it is not a string.

You ask about

line[ strlen( line ) - 1 ] = '\0';

line. , , a\n nul-.

, fgets , . line "Hello\n" (\n - escape- , 1 , 2)

strlen ( "Hello\n" ) 6, 6-1 - 5, 5. 0

"Hello\n"
      ^
      |
      Add 0 terminator

: ""

:

  • [strlen () - 1] = '\ 0'; , [-1].
  • , fgets. line, fgets , .
  • , , . , , , kMaxLineLength , , "" \n, strlen () -1 \n ( ).
+2

result = fgets( line, kMaxLineLength, stdin );

- Ok, kMaxLineLength.

fgets size stream ...

+1

line[ strlen( line ) - 1 ] = '\0'; ( insecurity — strlen() , ). fgets() nul- . , , line, , result != NULL. fgets() NULL .

+1
source

Yes, it's overkill.

One suggestion to make it more reliable against the code gene ... change

result = fgets( line, kMaxLineLength, stdin );

to

result = fgets( line, sizeof(line), stdin );
+1
source

All Articles