getc

头文件:#include <stdio.h>

函数getc()用于从流中取字符,其原型如下:
    int getc(FILE *stream);

【参数】参数*steam为要从中读取字符的文件流。

【返回值】该函数执行成功后,将返回所读取的字符。

【说明】若从一个文件中读取一个字符,读到文件尾而无数据时便返回EOF。getc()与 fgetc()作用相同,但在某些库中getc()为宏定义,而非真正的函数。

【实例】下面的示例演示了getc()函数的使用,在程序中采用该函数从标准输入控制台中读取字符,代码如下。
   
   
  1. #include <stdio.h> //引入标准输入输出库
  2. void main( ) {
  3. char ch;
  4. printf ("Input a character: "); //输入提示信息
  5. ch = getc(stdin); // 从标准输入控制台中读取字符
  6. printf ("The character input was: '%c'\n", ch); // 输出字符
  7. }
#include <stdio.h>  //引入标准输入输出库
void main( ) {
    char ch;
    printf ("Input a character: ");   //输入提示信息
    ch = getc(stdin);  // 从标准输入控制台中读取字符
    printf ("The character input was: '%c'\n", ch);  // 输出字符
}
运行上述程序,首先声明一个用于保存所取字符的变量;然后输 出提示信息,接收从标准输入控制台按下的任意键,并将该字符输出到控制台。

利用getc()从文件中读取字符串,代码如下。
   
   
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<stdlib.h>
  4. int main(void)
  5. {
  6. int ch;
  7. int len;
  8. int i=0;
  9. FILE* fstream;
  10. char msg[100] = "Hello!I have read this file.";
  11. fstream=fopen("test.txt","at+");
  12. if(fstream==NULL)
  13. {
  14. printf("read file test.txt failed!\n");
  15. exit(1);
  16. }
  17. /*getc从文件流中读取字符*/
  18. while( (ch = getc(fstream))!=EOF)
  19. {
  20. putchar(ch);
  21. }
  22. putchar('\n');
  23. len = strlen(msg);
  24. while(len>0)/*循环写入*/
  25. {
  26. putc(msg[i],fstream);
  27. putchar(msg[i]);
  28. len--;
  29. i++;
  30. }
  31. fclose(fstream);
  32. return 0;
  33. }
#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从文件流中逐个读取字符,直到读完。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值