【发布时间】:2021-12-10 14:51:27
【问题描述】:
所以我使用 C 中的 open 函数打开一个目标文件,如果它不存在,我会创建它。我正在将终端的标准输出重定向到这个文件中。当我运行我的程序时,它会使用我在 shell 中键入的名称创建一个新文件,但会附加一个“?”到最后。有人可以帮我弄清楚如何删除它吗?
我的代码在下面
// Take output from ls as input into the next argument.
command = strtok(NULL, " "); // Holds the value for the destination file.
printf("%s\n", command);
int targetFD = open(command, O_WRONLY | O_CREAT | O_TRUNC, 0700);
if (targetFD == -1)
{
perror("open()");
exit(1);
}
printf("The file descriptor for targetFD is %d\n", targetFD);
int result = dup2(targetFD, 1);
if (result == -1)
{
perror("dup2");
exit(2);
}
ls(); // instead of printing ls to the terminal, it gets written to the file.
这是示例执行的图像。注意 junk.txt 文件是如何存在的......我希望我的程序将“ls”重定向到该文件或创建一个新的文件不存在。 sample program execution
【问题讨论】:
-
代码太不完整。例如,
strtok在哪个缓冲区上运行?也就是说,错过了第一个strtok电话。请以minimal reproducible example 的形式提供完整代码。请注意,这意味着任何人都可以完全按照所示复制以重现问题的最少量的完整代码。 -
另外,请不要发布文本输出的屏幕截图。将文本直接复制到问题中。