Chapter Contents

Previous

Next
fgets

fgets



Read a String from a File

Portability: ISO/ANSI C conforming, UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
EXAMPLE
RELATED FUNCTIONS
SEE ALSO


SYNOPSIS

#include <stdio.h>

char *fgets(char *str, int n, FILE *f);


DESCRIPTION

fgets reads a line of data or up to n-1 characters (whichever is less) from the stream associated with the FILE object addressed by f , and it stores the input in the area addressed by str . The area must be large enough to contain n characters.

str addresses an array. For a stream accessed as text, characters are read into the array until n-1 characters have been read, a complete line of data have been read, or end of file has been reached.

For a stream accessed as binary, characters are read until a physical new-line character is encountered, n-1 characters have been read, or end of file has been reached.

fgets adds a null character ('\0') following the last character read into the area addressed by str .


RETURN VALUE

fgets returns str if successful. If end of file or an error occurs, fgets returns NULL .


EXAMPLE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFSIZE 10

main()
{
   char *buffer;
   int position;

   puts("Please enter a long line of input.");
   buffer = malloc(BUFSIZE);
   if (!buffer) exit(EXIT_FAILURE);
   *buffer = '\0';          /* Initially buffer is empty. */
   position = 0;            /* Read into start of buffer. */
   for (;;) {

         /* Read new data to last part of buffer.         */
      if (!fgets(buffer+position, BUFSIZE, stdin)) break;

         /* Stop reading if we've read the whole line.    */
      if (buffer[strlen(buffer)-1] == '\n') break;
         /* Make the buffer bigger so we can read again.  */
      buffer = realloc(buffer, strlen(buffer)+BUFSIZE);

      if (!buffer) exit(EXIT_FAILURE);
         /* Start reading after the last input character. */
      position = strlen(buffer);

   }
   if (ferror(stdin)) exit(EXIT_FAILURE);
   if (!*buffer)
      puts("There was no input data.");
   else
      printf("You entered a %d-character line:\n%s",
             strlen(buffer), buffer);
   free(buffer);
   exit(EXIT_SUCCESS);
}


RELATED FUNCTIONS

afread , gets


SEE ALSO


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.