stat函数:获取文件信息
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *pathname, struct stat *buf);
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for filesystem I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
}
getpwuid函数:解码所有者信息(解析struct stat中的st_uid数据)
#include <sys/types.h>
#include <pwd.h>
struct passwd *getpwuid(uid_t uid);
struct passwd {
char *pw_name; /* username */
char *pw_passwd; /* user password */
uid_t pw_uid; /* user ID */
gid_t pw_gid; /* group ID */
char *pw_gecos; /* user information */
char *pw_dir; /* home directory */
char *pw_shell; /* shell program */
};
getgrgid函数:解码所属组信息(解析struct stat中的 st_gid数据)
#include <sys/types.h>
#include <grp.h>
struct group *getgrgid(gid_t gid);
struct group {
char *gr_name; /* group name */
char *gr_passwd; /* group password */
gid_t gr_gid; /* group ID */
char **gr_mem; /* NULL-terminated array of pointers
to names of group members */
};
localtime函数:解码上次访问时间信息 (解析struct stat中的 st_atime数据)
#include <time.h>
struct tm *localtime(const time_t *timep);
struct tm {
int tm_sec; /* Seconds (0-60) */
int tm_min; /* Minutes (0-59) */
int tm_hour; /* Hours (0-23) */
int tm_mday; /* Day of the month (1-31) */
int tm_mon; /* Month (0-11) */
int tm_year; /* Year - 1900 */
int tm_wday; /* Day of the week (0-6, Sunday = 0) */
int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */
int tm_isdst; /* Daylight saving time */
};
使用stat函数实现ls -l的功能例程:
//使用stat函数实现ls -l的功能
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
int main(int argc,const char * argv[])
{
struct stat info;
stat(argv[1],&info);
//打印类型,权限
switch(info.st_mode & S_IFMT)
{
case S_IFREG:printf("-");break;
case S_IFDIR:printf("d");break;
case S_IFLNK:printf("l");break;
case S_IFCHR:printf("c");break;
case S_IFBLK:printf("b");break;
case S_IFIFO:printf("p");break;
case S_IFSOCK:printf("s");break;
}
char rwx[]={
'r','w','x'};
for(int i=0; i<10; i++)
{
printf("%c",info.st_mode & (0400>>i) ? rwx[i%3] : '-');
}
//打印所有者,所属组
struct passwd *pswd;
pswd=getpwuid(info.st_uid);
printf(" %s",pswd->pw_name);
struct group *grp;
grp=getgrgid(info.st_gid);
printf(" %s",grp->gr_name);
//打印文件大小
printf(" %ld ",info.st_size);
//打印最近时间
struct tm *atime;
atime = localtime(&info.st_mtime);
printf("%d-%d-%d %d:%d "
,atime->tm_year+1900
,atime->tm_mon+1,atime->tm_mday
,atime->tm_hour,atime->tm_min);
//打印文件名
printf(" %s\n",argv[1]);
return 0;
}
编译运行 :