【问题标题】:Writing to a file and console in C在 C 中写入文件和控制台
【发布时间】:2011-01-05 09:06:59
【问题描述】:

我正在尝试编写一个函数,允许我在 C 中写入控制台和文件。

我有以下代码,但我意识到它不允许我附加参数(如 printf)。

#include <stdio.h>

int footprint (FILE *outfile, char inarray[]) {
    printf("%s", inarray[]);
    fprintf(outfile, "%s", inarray[]);
}

int main (int argc, char *argv[]) {

    FILE *outfile;
    char *mode = "a+";
    char outputFilename[] = "/tmp/footprint.log";
    outfile = fopen(outputFilename, mode);

    char bigfoot[] = "It Smells!\n";
    int howbad = 10;

    footprint(outfile, "\n--------\n");

    /* then i realized that i can't send the arguments to fn:footprints */
    footprint(outfile, "%s %i",bigfoot, howbad); /* error here! I can't send bigfoot and howbad*/

    return 0;
}

我被困在这里了。有小费吗?对于我要发送给函数的参数:footprints,它将由字符串、字符和整数组成。

还有其他 printf 或 fprintf fns 我可以尝试创建包装器吗?

谢谢,希望听到你们的回应。

【问题讨论】:

标签: c stdio printf


【解决方案1】:

您可以使用&lt;stdarg.h&gt; 功能和vprintfvfprintf。例如

void footprint (FILE * restrict outfile, const char * restrict format, ...) {

    va_list ap1, ap2;

    va_start(ap1, format);
    va_copy(ap2, ap1);

    vprintf(format, ap1);
    vfprintf(outfile, format, ap2);

    va_end(ap2);
    va_end(ap1);
}

【讨论】:

  • +1 但 fooprint 接受两个参数加上 var args 可能更好;文件和格式像 fprintf 这样他就可以实际指定格式字符串(否则即使你有一个 var arg 函数,你也只能指定一个 var :/
  • @Jason Coco:很重要,我完全搞砸了。现已修复。
【解决方案2】:

printf、scanf 等函数使用可变长度参数。 Here 是关于如何创建自己的函数来获取可变长度参数的教程。

【讨论】:

    【解决方案3】:

    是的,printf 有多个版本。你要找的可能是vfprintf:

    int vfprintf(FILE *stream, const char *format, va_list ap);
    

    printf 这样的函数需要是可变参数函数(即:采用动态数量的参数)。


    这里是一个例子:

    int print( FILE *outfile, char *format, ... ) {
        va_list args;
        va_start (args, format);
        printf( outfil, format, args );
        va_end (args);
    }
    

    请注意,这完全是作为 printf 的唯一参数:你不能直接用 this 打印整数数组。

    【讨论】:

      【解决方案4】:

      你可以传入一个指向你的字符串的字符点吗?

      例如(语法未检查,但给你一个想法)

          #include <stdio.h>
      
      int footprint (FILE *outfile, char * inarray) {
          printf("%s", inarray);
          fprintf(outfile, "%s", inarray);
      }
      
      int main (int argc, char *argv[]) {
      
          FILE *outfile;
          char *mode = "a+";
          char outputFilename[] = "/tmp/footprint.log";
          outfile = fopen(outputFilename, mode);
      
          char bigfoot[] = "It Smells!\n";
          int howbad = 10;
      
          //footprint(outfile, "\n--------\n");
          char newString[255];
          sprintf(newString,"%s %i",bigfoot, howbad);
      
          footprint(outfile, newString); 
      
          return 0;
      }
      

      【讨论】:

      • 谢谢,发条熊!我猜你不是瑞士人。 :) 如果我采用 sprintf 函数后跟足迹函数,这将破坏我替换 print_to_file 和控制台的目的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      • 2017-08-27
      相关资源
      最近更新 更多