在C中写入文件和控制台

时间:2011-01-05 09:06:59

标签: c stdio printf

我正在尝试编写一个允许我写入控制台和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文件?

感谢并希望听到您的回复。

4 个答案:

答案 0 :(得分:5)

您可以使用<stdarg.h>功能以及vprintfvfprintf。 E.g。

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 :(得分:0)

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

答案 2 :(得分: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的唯一参数:你不能直接打印整数数组。

答案 3 :(得分:-1)

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

e.g。 (语法没有检查,但给你一个想法)

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