C 庫 - ungetc() 函式



C 庫函式 int ungetc(int char, FILE *stream) 將字元 char(一個無符號字元)壓回指定流中,以便下次讀取操作可以使用它。這在需要將字元放回輸入流的場景中非常有用,通常是在讀取字元並確定它不是當時要處理的正確字元之後。

語法

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

int ungetc(int char, FILE *stream);

引數

此函式接受以下引數:

  • char : 要壓回流中的字元。它被轉換為無符號字元。
  • stream : 指向 FILE 物件的指標,標識該流。

返回值

成功時,ungetc 函式返回壓回流中的字元。如果發生錯誤,函式返回 EOF 並設定流的錯誤指示符。

示例 1:ungetc 的基本用法

程式從檔案中讀取第一個字元,使用 ungetc 將其壓回流中,然後再次讀取它以演示它已成功壓回。

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

#include <stdio.h>

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

   int c = fgetc(file);
   printf("Read character: %c\n", c);

   ungetc(c, file);
   int c2 = fgetc(file);
   printf("Read character again: %c\n", c2);

   fclose(file);
   return 0;
}

輸出

上述程式碼產生以下結果:

Read character: H
Read character again: H

示例 2:處理多個 ungetc 呼叫

在此示例中,多次呼叫 ungetc 以演示如何處理壓回多個字元。

#include <stdio.h>

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

   int c1 = fgetc(file);
   int c2 = fgetc(file);
   printf("Read characters: %c%c\n", c1, c2);

   ungetc(c2, file);
   ungetc(c1, file);
   printf("Pushed back characters: %c%c\n", c1, c2);

   int d1 = fgetc(file);
   int d2 = fgetc(file);
   printf("Read characters again: %c%c\n", d1, d2);

   fclose(file);
   return 0;
}

輸出

執行上述程式碼後,我們將得到以下結果:

Read characters: H
Pushed back characters: He
Read characters again: He
廣告
© . All rights reserved.