C将stdout重定向到带有预定义消息的文件 [英] C redirecting stdout to file with predefined message

查看:87
本文介绍了C将stdout重定向到带有预定义消息的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用dup()和dup2()将案例's'打到案例'f的打开文件时,我想复制在stdout中打印的消息.

I want to duplicate the message that is being printed in stdout when I hit case 's' to the opened file for case 'f' using dup() and dup2().

我不确定dup系统调用的工作方式以及如何将stdout复制到文件中.我知道我必须使用dup捕获stdout指向的内容,然后使用dup2在屏幕和文件之间切换.

I'm not sure how the dup system calls work and how I could dup the stdout to the file. I know I would have to use dup to capture what stdout is pointing at then use dup2 to switch between the screen and the file.

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>

#define BUFFER_SIZE 128
#define PERMS 0666

int main(int argc, char *argv[])
{
    char outBuffer[BUFFER_SIZE] = "This is a message\n";
    int count;
    int fd;
    char input =0;
    int a;

    if(argc!=2){
        printf("Provide an valid file as an argument\n");
        exit(1);
    }

    if((fd = open(argv[1],O_CREAT|O_WRONLY|O_APPEND,PERMS)) == -1)
    {
        printf("Could not open file\n");
        exit(1);
    }

printf("0 to terminate, s to write to stdout, f to write to file\n");
        do{
        scanf(" %c", &input);
        switch(input)
        {

            case 'f':

            case 's':
            write(1,outBuffer,strlen(outBuffer));
            break;

            default:
            printf("Invalid Choice\n");

         }
     }while(input != '0');

     close(fd);
     return 0;
}

推荐答案

考虑使用"tee"程序(管道到子进程),该程序可以将stdout发送到文件.

Consider using a the 'tee' program (pipe to a child process), which has the ability to send stdout to a file.

   case 'f':
      pipe fd2[2] ;
      pipe(fd2) ;
      if (  fork() > 0 ) {
          // Child
          dup2(fd[0], 0) ;
          close(fd[1]) ;
          close(
          // create command line for 'tee'
          char teecmd[256] ;
          sprintf(teecmd, "...", ...) ;
          execlp(teecmd) ;
      } ;
      // Parent
      fd = fd[1] ;
      close(fd[0]) ;
      ...

这篇关于C将stdout重定向到带有预定义消息的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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