Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C |
both |
#include <stdio.h>
int fgetc(FILE *stream);
#define _OPEN_SYS_UNLOCKED_EXT 1
#include <stdio.h>
int fgetc_unlocked(FILE *stream);
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 fgetc() function is not supported for files opened with type=record or type=blocked.
fgetc() has the same restriction as any read operation for a read immediately following a write or a write immediately following a read. Between a write and a subsequent read, there must be an intervening flush or reposition. Between a read and a subsequent write, there must also be an intervening flush or reposition unless an EOF has been reached.
fgetc_unlocked() is functionally equivalent to fgetc() with the exception that it is not thread-safe. This function can safely be used in a multithreaded application if and only if it is called while the invoking thread owns the (FILE*) object, as is the case after a successful call to either the flockfile() or ftrylockfile() function.
If successful, fgetc() returns the character read as an integer.
⁄* CELEBF16
This example gathers a line of input from a stream.
It tests to see if the file can be opened.
If the file cannot be opened &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");
}