Запись в файл и консоль в C - PullRequest
4 голосов
/ 05 января 2011

Я пытаюсь написать функцию, которая позволяет мне записывать в консоль и файл в 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 ]

5 голосов
/ 05 января 2011

Вы можете использовать <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);
}
0 голосов
/ 05 января 2011

Вы можете передать символ, который указывает на вашу строку?

например (синтаксис не проверен, но чтобы дать вам представление)

    #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;
}
0 голосов
/ 05 января 2011

Да, есть несколько версий 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 он принимает только единственные параметры: вы не можете печатать целочисленный массив напрямую с этим.

0 голосов
/ 05 января 2011

функции printf, scanf и т. Д. Используют аргумент переменной длины. Здесь - учебник о том, как вы можете создать свою собственную функцию для аргументов переменной длины.

...