對比C語言中getc()函數和ungetc()函數的使用_C 語言

來源:互聯網
上載者:User

C語言getc()函數:從流中讀取字元
標頭檔:

#include <stdio.h>

函數getc()用於從流中取字元,其原型如下:

  int getc(FILE *stream);

【參數】參數*steam為要從中讀取字元的檔案流。

【傳回值】該函數執行成功後,將返回所讀取的字元。

【說明】若從一個檔案中讀取一個字元,讀到檔案尾而無資料時便返回EOF。getc()與fgetc()作用相同,但在某些庫中getc()為宏定義,而非真正的函數。

【執行個體】下面的樣本示範了getc()函數的使用,在程式中採用該函數從標準輸入控制台中讀取字元,代碼如下。

#include <stdio.h> //引入標準輸入輸出庫void main( ) {  char ch;  printf ("Input a character: ");  //輸入提示資訊  ch = getc(stdin); // 從標準輸入控制台中讀取字元  printf ("The character input was: '%c'\n", ch); // 輸出字元}

運行上述程式,首先聲明一個用於儲存所取字元的變數;然後輸 出提示資訊,接收從標準輸入控制台按下的任意鍵,並將該字元輸出到控制台。

利用getc()從檔案中讀取字串,代碼如下。

#include<stdio.h>#include<string.h>#include<stdlib.h>int main(void){  int ch;  int len;  int i=0;  FILE* fstream;  char msg[100] = "Hello!I have read this file.";  fstream=fopen("test.txt","at+");  if(fstream==NULL)  {    printf("read file test.txt failed!\n");    exit(1);  }  /*getc從檔案流中讀取字元*/  while( (ch = getc(fstream))!=EOF)  {    putchar(ch);  }  putchar('\n');  len = strlen(msg);  while(len>0)/*迴圈寫入*/  {    putc(msg[i],fstream);    putchar(msg[i]);    len--;    i++;  }  fclose(fstream);  return 0;}

函數fopen利用模式“at+”開啟文字檔,使用getc從檔案流中逐個讀取字元,直到讀完。

C語言ungetc()函數:把字元退回到輸入資料流
標頭檔:

#include<stdio.h>

ungetc()函數用於將一個字元退回到輸入資料流中,這個退回的字元會由下一個讀取檔案流的函數取得。其原型如下:

  int ungetc(char c, FILE *stream);

【參數】c為要退回的字元,stream為要退回的輸入資料流。

【傳回值】若該函數執行成功,返回非零值;否則,返回0。

舉例:下面的樣本示範了ungetc()函數的使用,使用該函數將字元退回到輸入資料流中,其代碼如下。

#include<stdio.h>#include<ctype.h>int main(){  int i=0;  char ch;  puts("Input an integer followed by a char:");  // 讀取字元直到遇到結束符或者非數字字元  while((ch = getchar()) != EOF && isdigit(ch))  {    i = 10 * i + ch - 48; // 轉為整數  }  // 如果不是數字,則放回緩衝區  if (ch != EOF)  {    ungetc(ch,stdin); // 把一個字元退回輸入資料流  }  printf("\n\ni = %d, next char in buffer = %c\n", i, getchar());  system("pause");  return 0;}

輸出結果:

123abi *= 123, next char in buffer = a

程式開始執行while迴圈,直到遇到非數字或者結束標識才能往下執行,緊接著判斷是不是結束標識,如果不是結束標識則退回鍵盤緩衝區,在最後輸出的時候使用getch()從緩衝區再次擷取該字元輸出。因為while中使用的是函數getchar(), 所以需要輸入字元後按斷行符號鍵。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.