c++ - 在循环中使用 dup2() 和 create() 在 Linux 中重定向

标签 c++ c linux

我正在运行下面的代码,但无法重定向到文件。文件已创建,但未放入任何内容。如果我删除最后一个 dup2(saveout,1) 语句,我可以创建并写入文件,但我无法返回到终端,这很重要。一旦我将 dup2(saveout,1) 放回我的代码中,重定向就会停止工作,但我可以返回到终端。我不明白为什么会这样。我想重定向并返回到终端。

main.cpp

#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
using namespace std;

void printmessage() {
    printf("this is the message\n");
}

int main(int argc, char** argv) {    
    int saveout;
    int fd;
    saveout = dup(1);

    for (int i = 0; i < 10; i++) {
        fd = creat("/home/carl/example.txt",O_CREAT|O_APPEND);
        dup2(fd, 1);
        close(fd);
        printf("Testing the message");
        printmessage();

       dup2(saveout,1);
       close(saveout);
    }
    return 0;
}

最佳答案

这是一个文件权限问题,您应该阅读您正在使用的函数的手册页。

creat() takes as first argument the filename, and as second the file creation rights, not its opening mode.

creat() 函数是一个简单的 open() 调用,带有一些特定的标志,因此您只需设置权限即可。

如果你想打开你的文件,如果他不存在就创建它,使用

open(filename, O_CREAT | O_RDWR | O_APPEND, 0600) for example, or
creat(filename, 0600),

这在很大程度上是等效的,但您将无法附加文本,因为“creat() 等效于 open(),其标志等于 O_CREAT | O_WRONLY | O_TRUNC”

关于c++ - 在循环中使用 dup2() 和 create() 在 Linux 中重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15030703/

相关文章:

c - 不同的程序,相同的变量,相同的内存地址

linux - 将两个 tar 进程的输出通过管道传输到单个子进程中

Python 3.4.3 无法构建这些模块 : _hashlib _ssl

c++ - 如何使用asm intel语法从c中的asm访问char?

c++ - 了解模板的声明、定义和特化

c - 如何从文件中读取整数到 C 中的一维数组

c - 写入文件的函数在 .cpp 文件中有效,但在 .h 文件中无效

javascript - 一个 grunt 的替代方案——编译 sass 和 minify JS

python - 图形界面开发包

c++ - "long double"有一个单词名称吗?