fgetc() — Read a Character

Format

#include <stdio.h>
int fgetc(FILE *stream);

Language Level: ANSI

Threadsafe: Yes.

Description

The fgetc() function reads a single unsigned character from the input stream at the current position and increases the associated file pointer, if any, so that it points to the next character.

Note:
The fgetc()function is identical to getc(), but it is always defined as a function call; it is never replaced by a macro.

Return Value

The fgetc() function returns the character that is read as an integer. An EOF return value indicates an error or an end-of-file condition. Use the feof() or the ferror() function to determine whether the EOF value indicates an error or the end of the file.

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.

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

Example that uses fgetc()

This example gathers a line of input from a stream.

#include <stdio.h>
 
#define  MAX_LEN  80
 
int main(void)
{
   FILE *stream;
   char buffer[MAX_LEN + 1];
   int i, ch;
 
   stream = fopen("mylib/myfile","r");
 
   for (i = 0; (i < (sizeof(buffer)-1) &&
         ((ch = fgetc(stream)) != EOF) && (ch != '\n')); i++)
      buffer[i] = ch;
 
   buffer[i] = '\0';
 
   if (fclose(stream))
      perror("fclose error");
 
   printf("line: %s\n", buffer);
}
 
 /***********************************************************************
      If FILENAME contains:  one two three
      The output should be:
      line: one two three
   ************************************************************************/

Related Information



[ Top of Page | Previous Page | Next Page | Contents | Index ]