使用fputs()将整数写入文件

12

无法像fputs(4, fptOut);这样做,因为fputs不接受整数。如何解决?

不能使用fputs("4", fptOut);,因为我正在使用计数器的值。

4个回答

24

怎么办?

fprintf(fptOut, "%d", yourCounter); // yourCounter of type int in this case

fprintf的文档可以在这里找到。


6
提供的答案是正确的。然而,如果你想使用fputs,那么你可以先使用sprintf将你的数字转换为字符串。像这样:
#include <stdio.h>
#include <stdint.h>

int main(int argc, char **argv){  
  uint32_t counter = 4;
  char buffer[16] = {0}; 
  FILE * fptOut = 0;

  /* ... code to open your file goes here ... */

  sprintf(buffer, "%d", counter);
  fputs(buffer, fptOut);

  return 0;
}

4
fprintf(fptOut, "%d", counter); 

2
我知道已经晚了6年,但如果你真的想使用 fputs,那么我可以帮助你进行翻译。
char buf[12], *p = buf + 11;
*p = 0;
for (; n; n /= 10)
    *--p = n % 10 + '0';
fputs(p, fptOut);

需要注意的是,这只是用于教育目的,你应该坚持使用fprintf


“48” 代表什么? - Andrew Henle
@Andrew Henle 48 是数字 0 的 ASCII 十进制代码。这将数字转换为其 ASCII 形式。在使用 printf("%d") 时,每个数字内部都会加上 48。 - rosghub
你为什么盲目地假设ASCII编码?你没有点击我提供的链接,是吗? - Andrew Henle
@Andrew Henle 已经修复。我一开始盲目地假设读者应该能够理解这是在重写轮子。当然,使用 fprintf("%d") 更好。读者还应该能够意识到盲目使用此代码也会破坏 n - rosghub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接