开发者

Writing an integer to a file with fputs()

开发者 https://www.devze.com 2022-12-19 10:32 出处:网络
It\'s not possible to do something like fputs(4, fptOut); because fputs doesn\'t like integers.开发者_如何学Python How can I work around this?

It's not possible to do something like fputs(4, fptOut); because fputs doesn't like integers.开发者_如何学Python How can I work around this?

Doing fputs("4", fptOut); is not an option because I'm working with a counter value.


What about

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

Documentation of fprintf can be found here.


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:

#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;
}


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


I know 6 years too late but if you really wanted to use 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消