【问题标题】:Writing an integer to a file with fputs()使用 fputs() 将整数写入文件
【发布时间】:2011-01-14 19:43:51
【问题描述】:

不可能做像fputs(4, fptOut); 这样的事情,因为 fputs 不喜欢整数。我该如何解决这个问题?

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

【问题讨论】:

    标签: c file integer


    【解决方案1】:
    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

      【讨论】:

      • @Andrew Henle 48 是数字 0 的 ASCII 十进制代码。这会将数字转换为其 ASCII 形式。使用printf("%d")时,每个数字在内部添加48@
      • 你为什么盲目地假设ASCII?没有点击我提供的链接,是吗?
      • @Andrew Henle 已修复。我盲目地假设读者应该能够理解它的本质,重写轮子。当然首选使用fprintf("%d")。读者应该也能看出,盲目地使用这段代码也会破坏n
      【解决方案3】:

      提供的答案是正确的。但是,如果您打算使用 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", yourCounter); // yourCounter of type int in this case
        

        fprintf的文档可以在here找到。

        【讨论】:

          猜你喜欢
          • 2018-02-19
          • 1970-01-01
          • 2019-01-18
          • 1970-01-01
          • 2023-02-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-03
          相关资源
          最近更新 更多