c - 为什么 execl 会覆盖文件

标签 c execl

#include <unistd.h>
#include <sys/types.h> 
#include <sys/wait.h>
#include <stdlib.h>
#include <fcntl.h> // open
#include <stdio.h>

int main() {
  close(1); // close standard out
  open("log.txt", O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
  puts("Captain's log");
  chdir("/usr/include");
  execl("/bin/ls", "ls", ".", (char *)NULL); 
  perror("exec failed");
  return 0;
}

当我检查log.txt时,我找不到“船长日志”。我认为它在 execl 之前运行,因此它应该在那里!

最佳答案

您正在将其写入标准输出,为什么您希望它出现在文件中?

如果您想重定向stdout,只需使用 freopen()

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include <unistd.h>

int main()
{
    FILE *file;

    file = freopen("log.txt", "w", stdout);
    if (file == NULL)
        return -1;

    printf("Captain's log");
    chdir("/usr/include");

    if (execl("/bin/ls", "ls", ".", NULL) != 0)
        perror("exec failed");
    fclose(file);

    return 0;
}

关于c - 为什么 execl 会覆盖文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28665166/

相关文章:

c++ - 一个数组中的 Char 和 Int

c - 管理编码器的值以了解编码器本身的方向(逆时针或顺时针)

java - C 中变量赋值需要多少个时钟周期?

c - Linux ubuntu下c中的execl命令

c - 执行权限被拒绝

c - C 中的父/子和管道,子-父通信

c - 为什么应该执行 exec "sh -c a.out"而不是 a.out 本身?

c - 我怎么知道用户按下了哪个关键字?

c - `size_t`是标准库的一部分,还是C语言本身的一部分?

c - execl error == "file exists"当文件不存在时