Linux 操作文件的底层系统调用主要通过以下几个核心函数实现,这些函数直接与内核交互,是用户空间程序访问文件系统的桥梁:
0
: 标准输入(STDIN_FILENO)1
: 标准输出(STDOUT_FILENO)2
: 标准错误(STDERR_FILENO)#include <fcntl.h>
int open(const char *pathname, int flags, mode_t mode);
pathname
: 文件路径。flags
: 打开方式(如 O_RDONLY
, O_WRONLY
, O_RDWR
, O_CREAT
, O_TRUNC
等)。mode
: 文件权限(仅 O_CREAT
时生效,如 0644
)。-1
。#include <unistd.h>
int close(int fd);
ssize_t read(int fd, void *buf, size_t count);
ssize_t write(int fd, const void *buf, size_t count);
fd
: 文件描述符。buf
: 数据缓冲区。count
: 读写字节数。-1
。off_t lseek(int fd, off_t offset, int whence);
SEEK_SET
: 文件开头。SEEK_CUR
: 当前位置。SEEK_END
: 文件末尾。#include <sys/stat.h>
int stat(const char *pathname, struct stat *buf);
int fstat(int fd, struct stat *buf);
struct stat
结构体中。int unlink(const char *pathname); // 删除文件
int rmdir(const char *pathname); // 删除空目录
#include <sys/mman.h>
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
int munmap(void *addr, size_t length);
int dup(int oldfd); // 复制描述符(返回最小可用fd)
int dup2(int oldfd, int newfd); // 强制指定新fd
#include <unistd.h>
int fsync(int fd); // 同步文件数据+元数据
int fdatasync(int fd); // 仅同步文件数据
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("test.txt", O_RDWR | O_CREAT, 0644);
write(fd, "Hello", 5);
lseek(fd, 0, SEEK_SET);
char buf[10];
read(fd, buf, 5);
close(fd);
return 0;
}
int 0x80
或 syscall
指令)触发系统调用。readv/writev
)或使用 mmap
。errno
)。fcntl
或 flock
避免竞争条件。通过掌握这些系统调用,可以深入理解Linux文件操作的底层机制,并编写高效、可靠的代码。