Linux下的文件描述符

什么是文件描述符

当我们在Linux下打开一个文件时,这个文件的内容就会被读取到内存中来,而Linux下有一个列表来管理这些内存,这个列表里面存储的就是这些空间对应的指针,所以说文件描述符的本质就是存这个文件内容的内存指针对应在链表的下标(索引),最基本的三个文件描述符就是标准输入(stdin,文件描述符0,一般就是键盘),标准输出(stdout,文件描述符1,一般输出到屏幕),标准错误输出(stderr,文件描述符2,一般也是屏幕),我们调用print()一般就是调用文件描述符1。

如何使用文件描述符

1. 打开文件(获取文件描述符)

使用open()系统调用打开文件,并获取文件描述符。

#include <fcntl.h>

#include <unistd.h>

int fd = open("example.txt", O_RDONLY);

if (fd == -1) {

perror("open");

return 1;

}

  1. 读取文件

使用read()系统调用来从文件描述符指向的文件中读取数据。

char buffer[1024];

ssize_t bytesRead = read(fd, buffer, sizeof(buffer));

if (bytesRead == -1) {

perror("read");

return 1;

}

3. 写入文件

使用write()系统调用来向文件描述符指向的文件中写入数据。

复制代码
const char *text = "Hello, World!\n";
ssize_t bytesWritten = write(fd, text, sizeof(text));
if (bytesWritten == -1) {
    perror("write");
    return 1;
}

4. 移动文件指针

使用lseek()系统调用来移动文件描述符指向的文件的文件指针。

复制代码
off_t offset = lseek(fd, 0, SEEK_SET);
if (offset == (off_t)-1) {
    perror("lseek");
    return 1;
}

5. 关闭文件

使用close()系统调用来关闭文件描述符,释放资源。

复制代码
if (close(fd) == -1) {
    perror("close");
    return 1;
}

8. 管道和套接字

文件描述符也用于管道和套接字,使用pipe()socket()系统调用来创建管道和套接字。

复制代码
int pipe_fds[2];
if (pipe(pipe_fds) == -1) {
    perror("pipe");
    return 1;
}

int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
    perror("socket");
    return 1;
}

文件描述符的重定向

我们可以对已经存在的文件描述符进行重定向,比如文件描述符1,默认是将向屏幕输送信息,可以将他更改为向某个文件输送,这样,调用printf()函数就会向对应文件输入信息,重定义的系统调用一般使用dup2()

#include <unistd.h>

#include <fcntl.h>

int main() {

int new_stdout_fd = open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);

if (new_stdout_fd == -1) {

perror("open");

return 1;

}

if (dup2(new_stdout_fd, STDOUT_FILENO) == -1) {

perror("dup2");

return 1;

}

// 现在,stdout被重定向到output.txt

printf("This will be written to output.txt\n");

// 关闭新文件描述符,因为dup2已经复制了它

close(new_stdout_fd);

return 0;

}

相关推荐
学不动CV了14 分钟前
数据结构---链表结构体、指针深入理解(三)
c语言·arm开发·数据结构·stm32·单片机·链表
tan77º14 分钟前
【Linux网络编程】Socket - UDP
linux·服务器·网络·c++·udp
czhc114007566326 分钟前
Linux 76 rsync
linux·运维·python
GiraKoo1 小时前
【GiraKoo】C++14的新特性
c++
悠悠小茉莉1 小时前
Win11 安装 Visual Studio(保姆教程 - 更新至2025.07)
c++·ide·vscode·python·visualstudio·visual studio
坏柠1 小时前
C++ Qt 基础教程:信号与槽机制详解及 QPushButton 实战
c++·qt
蓝易云1 小时前
Qt框架中connect()方法的ConnectionType参数使用说明 点击改变文章字体大小
linux·前端·后端
泽02022 小时前
C++之红黑树认识与实现
java·c++·rpc
花落已飘2 小时前
多线程 vs 异步
linux·网络·系统架构
岁忧2 小时前
(LeetCode 每日一题) 1865. 找出和为指定值的下标对 (哈希表)
java·c++·算法·leetcode·go·散列表