注意: stat 碰到链接,会追溯到源文件,穿透!!!lstat 并不会穿透。
stat结构体:
linux 命令 stat 执行结果:
注意三个时间的区别:
time_t st_atime;/* time of last access */ 文件被读,比如cat,open读等
time_t st_mtime;/* time of last modification */ 文件内容发生改变
time_t st_ctime;/* time of last status change */文件属性发生变化,比如大小,权限,硬连接数等
需求:使用stat实现实现 ls -l 的功能?
在实现的过程中需要获取用户名及组名,因此先看两个函数:
1)getpwuid
返回值
2)getgrgid
参数说明:
返回值
参数说明:
返回值
传入参数 timep 对应stat函数得到的结构体的秒数(time_t类型)。
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("./a.out filename\n");
return -1;
}
struct stat sb;
stat(argv[1], &sb);
char stmode[11] = {0};
memset(stmode, '-', sizeof(stmode)-1);
//解析文件属性
if (S_ISREG(sb.st_mode)) stmode[0] = '-'; //普通文件
if (S_ISDIR(sb.st_mode)) stmode[0] = 'd';
if (S_ISCHR(sb.st_mode)) stmode[0] = 'c';
if (S_ISBLK(sb.st_mode)) stmode[0] = 'b';
if (S_ISFIFO(sb.st_mode)) stmode[0] = 'p';
if (S_ISLNK(sb.st_mode)) stmode[0] = 'l';
if (S_ISSOCK(sb.st_mode)) stmode[0] = 's';
//解析权限
//user
if (sb.st_mode & S_IRUSR) stmode[1] = 'r';
if (sb.st_mode & S_IWUSR) stmode[2] = 'w';
if (sb.st_mode & S_IXUSR) stmode[3] = 'x';
//group
if (sb.st_mode & S_IRGRP) stmode[4] = 'r';
if (sb.st_mode & S_IWGRP) stmode[5] = 'w';
if (sb.st_mode & S_IXGRP) stmode[6] = 'x';
//other
if (sb.st_mode & S_IROTH) stmode[7] = 'r';
if (sb.st_mode & S_IWOTH) stmode[9] = 'w';
if (sb.st_mode & S_IXOTH) stmode[10] = 'x';
//分析 用户名,组名可以通过函数获得 getpwuid, getgrgid
//时间获取
struct tm *filetm = localtime(&sb.st_atim.tv_sec);
char timebuf[20] = {0};
sprintf(timebuf, "%d月 %d %02d:%02d", filetm->tm_mon+1, filetm->tm_mday, filetm->tm_hour, filetm->tm_min);
printf("%s %ld %s %s %ld %s %s\n", stmode, sb.st_nlink, getpwuid(sb.st_uid)->pw_name,
getgrgid(sb.st_gid)->gr_name, sb.st_size, timebuf, argv[1]);
return 0;
}
返回值
#include
#include
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("./a.out filename\n");
return -1;
}
if (access(argv[1], R_OK) == 0) printf("%s read ok!\n", argv[1]);
if (access(argv[1], W_OK) == 0) printf("%s write ok!\n", argv[1]);
if (access(argv[1], X_OK) == 0) printf("%s exe ok!\n", argv[1]);
if (access(argv[1], F_OK) == 0) printf("%s file exists!\n", argv[1]);
return 0;
}
参数说明:
返回值
参数说明:
返回值
参数解释:
返回值
参数解释:
返回值
函数参数:
返回值
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("./a.out filename\n");
return -1;
}
int fd = open(argv[1], O_WRONLY|O_CREAT, 0666);
//注意只要有进程在使用该文件,则unlink在该文件退出时删除该文件
unlink(argv[1]);
int ret = write(fd, "hello", 5);
if (ret > 0)
{
printf("write ok! %d\n", ret);
}
if (ret < 0)
{
perror("write err");
}
close(fd);
return 0;
}
函数参数:
返回值
参数说明:
返回值