fgets() — Read a String

Format

#include <stdio.h>
char *fgets (char *string, int n, FILE *stream);

Language Level

ANSI

Threadsafe

Yes

Description

The fgets() function reads characters from the current stream position up to and including the first new-line character (\n), up to the end of the stream, or until the number of characters read is equal to n-1, whichever comes first. The fgets() function stores the result in string and adds a null character (\0) to the end of the string. The string includes the new-line character, if read. If n is equal to 1, the string is empty.

Return Value

The fgets() function returns a pointer to the string buffer if successful. A NULL return value indicates an error or an end-of-file condition. Use the feof() or ferror() functions to determine whether the NULL value indicates an error or the end of the file. In either case, the value of the string is unchanged.

The fgets() function is not supported for files that are opened with type=record.

The value of errno can be set to:
Value
Meaning
EBADF
The file pointer or descriptor is not valid.
ECONVERT
A conversion error occurred.
ENOTREAD
The file is not open for read operations.
EGETANDPUT
An read operation that was not allowed occurred after a write operation.
ERECIO
The file is open for record I/O.
ESTDIN
stdin cannot be opened.
EIOERROR
A non-recoverable I/O error occurred.
EIORECERR
A recoverable I/O error occurred.

Example

This example gets a line of input from a data stream. The example reads no more than MAX_LEN - 1 characters, or up to a new-line character from the stream.
#include <stdio.h>
 
#define  MAX_LEN  100
 
int main(void)
{
   FILE *stream;
   char line[MAX_LEN], *result;
 
   stream = fopen("mylib/myfile","rb");
 
   if ((result = fgets(line,MAX_LEN,stream)) != NULL)
      printf("The string is %s\n", result);
 
   if (fclose(stream))
      perror("fclose error");
}