如何在 C 中同时打印到标准输出和文件 [英] How to print both to stdout and file in C

查看:55
本文介绍了如何在 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!
");
    printf("enter i : ");
    scanf("%d",&i);



    return 0;
}

本 dup2() 教程仅打印到文件.

This dup2() tutorial only print to file.

我也试过 tee,但它可能不起作用,因为我必须从用户那里获得输入(如果有效,这不公平",因为 tee 不在我的程序中).

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(以用户输入的精度打印出双精度)

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?

推荐答案

幸运的是,您不需要这样做.您只想使用 printffprintfv 变体,它们采用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆