C redirecting stdout to file with predefined message

瘦欲@ 提交于 2020-01-24 21:59:25

问题


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().

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.

Here is my code:

#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;
}

回答1:


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]) ;
      ...



回答2:


The dup system call duplicates the file descriptor which creates a second handle for the program to write to wherever the first one is connected.

It does not duplicate whatever activity goes on the i/o channel. If you want that, you'll have to do two (or more) writes.



来源:https://stackoverflow.com/questions/58667136/c-redirecting-stdout-to-file-with-predefined-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!