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 返回 EOFgetwc 返回 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. 如果 streamNULL,则 getcgetwc 将调用无效参数处理程序,如参数验证中所述。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. stream 关联的文件。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
getc fgetc 一样,但实现为函数和宏。Same as fgetc, but implemented as a function and as a macro.
getwc getc 的宽字符版本。Wide-character version of getc. 根据 stream 是在文本模式还是二进制模式中打开,读取多字节字符或宽字符。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 getc getc getwc


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

有关其他兼容性信息,请参见“简介”中的 兼容性For additional compatibility information, see Compatibility in the Introduction.


// 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/O Stream I/O
fgetc、fgetwc fgetc, fgetwc
_getch、_getwch _getch, _getwch
putc、putwc putc, putwc
ungetc、ungetwcungetc, ungetwc