clinuxfileoperating-systemdup

C redirecting stdout to file with predefined message


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

Solution

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