C 庫 - getc() 函式



C 庫函式 getc(FILE *stream) 從指定的流中獲取下一個字元(一個無符號字元),並推進流的位置指示器。它對於在字元級別處理檔案輸入操作至關重要。

語法

以下是 C 庫函式 getc() 的語法:

int getc(FILE *stream);

引數

此函式僅接受一個引數:

  • FILE *stream: 指向 FILE 物件的指標,指定輸入流。此 FILE 物件通常使用 fopen 函式獲取。

返回值

成功時,函式返回從指定流中獲取的下一個字元,作為轉換為 int 型別的無符號 char;失敗時,如果發生錯誤或到達檔案結尾,getc 返回 EOF(在 <stdio.h> 中定義的常量)。

示例 1:從檔案讀取字元

此示例演示如何使用 getc 從檔案讀取字元並將其列印到標準輸出。

以下是 C 庫 getc() 函式的示例。

#include <stdio.h>

int main() {
    FILE *file = fopen("example1.txt", "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    int ch;
    while ((ch = getc(file)) != EOF) {
        putchar(ch);
    }

    fclose(file);
    return 0;
}

輸出

以上程式碼讀取 example1.txt 檔案的內容,然後產生以下結果:

Hello, World!

示例 2:讀取直到特定字元

此示例從檔案中讀取字元,直到遇到字元“!”,演示了使用 getc 進行條件讀取。

#include <stdio.h>

int main() {
    FILE *file = fopen("example3.txt", "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    int ch;
    while ((ch = getc(file)) != EOF && ch != '!') {
        putchar(ch);
    }

    fclose(file);
    return 0;
}

輸出

假設 example3.txt 檔案包含文字:“Stop reading here! Continue...” ,則以上程式碼產生以下結果:

Stop reading here
廣告
© . All rights reserved.