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