【问题标题】:When using the open command, and O_CREAT, it is appending a "?" to the end of the file name, how do I remove this?当使用 open 命令和 O_CREAT 时,它会附加一个“?”到文件名的末尾,我该如何删除它?
【发布时间】: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 的形式提供完整代码。请注意,这意味着任何人都可以完全按照所示复制以重现问题的最少量的完整代码。
  • 另外,请不要发布文本输出的屏幕截图。将文本直接复制到问题中。

标签: c io stdout stdin


【解决方案1】:

我敢打赌 ? 不是文字 ? 字符,而是您的 ls 版本显示包含不可打印字符的文件名的方式,例如如果您使用 GNU ls 并默认启用 -q 选项。

我还注意到,在您的示例输出中,junk.txtThe file descriptor for targetFD 之间有一个额外的空白行。您在command 之后只打印了一个换行符,所以我怀疑字符串command 本身以\n 结尾。如果它是从以\n 结尾的字符串(例如以fgets 读取的行)解析的,那将很合适。所以你实际上创建了一个名为junk.txt\n 的文件,而ls 将换行符打印为?

也许您想使用" \n" 作为strtok 的分隔符字符串,这样换行符也将被视为分隔符而不包含在标记字符串中。

【讨论】:

  • 哇,成功了,非常感谢!!!
猜你喜欢
  • 2021-07-08
  • 2010-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
相关资源
最近更新 更多