C: > 的实现不替换文件

标签 c file-io pipe

我正在为我自己的“shell”在 c 中实现运算符 >。 但是,当输入“cat new.txt > new2.txt”时,会发生一些奇怪的事情:

> cat new.txt
This is a file. 
This file contains some text.

> cat new2.txt
This is also afile. 
This file also contains some text.
This file is called new2.txt.

> cat new.txt > new2.txt

> cat new2.txt
This is a file. 
This file contains some text.
me text.
This file is called new2.txt.

有人知道为什么会这样吗?我希望 new2.txt 被删除然后写入。

然后我重定向数据的行是:

...
pipe(pipefd);
pid = fork();
if (pid == 0)
{
  int fd = open(filename[OUT], O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
  dup2(fd, STDOUT_FILENO);
  close(fd);
  execvp(par[0], par);
  exit(-1);
}
waitpid(pid, NULL, 0);
close(pipefd[READ]);
close(pipefd[WRITE]);

最佳答案

您在 open 标志中离开了 O_TRUNC。奇怪的是,you're the second person this evening to make that mistake .

关于C: > 的实现不替换文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33647576/

相关文章:

java - Java 如何计算文件的哈希值?

python - 需要避免没有通信的子进程死锁

input - 期望重定向标准输入

C:scanf循环

c++ - 获取有向图中2个节点之间的所有路径

java - 更改父目录和子目录中的文件名

javascript - IE 不允许输入文件的自定义浏览按钮?

进程间通过管道进行通信

c - 通过 OpenCV 跟踪打印眼睛坐标

c - native C 程序中的 R.h 和 Rmath.h