...
The character I/O functions fgetc(), getc(), and getchar() all read a character from a stream and return it as an int. If the stream is at the end of the file, the end-of-file indicator for the stream is set and the function returns EOF. If a read error occurs, the error indicator for the stream is set and the function returns EOF. If these functions succeed, they cast the character returned into an unsigned char. Because EOF is negative, it should not match any unsigned character value. However, this is only true for platforms where the int datatype has more precision bits than char. On a platform where int and char have the same precision, a character-reading function could return EOF because it matched the value of the last character readread a valid character that had the same bit-pattern as EOF. The C Standard requires only that an int type be able to represent a maximum value of +32767 and that a char type be no larger than an int. Although uncommon, this situation can result in the integer constant expression EOF being indistinguishable from a normal character; that is, (int)(unsigned char)65535 == -1. Consequently, failing to use feof() and ferror() to detect end-of-file and file errors can result in incorrectly identifying the EOF character on rare implementations where sizeof(int) == sizeof(char).
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stddef.h>
#include <stdio.h>
#include <wchar.h>
void g(void) {
enum { BUFFER_SIZE = 32 };
assert(PRECISION(WCHAR_MAX) < PRECISION(WINT_MAX));
wchar_t buf[BUFFER_SIZE];
wint_t wc;
size_t i = 0;
while ((wc = getwc(stdin)) != L'\n' &&
!feof(stdin) && !ferror(stdin)) {
if (i < BUFSIZBUFFER_SIZE - 1) {
buf[i++] = wc;
}
}
buf[i] = L'\0';
}
|
...