【问题标题】:C dup2 overwrite file bug when line > 1当行 > 1 时 C dup2 覆盖文件错误
【发布时间】:2014-10-18 19:50:00
【问题描述】:

我有以下将 infile 连接到 outfile 的简单程序

  char *execArgs[] = { "cat", NULL};
  int outfile = open("outfile", O_WRONLY | O_CREAT, 0644);
  int infile = open("infile", O_RDONLY, 0);
  dup2(outfile, STDOUT_FILENO); 
  dup2(infile, STDIN_FILENO); 
  close(outfile);
  close(infile);
  execvp(execArgs[0], execArgs);

现在,假设 infile 的内容是

this is infile

outfile 是

this is outfile

程序运行后,outfile的内容最后多了一个“e”

this is infilee

另外,如果是输出文件

this is outfile
this is outfile

变成了

this is infilee
this is outfile

怎么了?

【问题讨论】:

  • int outfile = open("outfile", O_WRONLY | O_CREAT, 0644);此行导致问题,您只想在 outfile 不存在时创建。

标签: c cat dup


【解决方案1】:

您遇到的是预期的行为。 cat 只是写入它读取的字节数,所以由于原来的outfile 更长,剩余的字节包含它们之前包含的内容。

如果你问为什么你会得到与使用 shell 执行不同的行为:

cat < infile > outfile

原因是外壳打开outfile(或&gt; 的任何目标)时使用O_TRUNC,这会将文件截断为零长度作为打开它的一部分。您可以通过将 | O_TRUNC 添加到您的 open 调用的 flags 参数来获得相同的行为。

【讨论】:

    【解决方案2】:

    尝试使用O_TRUNC,这将截断它存在的文件。

    int outfile = open("outfile", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    

    【讨论】:

      【解决方案3】:

      它没有额外的 e,它具有与该位置始终相同的e。

      看看你写的字符串:

      this is infilee
      this is outfile
                    ^
                    +-- lines up
      

      问题在于输出没有被截断,因此它保留了所有旧内容。你只是从一开始就覆盖它。

      【讨论】:

        猜你喜欢
        • 2011-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-20
        • 1970-01-01
        • 2021-07-23
        • 1970-01-01
        相关资源
        最近更新 更多