qfedu-linux-advanced-level/day4/file2.c

20 lines
708 B
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd = open("a.txt", O_WRONLY | O_CREAT | O_APPEND, 0644);
printf("新打开的hello fd\n"); // fd 描述符会变为 1 ,printf 回答引导 fd 对应文件中
close(1); // 关闭标准输出文件描述符为1
int newfd = dup(fd); // 1->a.txt会分配当前最小可用的文件描述符(这个时候标准输出1的描述符空闲)即拿到文件描述符1
// 下面的打印(写入)会重定向到 a.txt 文件中
printf("newfd = %d\n", newfd);
printf("hahah\n");
close(fd);
printf("yes\n");
return 0;
}