我读了这个主题,但他的问题可能与我写入stdout和文件有所不同
我想写一个函数,该函数需要打印到stdout和一个文件.我的C程序通过scanf获取用户输入.
我打算写一个像printf这样的函数,但我真的不知道如何:
我试过这个,但它只能用"纯"字符串,不能转换%d,%.*lf(我的打印功能只需要两次转换)
void dupPrint(FILE *fp,char *string)
{
printf("%s",string);
fprintf(fp,"%s",string);
return;
}
Run Code Online (Sandbox Code Playgroud)
我试过dup2和freopen,但它们对我不起作用.
#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;
}
Run Code Online (Sandbox Code Playgroud)
这个dup2()教程只打印到文件.
我也试过tee,但可能不行,因为我必须得到用户的输入(如果工作,那不是"公平的"因为tee不在我的程序中).
我认为实现类似printf会解决问题,但我不知道如何转换.*lf(用户输入精度打印输出double)
#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' //?????
}
}
}
Run Code Online (Sandbox Code Playgroud)
谁能为我的问题提出解决方案?
Jer*_*fin 14
幸运的是,你不需要.你只是想使用v的变种printf,并fprintf认为采取va_list直接代替你传递参数:
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);
}
Run Code Online (Sandbox Code Playgroud)