了解文件描述符之前,我们先整理一下这五个字

文件描述符就是:描述文件的符号,是对于文件的别名

#include <stdio.h>
#include <fcntl.h> // For open() flags
#include <unistd.h> // For syscalls like write(), close()
 
int main() {
    int fd; // fd 就是文件描述符 (file descriptor)
 
    // 1. 打开一个文件 "my_file.txt" 用于写入,如果不存在就创建
    fd = open("my_file.txt", O_WRONLY | O_CREAT, 0644);
    if (fd == -1) {
        perror("open"); // 如果打开失败,打印错误信息
        return 1;
    }
 
    // 2. 使用文件描述符 fd 向文件写入 "Hello, world!\n"
    const char *message = "Hello, world!\n";
    write(fd, message, 14); // 14 是消息的长度
 
    // 3. 关闭文件描述符 fd,表示操作完成
    close(fd);
 
    printf("写入完成!\n");
    return 0;
}

write(fd, message, 14); // 14 是消息的长度为例,向描述符号为fd的文件写入长14的信息

更准确的理解应该是,文件是资源、文件描述符是资源的授权代号