Reputation: 1412
I would like everything that gets output to stdout to also be saved in a file in my C code. I know that I can do this by calling the process on the command line and piping it to a file:
myprogram.exe 1>logfile.txt
for example. But I am wondering if there is a way to do this from within the C code itself. Is there a function in the printf() family that can output to both the terminal and a specified file with the same arguments?
If not, what would be the syntax required to write my own printf()-style function which calls both printf() and fprintf() within it, using the same argument style as printf()?
Upvotes: 0
Views: 2373
Reputation:
Going off the suggestion to use variadic functions:
#include <stdio.h>
#include <stdarg.h>
/*
* Not all compilers provide va_copy(), but __va_copy() is a
* relatively common pre-C99 extension.
*/
#ifndef va_copy
#ifdef __va_copy
#define va_copy(dst, src) __va_copy((dst), (src))
#endif
#endif
#ifdef va_copy
#define HAVE_VACOPY 1
#endif
int
ftee(FILE *outfile, const char *format, ...)
{
int result;
va_list ap;
#if HAVE_VACOPY
va_list ap_copy;
#endif
va_start(ap, format);
#if HAVE_VACOPY
va_copy(ap_copy, ap);
result = vfprintf(outfile, format, ap_copy);
va_end(ap_copy);
if (result >= 0)
result = vprintf(format, ap);
#else
result = vfprintf(outfile, format, ap);
if (result >= 0) {
va_end(ap);
va_start(ap, outfile);
result = vprintf(format, ap);
}
#endif
va_end(ap);
return result;
}
That can be used like the standard fprintf
function in that you specify an output file, except it will also write the normal output to stdout
. I attempted to support relatively recent compilers that still didn't have a va_copy()
macro (defined in C99) such as that which comes with Visual Studio 2012 (VS2013 finally has one). Some C runtimes also conditionally define va_copy()
such that compiling with strict C89/C90 mode enabled will make it undefined while __va_copy()
may remain defined.
Upvotes: 2
Reputation: 989
You can use the fprintf() function, which is quite similar to printf() in the way it works.
Here is an example:
FILE *fp;
int var = 5;
fp = fopen("file_name.txt", "w");// "w" means that we are going to write on this file
fprintf(fp, "Writting to the file. This is an int variable: %d", var);
The output on your file would be this:
This is being written in the file. This is an int variable: 5
N.B: Opening the file using w as parameter will destroy the file's content every time you open it.
For writing to a file you have to use file operation commands, it is not possible to write to a file using printf (it prints only to the stdout). You can use:
sprintf(buf,"%d",var); //for storing in the buffer
printf(buf); //output to stdout
fputs(buf, fp); //output to file
Upvotes: 0