C语言 使用 fputs() 将整数写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2229377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing an integer to a file with fputs()
提问by Pieter
It's not possible to do something like fputs(4, fptOut);because fputs doesn't like integers. How can I work around this?
不可能做类似的事情,fputs(4, fptOut);因为 fputs 不喜欢整数。我该如何解决这个问题?
Doing fputs("4", fptOut);is not an option because I'm working with a counter value.
这样做fputs("4", fptOut);不是一种选择,因为我正在使用计数器值。
回答by AndiDog
回答by vicatcu
The provided answers are correct. However, if you're intent on using fputs, then you can convert your number to a string using sprintf first. Something like this:
提供的答案是正确的。但是,如果您打算使用 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;
}
回答by Richard Pennington
fprintf(fptOut, "%d", counter);
回答by jeffer son
I know 6 years too late but if you really wanted to use fputs
我知道晚了 6 年,但如果你真的想使用 fputs
char buf[12], *p = buf + 11;
*p = 0;
for (; n; n /= 10)
*--p = n % 10 + '0';
fputs(p, fptOut);
Should also note this is for educational purpose, you should stick with fprintf.
还应注意这是出于教育目的,您应该坚持使用fprintf.

