2025年4月2日 星期三 乙巳(蛇)年 正月初三 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

C语言putc()函数:写文件函数(将一指定字符写入文件中)

时间:12-29来源:作者:点击数:104

头文件:#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()为宏定义,非真正的函数调用。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门