Your Browser is not longer supported

Please use Google Chrome, Mozilla Firefox or Microsoft Edge to view the page correctly
Loading...

{{viewport.spaceProperty.prod}}

getc - Read a character from a file

&pagelevel(4)&pagelevel

Definition  

#include <stdio.h>

int getc(FILE *fp);

getc reads a character from the file with file pointer fp from the current read/write position.

Return val.

Character read as a positive integer value


if successful.

EOF

in case of an error or end of file.

Notes

getc is implemented both as a macro and as a function (see section “Functions and macros”).

The call getc(stdin) is identical to getchar().

If you use a comparison such as while((c = getc(fp)) != EOF)
in your program, the variable c must always be declared as an integer. If you define c as a char, the EOF condition is never satisfied for the following reason: -1 is converted to char0xFF’ (i.e. +255); EOF, however, is defined as -1.

If getc is reading from the standard input stdin, and EOF is the end criterion for reading,
you can satisfy the EOF condition by means of the following actions at the terminal:
pressing the K2 key and entering the system commands EOF and RESUME-PROGRAM.

The following applies in the case of text files with SAM access mode and variable record length for which a maximum record length is also specified: When the specification split=no was entered for fopen, records of maximum record length are not concatenated with the subsequent record when they are read. By default or with the specification split=yes, when a record with maximum record length is read, it is assumed that the following record is the continuation of this record and the records are concatenated.

For text files with access mode SAM or ISAM, getc returns an additional newline character at the end of a sentence. In this case, a subsequent call to _fnlinserted returns a value other than 0. In all other cases, a subsequent call to _fnlinserted returns the value 0.

Example

The following program reads a file with file pointer fp one character at a time until end of file
is reached. The read characters are stored in the area buf.

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  int c, i = 0;
  char buf[BUFSIZ];
  FILE *fp;
  char name[40];
  printf("Please enter file to be read\n");
  scanf("%s", name);
  if(( fp = fopen(name, "r")) == NULL)
    {
    perror("fopen");  /* Abort with error message 'fopen' if */
    exit(1);          /* file does not exist                 */
    }
  while (( c = getc(fp)) != EOF )
    buf[i++] = c;
  puts(buf);
  fclose(fp);
  return 0;
}

See also

fgetc, getchar, getwc, ungetc, fopen, fopen64, _fnlinserted