COHERENT manpages

This page displays the COHERENT manpage for fgets() [Read line from stream].

List of available manpages
Index


fgets() -- STDIO Function (libc)

Read line from stream
#include <stdio.h>
char *fgets(s, n, fp)
char *s; int n; FILE *fp;

fgets() reads characters from the stream  fp into string s until either n-1
characters have been read, or a  newline or EOF is encountered.  It retains
the newline,  if any,  and appends a  null character at  the end of  of the
string.  fgets()  returns the argument  s if any characters  were read, and
NULL if none were read.

Example

This example looks for the pattern given by argv[1] in standard input or in
file  argv[2].  It  demonstrates  the  functions  pnmatch(),  fgets(),  and
freopen().

#include <stdio.h>
#define MAXLINE 128
char buf[MAXLINE];

void fatal(s) char *s;
{
    fprintf(stderr, "pnmatch: %s\n", s);
    exit(1);
}

main(argc, argv)
int argc; char *argv[];
{
    if (argc != 2 && argc != 3)
        fatal("Usage: pnmatch pattern [ file ]");

    if (argc==3 && freopen(argv[2], "r", stdin)==NULL)
        fatal("cannot open input file");

    while (fgets(buf, MAXLINE, stdin) != NULL) {
        if (pnmatch(buf, argv[1], 1))
            printf("%s", buf);
    }

    if (!feof(stdin))
        fatal("read error");
    exit(0);
}

See Also

fgetc(),
gets(),
libc
ANSI Standard, §7.9.7.2
POSIX Standard, §8.1

Diagnostics

fgets()  returns NULL  if an  error occurs,  or if EOF  is seen  before any
characters are read.