gtpc2m2g | C/C++ Language Support User's Guide |
This function reads a character.
Format
#include <stdio.h> int fgetc(FILE *stream);
This function reads a single-byte unsigned character from the input stream pointed to by stream at the current position and increases the associated file pointer so that it points to the next character.
The getc function has the same restriction as any read operation for a read immediately following a write or a write immediately following a read. Between a read and a subsequent write, there must be an intervening reposition unless an end-of-file (EOF) has been reached.
Normal Return
If successful, the fgetc function returns the character that was read as an integer.
Error Return
An EOF return value indicates an error or an EOF condition. Use the feof or ferror function to determine if the EOF value indicates an error or the end of the file. Note that EOF is only reached when an attempt is made to read past the last byte of data. Reading up to and including the last byte of data does not turn on the EOF indicator.
Programming Considerations
None.
Examples
The following example gathers a line of input from a stream and tests to see if the file can be opened. If the file cannot be opened, the function perror is called.
#include <stdio.h> #define MAX_LEN 80 int main(void) { FILE *stream; char buffer[MAX_LEN + 1]; int i, ch; if ((stream = fopen("myfile.dat","r")) != NULL) { for (i = 0; (i < (sizeof(buffer)-1) && ((ch = fgetc(stream)) != EOF) && (ch != '\n')); i++) printf("character is %d\n",ch); buffer[i] = ch; buffer[i] = '\0'; if (fclose(stream)) perror("fclose error"); } else perror("fopen error"); }
Related Information
See Appendix E, Programming Support for the TPF File System for more information about TPF File System C Functions.