gpt4 book ai didi

C: > 的实现不替换文件

转载 作者:太空宇宙 更新时间:2023-11-04 06:21:47 25 4
gpt4 key购买 nike

我正在为我自己的“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com