putc

来源:互联网 发布:杭盖乐队 知乎 编辑:程序博客网 时间:2024/06/06 08:53
头文件:#include <stdio.h>

putc()函数用于输入一个字符到指定流中,其原型如下:
    int putc(int ch, FILE *stream);

【参数】参数ch表示要输入的位置,参数stream为要输入的流。

【返回值】若正确,返回输入的的字符,否则返回EOF。

【实例】创建一个新文件,然后利用putc写入字符串,代码如下。
复制纯文本新窗口
  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函数以文本方式读/写一个文件, 因为文件是新建的,所以内容为空,故第一个while循环没有输出任何内容。接着strlen函数获取字符数组的长度。再次使用while 循环逐个往文件写字符,最后关闭文件。现在查看程序运行目录应该会有一个 test.txt 文件,内容是 “Hello! I have read this file. ”。

注意:虽然putc()与fputc()作用相同,但putc()为宏定义,非真正的函数调用。
0 0
原创粉丝点击