Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
Miscellaneous
C Library
cassert (assert.h)
cctype (ctype.h)
cerrno (errno.h)
cfloat (float.h)
ciso646 (iso646.h)
climits (limits.h)
clocale (locale.h)
cmath (math.h)
csetjmp (setjmp.h)
csignal (signal.h)
cstdarg (stdarg.h)
cstddef (stddef.h)
cstdio (stdio.h)
cstdlib (stdlib.h)
cstring (string.h)
ctime (time.h)
cstdio (stdio.h)
functions:
clearerr
fclose
feof
ferror
fflush
fgetc
fgetpos
fgets
fopen
fprintf
fputc
fputs
fread
freopen
fscanf
fseek
fsetpos
ftell
fwrite
getc
getchar
gets
perror
printf
putc
putchar
puts
remove
rename
rewind
scanf
setbuf
setvbuf
sprintf
sscanf
tmpfile
tmpnam
ungetc
vfprintf
vprintf
vsprintf
macro constants:
EOF
FILENAME_MAX
NULL
TMP_MAX
objects:
stderr
stdin
stdout
types:
FILE
fpos_t
size_t


fgets

function
<cstdio>
char * fgets ( char * str, int num, FILE * stream );

Get string from stream

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or a the End-of-File is reached, whichever comes first.
A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str.
A null character is automatically appended in str after the characters read to signal the end of the C string.

Parameters

str
Pointer to an array of chars where the string read is stored.
num
Maximum number of characters to be read (including the final null-character). Usually, the length of the array passed as str is used.
stream
Pointer to a FILE object that identifies the stream where characters are read from.
To read from the standard input, stdin can be used for this parameter.

Return Value

On success, the function returns the same str parameter.
If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned.
If an error occurs, a null pointer is returned.
Use either ferror or feof to check whether an error happened or the End-of-File was reached.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* fgets example */
#include <stdio.h>
int main()
{
   FILE * pFile;
   char mystring [100];
   pFile = fopen ("myfile.txt" , "r");
   if (pFile == NULL) perror ("Error opening file");
   else {
     fgets (mystring , 100 , pFile);
     puts (mystring);
     fclose (pFile);
   }
   return 0;
}


This example reads the first line of myfile.txt or the first 100 characters, whichever comes first, and prints them on the screen.

See also