6.18.17 fgets Function

Get a string from a stream.

Attention: This function is not implemented by MPLAB XC8.

Include

<stdio.h>

Prototype

char * fgets(char * s, int n, FILE * stream);

Arguments

s
pointer to the storage string
n
maximum number of characters to read
stream
pointer to the open stream

Return Value

Returns a pointer to the string s if successful; otherwise, returns a null pointer.

Remarks

The function reads characters from the input stream and stores them into the string pointed to by s until it has read n-1 characters, stores a newline character or sets the end-of-file or error indicators. If any characters were stored, a null character is stored immediately after the last read character in the next element of the array. If fgets sets the error indicator, the array contents are indeterminate.

Example

See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

#include <stdio.h>

#define MAX 50

int main(void)
{
  FILE *buf;
  char s[MAX];

  if ((buf = fopen("afile.txt", "r")) == NULL)
    printf("Cannot open afile.txt\n");
  else
  {
    while (fgets(s, MAX, buf) != NULL)
      printf("%s|", s);
    fclose(buf);
  }
}

Example Input

Contents of afile.txt (used as input):

Short
Longer string

Example Output

Short
|Longer string
|