/*-----用stat函数得到文件信息,并用函数转化为文本输出,就跟蠢罩ls命令一样-----*/
/*----------注释我写得很详细,望采纳-----------*/
#include <sys/types.h>/*-----这三个头文件一定要有-*/
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void mode_to_letter(int mode,char *str)
{
/*-------这个函数用来把模式值转化为字符串------*/
str[0]='-'/*------这里的S_*****都是宏定义,用来判断模式属性-*/
if(S_ISDIR(mode)) str[0]='d'/*-文件夹-*/
if(S_ISCHR(mode)) str[0]='c'/*-字符设备-*/
if(S_ISBLK(mode)) str[0]='b'/*-块设备-*/
if(mode &S_IRUSR) str[1]='r'/*--用户的三个属性-*/
else str[1]='-'
if(mode &S_IWUSR) str[2]='w'
else str[2]='-'
if(mode &S_IXUSR) str[3]='x'
else str[3]='-'
if(mode &S_IRGRP) str[4]='r'/*--组的三个属颤银性-*/
else str[4]='-'
if(mode &S_IWGRP) str[5]='w'
else str[5]='-'
if(mode &S_IXGRP) str[6]='x'
else str[6]='-'
if(mode &S_IROTH) str[7]='r'/*-其他带洞闹人的三个属性-*/
else str[7]='-'
if(mode &S_IWOTH) str[8]='w'
else str[8]='-'
if(mode &S_IXOTH) str[9]='x'
else str[9]='-'
str[10]='\0'
}
int main(int argc,char *argv[])
{
struct stat sb/*- 定义stat结构--*/
char str[12]
if(argc!=2){
fprintf(stderr,"Usage: %s <pathname>\n",argv[0])
exit(EXIT_FAILURE)
}
if(stat(argv[1],&sb)==-1){/*-stat函数,详情请 man 2 stat 查看 -*/
perror("stat")
exit(EXIT_FAILURE)
}
printf("Mode:%lo(octal)\n",(unsigned long)sb.st_mode)
mode_to_letter(sb.st_mode,str)
printf("Mode:%s\n",str)
return 0
}
调用好没 stat(),fstat(), lstat(), 等函数时,需要包含 #include <sys/stat.h>头文件,它包含了要用到一些数据类型,结构类型。例如:dev_t st_dev ID of device containing file
ino_t st_ino file serial number
mode_tst_modemode of file (see below)
nlink_t st_nlink number of links to the file
uid_t st_uid user ID of file
gid_t st_gid group ID of file
dev_t st_rdevdevice ID (if file is character or block special)
off_t st_sizefile size in bytes (if file is a regular file)
time_tst_atime time of last access
time_tst_mtime time of last data modification
time_tst_ctime time of last status change
用法:包含头文件:
#include <sys/types.h>
#include <sys/stat.h>
程蠢袜禅序里,需要时可调用下列函数,下面是函数原型
intchmod(const char *, mode_t)
intfchmod(int, mode_t)
intfstat(int, struct stat *)
intlstat(const char *, struct stat *)
intmkdir(const char *, mode_t)
intmkfifo(const char *, mode_t)
intmknod(const char *, mode_t, dev_t)
intstat(const char *, struct stat *)
int main(){
具带尘体的调用语句和程序可写在这里
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)