名稱空間
變體
操作

fgetc, getc

來自 cppreference.com
< c‎ | io
 
 
檔案輸入/輸出
型別和物件
        
函式
檔案訪問
(C95)
非格式化輸入/輸出
(C95)(C95)
(C95)
(C95)(C95)
(C95)
(C95)

格式化輸入
 
定義於標頭檔案 <stdio.h>
int fgetc( FILE* stream );
(1)
int getc( FILE* stream );
(2)
1) 從給定的輸入流中讀取下一個字元。
2)fgetc 相同,但如果 getc 實現為宏,它可能會多次評估 stream,因此相應的引數不應是帶有副作用的表示式。

目錄

[編輯] 引數

stream - 從中讀取字元的流

[編輯] 返回值

成功時,返回獲取的字元,作為轉換為 intunsigned char。失敗時,返回 EOF

如果失敗是由檔案結束條件引起的,則額外在 stream 上設定 eof 指示器(參閱 feof())。如果失敗是由其他錯誤引起的,則在 stream 上設定 error 指示器(參閱 ferror())。

[編輯] 示例

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    const char* fname = "/tmp/unique_name.txt"; // or tmpnam(NULL);
    int is_ok = EXIT_FAILURE;
 
    FILE* fp = fopen(fname, "w+");
    if (!fp)
    {
        perror("File opening failed");
        return is_ok;
    }
    fputs("Hello, world!\n", fp);
    rewind(fp);
 
    int c; // note: int, not char, required to handle EOF
    while ((c = fgetc(fp)) != EOF) // standard C I/O file reading loop
        putchar(c);
 
    if (ferror(fp))
        puts("I/O error when reading");
    else if (feof(fp))
    {
        puts("End of file is reached successfully");
        is_ok = EXIT_SUCCESS;
    }
 
    fclose(fp);
    remove(fname);
    return is_ok;
}

可能的輸出

Hello, world!
End of file is reached successfully

[編輯] 參考

  • C23 標準 (ISO/IEC 9899:2024)
  • 7.21.7.1 fgetc 函式 (p: TBD)
  • 7.21.7.5 getc 函式 (p: TBD)
  • C17 標準 (ISO/IEC 9899:2018)
  • 7.21.7.1 fgetc 函式 (p: 240-241)
  • 7.21.7.5 getc 函式 (p: 242)
  • C11 標準 (ISO/IEC 9899:2011)
  • 7.21.7.1 fgetc 函式 (p: 330)
  • 7.21.7.5 getc 函式 (p: 332)
  • C99 標準 (ISO/IEC 9899:1999)
  • 7.19.7.1 fgetc 函式 (p: 296)
  • 7.19.7.5 getc 函式 (p: 297-298)
  • C89/C90 標準 (ISO/IEC 9899:1990)
  • 4.9.7.1 fgetc 函式
  • 4.9.7.5 getc 函式

[編輯] 另請參閱

stdin 讀取一個字元
(函式) [編輯]
(在 C11 中移除)(C11)
stdin 讀取一個字串
(函式) [編輯]
向檔案流寫入一個字元
(函式) [編輯]
將一個字元放回檔案流中
(函式) [編輯]
有關 fgetc, getcC++ 文件