我正在尝试编写一个允许我写入控制台和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;
}
Run Code Online (Sandbox Code Playgroud)
我被困在这里 有小费吗?对于我想要发送到函数的参数:footprints,它将包含字符串,字符和整数.
是否有其他printf或fprintf fns,我可以尝试创建一个包装?
谢谢,希望听到你们的回复.
您可以使用<stdarg.h>功能vprintf和vfprintf.例如
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);
}
Run Code Online (Sandbox Code Playgroud)