函式
<cstdio>

fgetc

int fgetc ( FILE * stream );
從流中讀取字元
返回指定的內部檔案位置指示器當前指向的字元。然後,內部檔案位置指示器會前進到下一個字元。

如果呼叫時流已到達檔案末尾,函式將返回 EOF 並設定流的檔案結束指示器(請參見 feof)。

如果發生讀取錯誤,函式將返回 EOF 並設定流的錯誤指示器(請參見 ferror)。

fgetcgetc 等效,不同之處在於 getc 在某些庫中可能被實現為宏。

引數

stream
指向標識輸入流的 FILE 物件的指標。

返回值

成功時,返回讀取到的字元(提升為int值)。
返回型別是int以容納特殊值 EOF,它表示失敗
如果位置指示器位於檔案末尾,函式將返回 EOF 並設定檔案結束指示器(請參見 feof)。
如果發生其他讀取錯誤,函式也會返回 EOF,但會設定其錯誤指示符 (ferror)。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* fgetc example: money counter */
#include <stdio.h>
int main ()
{
  FILE * pFile;
  int c;
  int n = 0;
  pFile=fopen ("myfile.txt","r");
  if (pFile==NULL) perror ("Error opening file");
  else
  {
    do {
      c = fgetc (pFile);
      if (c == '$') n++;
    } while (c != EOF);
    fclose (pFile);
    printf ("The file contains %d dollar sign characters ($).\n",n);
  }
  return 0;
}

此程式讀取一個名為myfile.txt的現有檔案,逐個字元地讀取,並使用n變數來計算檔案中包含多少個美元符號 ($) 檔案包含的內容。

另見