putc

头文件:#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值