[MCU开发工具资源区] keil中定义 fputc 函数

[复制链接]
575|0
 楼主| 51xlf 发表于 2022-12-21 20:58 | 显示全部楼层 |阅读模式
函数 fputc 是输出字符的底层函数,只需要实现这个函数,类似 printfputs 等函数也可以正常使用了。
由于存在3种文件类型,这里分别定义3种文件类型的fputc函数,在 fputc 中统一调用。


  1. // 设备文件写入一个字符
  2. static int fputc_dev(int c,FILE * stream)
  3. {
  4.   const libc_device_file *dev=stream->dev;
  5.   if(dev)
  6.   {
  7.     if(dev->putc)
  8.     {
  9.       dev->putc(c);
  10.       return c;
  11.     }
  12.   }
  13.   return EOF;
  14. }

  15. // 内存文件写入一个字符
  16. static int fputc_mem(int c,FILE * stream)
  17. {
  18.   libc_mem_file *mem=stream->mem;
  19.   if(mem)
  20.   {
  21.     if(mem->ptr<mem->size)
  22.     {
  23.       mem->data[mem->ptr]=c;
  24.       mem->ptr++;
  25.       return c;
  26.     }
  27.   }
  28.   return EOF;
  29. }

  30. // 普通文件写入一个字符
  31. static int fputc_fil(int c,FILE * stream)
  32. {
  33.   uint8_t d=c;
  34.   if(fwrite(&d, 1, 1, stream)==1)
  35.     return c;
  36.   else
  37.     return EOF;
  38. }

  39. static int (*const g_putc_funs[3])(int,FILE *)={
  40.   fputc_fil,
  41.   fputc_dev,
  42.   fputc_mem,
  43. };


  44. // 写入一个字符
  45. int fputc(int c, FILE * stream)
  46. {
  47.   if(stream)
  48.   {
  49.     return g_putc_funs[stream->type](c,stream);
  50.   }
  51.   return EOF;
  52. }



您需要登录后才可以回帖 登录 | 注册

本版积分规则

551

主题

9967

帖子

24

粉丝
快速回复 在线客服 返回列表 返回顶部