The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.
We recommend using Visual Studio 2017

fgets, fgetws


The new home for Visual Studio documentation is Visual Studio 2017 Documentation on

The latest version of this topic can be found at fgets, fgetws.

Get a string from a stream.

char *fgets(   
   char *str,  
   int n,  
   FILE *stream   
wchar_t *fgetws(   
   wchar_t *str,  
   int n,  
   FILE *stream   


Storage location for data.

Maximum number of characters to read.

Pointer to FILE structure.

Each of these functions returns str. NULL is returned to indicate an error or an end-of-file condition. Use feof or ferror to determine whether an error occurred. If str or stream is a null pointer, or n is less than or equal to zero, this function invokes the invalid parameter handler, as described in Parameter Validation. If execution is allowed to continue, errno is set to EINVAL and the function returns NULL.

See _doserrno, errno, _sys_errlist, and _sys_nerr for more information on these, and other, error codes.

The fgets function reads a string from the input stream argument and stores it in str. fgets reads characters from the current stream position to and including the first newline character, to the end of the stream, or until the number of characters read is equal to n – 1, whichever comes first. The result stored in str is appended with a null character. The newline character, if read, is included in the string.

fgetws is a wide-character version of fgets.

fgetws reads the wide-character argument str as a multibyte-character string or a wide-character string according to whether stream is opened in text mode or binary mode, respectively. For more information about using text and binary modes in Unicode and multibyte stream-I/O, see Text and Binary Mode File I/O and Unicode Stream I/O in Text and Binary Modes.

Generic-Text Routine Mappings

TCHAR.H routine_UNICODE & _MBCS not defined_MBCS defined_UNICODE defined
FunctionRequired header
fgetws<stdio.h> or <wchar.h>

For additional compatibility information, see Compatibility in the Introduction.

// crt_fgets.c  
// This program uses fgets to display  
// a line from a file on the screen.  
#include <stdio.h>  
int main( void )  
   FILE *stream;  
   char line[100];  
   if( fopen_s( &stream, "crt_fgets.txt", "r" ) == 0 )  
      if( fgets( line, 100, stream ) == NULL)  
         printf( "fgets error\n" );  
         printf( "%s", line);  
      fclose( stream );  

Line one.  
Line two.  


Line one.  

Stream I/O
fputs, fputws
gets, _getws
puts, _putws