外部输入一个路径,要求显示该路径下,所有文件的详细信息,除了隐藏文件
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <error.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <grp.h>
#include <pwd.h>
#include <time.h>
char* get_file_permission(mode_t mode, char ptr[10], long size)
{
if (size < 10)
return NULL;
bzero(ptr, size);
char per[] = "rwx";
char buf[10] = "";
int i = 0;
for ( ; i < 9; i++)
{
if ((mode & (0400 >> i)) == 0)
{
buf[i] = '-';
}
else
{
buf[i] = per[i%3];
}
}
strcpy(ptr, buf);
return ptr;
}
char* get_file_type(mode_t m, char str[])
{
if(S_ISREG(m)) strcpy(str, "-");
else if (S_ISDIR(m)) strcpy(str, "d");
else if (S_ISCHR(m)) strcpy(str, "c");
else if (S_ISBLK(m)) strcpy(str, "b");
else if (S_ISFIFO(m)) strcpy(str, "p");
else if (S_ISLNK(m)) strcpy(str, "l");
else if (S_ISSOCK(m)) strcpy(str, "s");
return str;
}
char* get_file_uid(uid_t uid, char str[])
{
struct passwd* pwd = getpwuid(uid);
if(NULL == pwd)
{
perror("getpwuid");
return NULL;
}
strcpy(str, pwd->pw_name);
return str;
}
char* get_file_gid(gid_t gid, char str[])
{
struct group* grp = getgrgid(gid);
if(NULL == grp)
{
perror("getgrgid");
return NULL;
}
strcpy(str, grp->gr_name);
return str;
}
void time_trans(time_t time_sec)
{
struct tm* info = NULL;
info = localtime(&time_sec);
printf("%4d-%02d-%02d %02d:%02d:%02d ",\
info->tm_year+1900, info->tm_mon+1,info->tm_mday,\
info->tm_hour, info->tm_min, info->tm_sec);
}
void ttttime(char file_name[])
{
struct stat buf;
if (stat(file_name, &buf) < 0)
{
perror("stat");
return;
}
char str_type[5] = "";
get_file_type(buf.st_mode, str_type);
char perm[10] = "";
get_file_permission(buf.st_mode, perm, sizeof(perm));
char str_uid[32] = "";
get_file_uid(buf.st_uid, str_uid);
char str_gid[32] = "";
get_file_gid(buf.st_gid, str_gid);
printf("%s%s %lu %s %s %ld ", str_type, perm, buf.st_nlink, \
str_uid, str_gid, buf.st_size);
time_trans(buf.st_ctime);
}
int main(int argc, const char *argv[])
{
if (argc < 2)
{
fprintf(stderr,"请输入文件名:\n");
}
DIR* dp = opendir(argv[1]);
if(NULL == dp)
{
perror("opendir");
return -1;
}
int i = 0;
struct dirent* rp = NULL;
while(1)
{
rp = readdir(dp);
if(NULL == rp)
{
if(0 == error)
{
printf("目录读取完毕\n");
break;
}
else
{
perror("readdir");
return -1;
}
}
if ((rp->d_name)[0] != '.')
{
ttttime(rp->d_name);
printf("[%d] %s\n", ++i, rp->d_name);
}
}
if(closedir(dp) < 0)
{
perror("closedir");
return -1;
}
return 0;
}
孤儿进程:没有父进程的进程,父进程退出,子进程不退出。
int main()
{
pid_t cpid = fork();
if(cpid > 0)
{
return 0;
}
else if(0 == cpid)
{
while(1)
{
printf("this is child %d %d\n", getppid(), getpid());
sleep(1);
}
}
else
{
perror("fork");
return 0;
}
}
---------------------------------------
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
if(fork() == 0)
{
while(1)
{
printf("this is child %d %d\n", getppid(), getpid());
sleep(1);
}
}
return 0;
}
僵尸进程:父进程不退出,子进程退出。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c8c9b3afbae29ac241aa3665903152f2.png)