如何既打印在C标准输出和文件 [英] How to print both to stdout and file in C
问题描述
我看了这个题目,但他的问题与我的不同,也许
写入标准输出和放大器;一个文件
I read this topic, but his problem maybe different from mine Writing to both stdout & a file
我想编写一个函数,该函数需要打印到标准输出和文件。我的C程序由scanf函数获取用户输入。
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.
我打算写如printf函数,但我真的不知道该怎么
I intend to write a function like printf but I don't really know how:
我想这一点,但它只能用纯字符串的工作,不能转换%D,%*。LF(我的打印功能只需要两次转换)
I tried this, but it only can work with "pure" string, can't convert %d, %.*lf (my print function only need two conversions)
void dupPrint(FILE *fp,char *string)
{
printf("%s",string);
fprintf(fp,"%s",string);
return;
}
我试过dup2和freopen函数,但他们并没有为我工作。
I tried dup2 and freopen but they didn't work for me.
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int i;
int file = open("input3.txt", O_APPEND | O_WRONLY);
if(file < 0) return 1;
if(dup2(file,1) < 0) return 1;
printf("Redirect to file!\n");
printf("enter i : ");
scanf("%d",&i);
return 0;
}
这dup2()教程只打印到文件中。
This dup2() tutorial only print to file.
我也试过发球,但可能那不行,因为我必须从用户那里获取输入(如果工作,它不是公平,因为发球是不是在我的程序)。
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).
我想实现一个类printf会解决问题,但我不知道如何转换。* LF
(需要用户输入precision打印出双)
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)
#include <stdio.h>
#include <stdarg.h>
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' //?????
}
}
}
任何人都可以提出一个解决方案,我的问题?
Can anyone suggest a solution for my problem?
推荐答案
幸运的是,你并不需要。你只需要使用 v
的printf
和 fprintf中$ C $的C
变种>是采取的va_list
,而不是你传递参数直接:
Fortunately, you don't need to. You just want to use the v
variants of printf
and fprintf
that take a va_list
instead of your passing arguments directly:
void tee(FILE *f, char const *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
va_start(ap, fmt);
vfprintf(f, fmt, ap);
va_end(ap);
}
这篇关于如何既打印在C标准输出和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!