【发布时间】:2018-03-26 21:02:50
【问题描述】:
我正在学习 Linux,我需要创建一个允许我输入重定向 (stdin) 和输出重定向 (stdout) 的函数。我发现了一个示例,其中实际创建了一个具有我选择调用它的名称的文件文本。但我不明白如何在创建同一个文件后写入它。我发现的函数是下面这个
#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;
}
【问题讨论】:
-
freopen("mystdout.txt", "a+", stdout);cplusplus.com/reference/cstdio/freopen "[...] 此函数对于将预定义的流(如标准输入、标准输出和标准错误)重定向到特定文件特别有用(参见下面的示例)。" -
我只能使用open和dup/dup2。所以我认为我不能使用 freopen 但我想我理解你的答案背后的想法