我正在运行下面的代码,但无法重定向到文件。文件已创建,但未放入任何内容。如果我删除最后一个 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/