【问题标题】:C redirecting stdout to file with predefined messageC将标准输出重定向到带有预定义消息的文件
【发布时间】:2020-02-28 05:13:21
【问题描述】:

当我使用 dup() 和 dup2() 将 case 's' 打到 case 'f' 的打开文件中时,我想复制在标准输出中打印的消息。

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

这是我的代码:

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

【问题讨论】:

  • 您是否要同时写入屏幕和文件?这不是dup 所做的。

标签: c linux file operating-system dup


【解决方案1】:

dup 系统调用复制文件描述符,它为程序创建第二个句柄以写入第一个句柄连接的任何位置。

它确实复制 i/o 通道上的任何活动。如果你想这样,你必须写两次(或更多)。

【讨论】:

  • 您好,谢谢您的回答。我正在写的一本书中的问题坚持我尝试只使用一次写入。有可能按照我的方式做到这一点吗?我正在考虑使用管道来解决这个问题。
【解决方案2】:

考虑使用 'tee' 程序(到子进程的管道),它能够将标准输出发送到文件。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多