【问题标题】:Linux Files ManagementLinux 文件管理
【发布时间】: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 但我想我理解你的答案背后的想法

标签: c linux


【解决方案1】:

打开文件后,您可以使用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;
}

重定向stdinO_RDONLY 模式打开文件并使用STDIN_FILENO

【讨论】:

  • 我测试了它,唯一的新东西是屏幕上的 printf。我可以使用 --> dup2(STDOUT_FILENO, pfd) 写入文件?
  • 是的,应该将标准输出重定向到文件。
  • dup2 将文件描述符复制到另一个文件描述符,因此它“复制到 (dup2)”。奇怪的语义。
  • 是的,但它不是标准输出。因此,它不会遵循允许将进程连接在一起的 linux 约定。
  • 所以如果我理解我在创建文件时不能直接写入文件?
猜你喜欢
  • 2012-07-25
  • 2011-06-14
  • 2010-09-28
  • 1970-01-01
  • 2015-11-01
  • 2023-03-03
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
相关资源
最近更新 更多