头文件:#include <stdio.h>
putc()函数用于输入一个字符到指定流中,其原型如下:
int putc(int ch, FILE *stream);
【参数】参数ch表示要输入的位置,参数stream为要输入的流。
【返回值】若正确,返回输入的的字符,否则返回EOF。
【实例】创建一个新文件,然后利用putc写入字符串,代码如下。
- #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函数以文本方式读/写一个文件, 因为文件是新建的,所以内容为空,故第一个while循环没有输出任何内容。接着strlen函数获取字符数组的长度。再次使用while 循环逐个往文件写字符,最后关闭文件。现在查看程序运行目录应该会有一个 test.txt 文件,内容是 “Hello! I have read this file. ”。
注意:虽然putc()与fputc()作用相同,但putc()为宏定义,非真正的函数调用。