230505作业

fork函数
230505作业_第1张图片
fork函数前定义变量,虚拟地址相同,物理地址不同
fork函数后父进程定义变量,子进程中调用编译无法通过
fork函数后子函数定义变量,父进程中调用编译无法通过

实现打开目录下所有文件
main.c

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
char getfiletype(mode_t m)
{
	char flag;
	if(S_ISREG(m))
	{
		flag ='-';
	}else if(S_ISDIR(m))
	{
		flag ='d';
	}else if(S_ISCHR(m))
	{
		flag = 'c';
	}else if(S_ISBLK(m))
	{
		flag = 'b';
	}else if(S_ISFIFO(m))
	{
		flag = 'p';
	}else if(S_ISLNK(m))
	{
		flag = 'l';
	}else if(S_ISSOCK(m))
	{
		flag = 's';
	}
	putchar(flag);
	return flag;
}
void getfileper(mode_t m)
{
	if(0400 & m)
		putchar('r');
	else
		putchar('-');	
	if(0200 & m)
		putchar('w');
	else
		putchar('-');
	if(0100 & m)
		putchar('x');
	else
		putchar('-');
	if(0040 & m)
		putchar('r');
	else
		putchar('-');	
	if(0020 & m)
		putchar('w');
	else
		putchar('-');
	if(0010 & m)
		putchar('x');
	else
		putchar('-');
	if(0004 & m)
		putchar('r');
	else
		putchar('-');	
	if(0002 & m)
		putchar('w');
	else
		putchar('-');
	if(0001 & m)
		putchar('x');
	else
		putchar('-');
}
char getfilemessage(char *filename,int level)
{
	int i;
	for(i=0;i<level;i++)
	{
		putchar(' ');
	}
	struct stat buf;
	int a= stat(filename,&buf);
	char flag = getfiletype(buf.st_mode);
	getfileper(buf.st_mode);
	printf(" %d",buf.st_nlink);
	struct passwd *pass_user = getpwuid(buf.st_uid);
	printf(" %s",pass_user->pw_name);
	struct group *grp =getgrgid(buf.st_gid);
	printf(" %s",grp->gr_name);
	printf(" %ld",buf.st_size);
	struct tm* up_tm=localtime(&buf.st_atime);
	printf(" %02d",up_tm->tm_mon);
	printf(" %02d",up_tm->tm_mday);
	printf(" %02d",up_tm->tm_hour);	
	printf(":%02d",up_tm->tm_min);
	printf(" %s\n",filename);
	return flag;
}
void myopendir(char *dir_name,int level)
{
	char dir_file_name[1024]={0};
	DIR* dp =opendir(dir_name);
	if (NULL==dp)
	{
		perror("opendir");
		return ;
	}
	struct dirent* p=NULL;
	while(1)
	{
		bzero(dir_file_name,strlen(dir_file_name));
		strcpy(dir_file_name,dir_name);
		p = readdir(dp);
		if(p==NULL)
		{
			break;
		}
		if(*(p->d_name)!='.')
		{
			strcat(dir_file_name,p->d_name);
			char flag = getfilemessage(dir_file_name,level);
			if(flag=='d')
			{
				strcat(dir_file_name,"/");
				myopendir(dir_file_name,level+1);
			}
		}
	}
	if(closedir(dp)<0)
		perror("closedir");
	return ;
}
int main(int argc, const char *argv[])
{	int level=0;
	myopendir("/home/linux/gcc2023/",level);
	putchar(10);
	return 0;
}

你可能感兴趣的:(c++,数据结构,算法)