2025年4月14日 星期一 乙巳(蛇)年 正月十五 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

C语言getc()函数:从流中读取字符

时间:12-29来源:作者:点击数:112

头文件:#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从文件流中逐个读取字符,直到读完。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门