Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to print both to stdout and file in C
    text
    copied!<p>I read this topic, but his problem maybe different from mine <a href="https://stackoverflow.com/questions/3661070/writing-to-both-stdout-a-file">Writing to both stdout &amp; a file</a></p> <p>I want to write a function, that function need to print out to both stdout and a file. My C program gets user input by scanf.</p> <p>I intend to write a function like printf but I don't really know how:</p> <p>I tried this, but it only can work with "pure" string, can't convert %d, %.*lf (my print function only need two conversions)</p> <pre><code>void dupPrint(FILE *fp,char *string) { printf("%s",string); fprintf(fp,"%s",string); return; } </code></pre> <p>I tried dup2 and freopen but they didn't work for me.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;fcntl.h&gt; int main() { int i; int file = open("input3.txt", O_APPEND | O_WRONLY); if(file &lt; 0) return 1; if(dup2(file,1) &lt; 0) return 1; printf("Redirect to file!\n"); printf("enter i : "); scanf("%d",&amp;i); return 0; } </code></pre> <p>This dup2() tutorial only print to file.</p> <p>I also tried tee, but may be it not work because I have to get input from user (if work, it's not "fair" because tee isn't in my program).</p> <p>I think implement a printf-like will solved problem but I don't know how to convert .*lf (print out double with user-enter precision)</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdarg.h&gt; void dupPrint(FILE *fp,char *fmt, ...) { va_list ap; char *p, *sval; int ival; double dval; va_start (ap, fmt); //make ap point to 1st unnamed arg for(p = fmt; *p; p++) { if (*p != '%') { putchar(*p); continue; } switch (*++p) { case 'd': ival = va_arg(ap, int); printf("%d", ival); break; case '.*lf' //????? } } } </code></pre> <p>Can anyone suggest a solution for my problem?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload