开发者

Writing to a file and console in C

I am trying to write a function that allows me to write to the console and a file in C.

I have the following code but i realized that it does not allow me to append arguments (like 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;
}

I'm stuck here. Any tips? For the arguments which I want to sent to function:footprints, it will consist of strings, chars and integers.

Are there other printf or fprintf fns that I can try to create a wrapper around?

Thanks and hope to hear ya'll responses.


You can use <stdarg.h> functionality and vprintf and vfprintf. 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);
}


printf, scanf etc. functions use variable length argument. Here is tutorial on how you can create your own function to take variable length arguments.


Yes, there are several versions of printf. The one you're looking for is probably vfprintf:

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

Functions like printf need to be variadic functions (ie: taking a dynamic number of parameters).


Here an example:

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

Note that this takes exactly the only parameters as printf: you can't print an integer array directly with this.


You could pass in a char point that points to your string?

e.g. (syntax not checked but to give you an idea)

    #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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜