Search code examples
cprintffopen

can I write a function that writes the printf type output of another function into a .txt file in C?


I would like to know how to create a function that gathers the outputs of other functions and writes them into a txt file using C. To be clear, the function outputs that I want to write are all of them of the type printf. I'm guessing that I have to use the frpintf function, but I don't really know how in this case. This is one of the functions with a printf output that I'm interested in.

void max_pixel(const char *filename){
    int red=0, green=0, blue=0, i, j, width, height, n, max=0, absc=0, ordo=0, sum=0;
    unsigned char *data;
    read_image_data(filename, &data, &width, &height, &n);
    for (i=0; i<height ; i++){
        for (j=0; j<width ; j++){
            
            pixelRGB* pixel;
            pixel = get_pixel(data,width,height,n,j,i);
            sum=pixel->R + pixel->G + pixel->B;
            if(max<sum){
                red=pixel->R;
                green=pixel->G;
                blue=pixel->B;
                absc=j;
                ordo=i;
                max=sum;

            }
        }
    }
    printf("max pixel (%d, %d): %d, %d, %d\n", absc, ordo, red, green, blue);
}

And this is the function I'm trying to use to write the previous function's output into a txt file.

void stat_report(const char *filename){
    FILE* fp;
    fp=fopen("stat_report.txt", "w");
    max_pixel(filename);
    fprintf(fp, , ,);  // Help needed here

    fclose(fp);
}

As you can see, I don't know what to put inside the fprintf function.

I hope someone can give me a helping hand and thank you for your time.


Solution

  • printf writes to stdout, or the "Standard Output", which is normally the console.

    What you want to do is redirect stdout to a file instead of the normal console.

    The way to do that is with function freopen. The call is:

    freopen("output.txt", "a+", stdout); 
    

    That is, you want to "reopen" stdout to instead direct to output.txt.

    After that, any output to stdout (such as printf) will instead go to "output.txt"


    One thing to be cautious of: If you're working in a large complex system with other developers, just because you redirected stdout doesn't mean it will stick. Another developer, another thread, another component, etc, might redirect stdout for its own purposes, and you would lose your redirection. In otherwords, this is not a great technique for a large-scale system with many components and developers.