我正在学习Linux,我需要创建一个允许我输入重定向(Stdin)和输出重定向(stdout)的函数。我发现了一个示例,其中实际创建了一个以我选择的名称命名的文件text。但我不明白如何在创建后写入相同的文件。我发现的函数如下所示
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define LOCKFILE "/etc/ptmp"
int main()
{
int pfd;
char filename[1024];
if ((pfd = open("Test", O_WRONLY | O_CREAT | O_TRUNC,S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
perror("Cannot open output file\n"); exit(1);
}
}我需要创建一个函数,允许我使用open和dup/dup2进行输入重定向(Stdin)和输出重定向(stdout),但是我到处寻找,却找不到一个我真正理解的答案。
所以现在我正在尝试这种方式,但是我仍然不能写入文件
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define LOCKFILE "/etc/ptmp"
int main()
{
int pfd;
char filename[1024];
if ((pfd = open("Test", O_RDONLY | O_CREAT | O_TRUNC,S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
perror("Cannot open output file\n"); exit(1);
}
dup2(STDIN_FILENO, pfd);
close(pfd);
printf("This will be put in the file\n");
return 0;
}发布于 2018-03-27 05:07:46
打开文件后,可以使用dup2()将标准文件描述符重定向到该文件
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define LOCKFILE "/etc/ptmp"
int main()
{
int pfd;
char filename[1024];
if ((pfd = open("Test", O_WRONLY | O_CREAT | O_TRUNC,S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
perror("Cannot open output file\n"); exit(1);
}
dup2(STDOUT_FILENO, pfd);
close(pfd);
printf("This will be put in the file\n");
return 0;
}要重定向stdin,请在O_RDONLY模式下打开文件并使用STDIN_FILENO。
https://stackoverflow.com/questions/49500541
复制相似问题