[转]stat函数说明
1 函数都是获取文件(普通文件,目录,管道,socket,字符,块()的属性。
函数原型
#include <sys/stat.h>
int stat(const char *restrict pathname, struct stat *restrict buf);
提供文件名字,获取文件对应属性。
int fstat(int filedes, struct stat *buf);
通过文件描述符获取文件对应的属性。
int lstat(const char *restrict pathname, struct stat *restrict buf);
连接文件描述命,获取文件属性。
2 文件对应的属性
struct stat
{
mode_t st_mode; //文件对应的模式,文件,目录等
ino_t st_ino; //inode节点号
dev_t st_dev; //设备号码
dev_t st_rdev; //特殊设备号码
nlink_t st_nlink; //文件的连接数
uid_t st_uid; //文件所有者
gid_t st_gid; //文件所有者对应的组
off_t st_size; //普通文件,对应的文件字节数
time_t st_atime; //文件最后被访问的时间
time_t st_mtime; //文件内容最后被修改的时间
time_t st_ctime; //文件状态改变时间
blksize_t st_blksize; //文件内容对应的块大小
blkcnt_t st_blocks; //伟建内容对应的块数量
};
可以通过上面提供的函数,返回一个结构体,保存着文件的信息。
2008-07-26 20:25
/* 最近要做简单的linux文件管理的功能,用到函数相继贴出来.很乱,待总结!*/
/*reference :http://www.lslnet.com/linux/dosc1/10/linux-154990.htm*/
/* dir.c */
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
extern int errno;
/*
DIR *opendir(const char *name);
struct dirent *readdir(DIR *dir);
int closedir(DIR *dir);
*/
int main(int argc,char *argv[])
{
DIR *dir;
struct dirent *pdir;
struct stat st;
char buf[1024];
char c_type[6][9]={"普通文件","目录","连接","\0","其他格式","\0"};
int type;
int n;
if(argc>2)
{
printf("Usage: dir /path\n");
return 0;
}
if(argc==2)
strncpy(buf,argv[1],99);
else
strcpy(buf,".");
printf("%s\n\n",buf);
dir=opendir(buf);
if(dir==NULL)
{
printf("Can not open %s\n",buf);
return 0;
}
n = strlen(buf);
if (buf[n-1] != '/') {
strcat(buf, "/");
n++;
}
while((pdir=readdir(dir))!=NULL)
{
strcat(buf, pdir->d_name);
if(stat(buf,&st)==0)
{
if(st.st_mode&S_IFREG)
type=0;
else if(st.st_mode&S_IFDIR)
type=1;
else if(st.st_mode&S_IFLNK)
type=2;
else type=4;
printf("%-10s%-20s%7d\n",c_type[type],pdir->d_name,(int)st.st_size);
}
else
printf("%-20s%-10d%-10d\n",pdir->d_name,st.st_mode,errno);
bzero(&st,sizeof(struct stat));
buf[n]='\0';
}
closedir(dir);
return 0;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构