getc、getwcgetc, getwc

从流中读取字符。Read a character from a stream.


int getc(
   FILE *stream
wint_t getwc(
   FILE *stream


输入流。Input stream.

返回值Return Value

返回读取的字符。Returns the character read. 若要指示读取的错误或文件尾条件getc返回EOF,和getwc返回WEOFTo indicate a read error or end-of-file condition, getc returns EOF, and getwc returns WEOF. 有关getc,使用ferrorfeof来检查是否有错误或文件尾。For getc, use ferror or feof to check for an error or for end of file. 如果NULLgetcgetwc中所述将调用无效参数处理程序,参数验证If stream is NULL, getc and getwc invoke the invalid parameter handler, as described in Parameter Validation. 如果允许执行继续,则这些函数将返回EOF (或WEOFgetwc) 并设置errnoEINVALIf execution is allowed to continue, these functions return EOF (or WEOF for getwc) and set errno to EINVAL.

有关这些代码以及其他错误代码的详细信息,请参阅 _doserrno、errno、_sys_errlist 和 _sys_nerrSee _doserrno, errno, _sys_errlist, and _sys_nerr for more information on these, and other, error codes.


每个例程从文件的当前位置读取单个字符,并增量关联的文件指针(如果已定义)以指向下一个字符。Each routine reads a single character from a file at the current position and increments the associated file pointer (if defined) to point to the next character. 与相关联的文件The file is associated with stream.

这些函数会锁定调用线程,因此是线程安全的。These functions lock the calling thread and are therefore thread-safe. 有关非锁定版本,请参阅 _getc_nolock、_getwc_nolockFor a non-locking version, see _getc_nolock, _getwc_nolock.

下面是例程特定的备注。Routine-specific remarks follow.

例程Routine 备注Remarks
getcgetc 与相同fgetc,但实现为函数和宏。Same as fgetc, but implemented as a function and as a macro.
getwcgetwc 宽字符版本的getcWide-character version of getc. 读取多字节字符或宽字符根据是否以文本模式还是二进制模式下打开。Reads a multibyte character or a wide character according to whether stream is opened in text mode or binary mode.

一般文本例程映射Generic-Text Routine Mappings

TCHAR.H 例程TCHAR.H routine 未定义 _UNICODE 和 _MBCS_UNICODE & _MBCS not defined 已定义 _MBCS_MBCS defined 已定义 _UNICODE_UNICODE defined
_gettc_gettc getcgetc getcgetc getwcgetwc


例程Routine 必需的标头Required header
getcgetc <stdio.h><stdio.h>
getwcgetwc <stdio.h> 或 <wchar.h><stdio.h> or <wchar.h>

有关其他兼容性信息,请参阅 兼容性For additional compatibility information, see Compatibility.


// crt_getc.c
// Use getc to read a line from a file.

#include <stdio.h>

int main()
    char buffer[81];
    int i, ch;
    FILE* fp;

    // Read a single line from the file "crt_getc.txt".

    fopen_s(&fp, "crt_getc.txt", "r");
    if (!fp)
       printf("Failed to open file crt_getc.txt.\n");

    for (i = 0; (i < 80) && ((ch = getc(fp)) != EOF)
                         && (ch != '\n'); i++)
        buffer[i] = (char) ch;

    // Terminate string with a null character
    buffer[i] = '\0';
    printf( "Input was: %s\n", buffer);


输入:crt_getc.txtInput: crt_getc.txt

Line one.
Line two.


Input was: Line one.

请参阅See also

流 I/OStream I/O
fgetc、fgetwcfgetc, fgetwc
_getch、_getwch_getch, _getwch
putc、putwcputc, putwc
ungetc、ungetwcungetc, ungetwc