【发布时间】: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