4

我正在尝试编写一个函数,允许我在 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 可以尝试创建包装器?

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

4

4 回答 4

5

您可以使用<stdarg.h>功能 和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);
}
于 2011-01-05T09:16:38.450 回答
0

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

于 2011-01-05T09:16:41.363 回答
0

是的,有几个版本的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 的唯一参数:您不能直接使用它打印整数数组。

于 2011-01-05T09:17:01.787 回答
-1

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

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

    #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;
}
于 2011-01-05T09:17:07.927 回答