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

时间:2010-02-09 13:34:02

标签: c file integer

由于fput不喜欢整数,所以不可能执行fputs(4, fptOut);之类的操作。我该如何解决这个问题?

执行fputs("4", fptOut);不是一个选项,因为我正在使用计数器值。

4 个答案:

答案 0 :(得分:17)

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

可以找到fprintf的文档here

答案 1 :(得分:4)

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

答案 2 :(得分:4)

提供的答案是正确的。但是,如果您打算使用fput,那么您可以先使用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;
}

答案 3 :(得分:1)

我知道6年太晚但是如果你真的想使用fputs

char buf[12], *p = buf + 11;
*p = 0;
for (; n; n /= 10)
    *--p = n % 10 + '0';
fputs(p, fptOut);

还应注意这是出于教育目的,你应该坚持使用fprintf

相关问题