getc()

Reads the next character from a stream.

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

stream

A pointer to a file stream.

Remarks

The getc() function reads the next character from stream, advances the file position indicator, and returns the character as an int value. Unlike the fgetc() function, getc() is implemented as a macro.

If the file is opened in update mode (+) it cannot be read from and then written to without being repositioned using one of the file positioning functions ( fseek(), fsetpos(), or rewind()) unless the last read or write reached the end-of-file.

getc() returns the next character from the stream or returns EOF if the end-of-file has been reached or a read error has occurred.

Listing: Example of getc() Usage

#include <stdio.h>

#include <stdlib.h>

int main(void)

{

FILE *f;

char filename[80], c;

// get a filename from the user

printf("Enter a filename to read.\n");

scanf("%s", filename);

// open a file for input

if (( f = fopen(filename, "r")) == NULL) {

printf("Can't open %s.\n", filename);

exit(1);

}

// read one character at a time until end-of-file

while ( (c = getc(f)) != EOF)

putchar(c);

// close the file

fclose(f);

return 0;

}

Output

Enter a filename to read.

foofoo

0 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19

20 21 22 23 24 25 26 27 28 29

30 31 32 33 34 35 36 37 38 39

40 41 42 43 44 45 46 47 48 49

50 51 52 53 54 55 56 57 58 59

60 61 62 63 64 65 66 67 68 69

70 71 72 73 74 75 76 77 78 79

80 81 82 83 84 85 86 87 88 89

90 91 92 93 94 95 96 97 98 99