getc

来源:互联网 发布:c语言的软件是什么 编辑:程序博客网 时间:2024/06/04 19:05
头文件:#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 0
原创粉丝点击