Linux函数之lseek、stat、lstat
Linux函数之lseek、stat、lstat的简单介绍
lseek函数
在Linux终端下输入命令:man 2 lseek
,可以查看具体函数信息
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
参数:
- fd:文件描述符:通过open得到,用于操作文件
- offset:偏移量
- whence:
SEEK_SET
The file offset is set to offset bytes.
SEEK_CUR
The file offset is set to its current location plus offset bytes.
SEEK_END
The file offset is set to the size of the file plus offset bytes.
返回值:
返回文件指针的位置
作用:
1. 移动文件指针到头文件 lseek(fd,0,SEEK_SET);
2. 获取文件当前指针的位置 lseek(fd,0,SEEK_CUR);
3. 获取文件的长度 lseek(fd,0,SEEK_END);
4. 拓展文件的长度 lseek(fd,100,SEEK_END);
下面为简单案例:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(){
int fd = open("./hello.txt",O_WRONLY);
if(fd == -1){
perror("open");
return -1;
}
//扩展文件
int ret = lseek(fd,100,SEEK_END);
if(ret == -1){
perror("lseek");
return -1;
}
//写入空数据
write(fd,"mengyan",7);
lseek(fd,12,SEEK_SET);
write(fd,"miaomiao",8);
//关闭文件
close(fd);
return 0;
}
stat函数
在Linux终端下输入命令:man 2 stat
,可以查看具体函数信息
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *pathname, struct stat *statbuf);
作用:获取一个文件的相关信息
参数:
- pathname:操作文件的路径
- statbuf:结构体变量,传出参数,用于保存获取到的文件信息
返回值:
- 成功:返回0
- 失败:返回-1,设置error
int lstat(const char *pathname, struct stat *statbuf);
作用:用于获取连接文件的信息
下面为简单案例:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
int main(){
struct stat statbuf;
int ret = stat("./hello.txt",&statbuf);
if(ret == -1){
perror("stat");
return -1;
}
std::cout << statbuf.st_size <<std::endl;
return 0;
}
lstat函数
作用:用于获取链接文件的信息
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异