作业1
将指定目录下所有文件的属性显示出来,类似 ls -l 一个指定目录
打开目录,
读取目录中的文件名
将路径和文件名拼接
传入给stat获取文件属性
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <dirent.h>
#include <errno.h>
int get_fileMsg(struct stat buf, char* path);
//获取文件权限
void get_filePermission(mode_t m)
{
char buf[] = "rwx";
for(int i=0; i<9; i++)
{
if( (m & (0400>>i)) == 0)
{
putchar('-');
continue;
}
printf("%c", buf[i%3]);
}
return;
}
//获取文件类型
char get_fileType(mode_t m)
{
switch(m & S_IFMT)
{
case S_IFSOCK: return 's'; break;
case S_IFLNK: return 'l'; break;
case S_IFREG: return '-'; break;
case S_IFDIR: return 'd'; break;
}
}
int main(int argc, const char *argv[])
{
char path[20] = "";
char fin_path[300] = "";
char type = 0;
struct stat buf;
DIR* dp = NULL;
struct dirent* rp = NULL;
//从终端获取一个文件的路径以及名字
printf("请输入>>> ");
scanf("%s", path);
getchar();
//判断文件是否是目录文件
if(stat(path, &buf) < 0)
{
perror("stat");
return -1;
}
type = get_fileType(buf.st_mode);
if('d' == type)
{
//文件是一个目录文件,则需要打开目录,
dp = opendir(path);
if(NULL == dp)
{
perror("opendir");
return -1;
}
while(1)
{
//循环读取目录
rp = readdir(dp);
if(NULL == rp)
{
if(0 == errno)
{
printf("目录读取完毕\n");
break;
}
else
{
perror("readdir");
return -1;
}
}
//将读取到的文件名传入stat获取属性
sprintf(fin_path, "%s%s", path, rp->d_name);
if(stat(fin_path, &buf) < 0)
{
perror("stat");
return -1;
}
get_fileMsg(buf, rp->d_name);
}
}
else
{
get_fileMsg(buf, path);
}
return 0;
}
int get_fileMsg(struct stat buf, char* path)
{
//文件的类型和权限
char type = get_fileType(buf.st_mode);
printf("%c", type);
get_filePermission(buf.st_mode);
//文件的硬链接数
printf(" %ld", buf.st_nlink);
//文件的所属用户
//将uid转换成名字
struct passwd* pwd = getpwuid(buf.st_uid);
if(NULL == pwd)
{
perror("getpwuid");
return -1;
}
printf(" %s", pwd->pw_name);
//文件所属组用户
//将gid转换成名字
struct group* grp = getgrgid(buf.st_gid);
if(NULL == grp)
{
perror("getgrgid");
return -1;
}
printf(" %s", grp->gr_name);
//文件大小
printf(" %ld", buf.st_size);
//文件的修改时间
printf(" time: %ld ", buf.st_ctime);
//文件的名字
printf(" %s\n", path);
return 0;
}
现象
作业2 XMIND