zoukankan      html  css  js  c++  java
  • 自己动手写shell命令之ls -R1fF

        ls命令的R參数代表递归的列出全部子目录中的全部文件,1表示每一行仅仅显示一个文件或目录,f表示不排序即输出。F表示在每项的输出的最后依据其文件类型对应的加上*/=>@|字符。通过c语言实现ls -R1fF命令的效果,其源码例如以下:

    #include <stdio.h>
    #include <sys/types.h>
    #include <dirent.h>
    #include <sys/stat.h>
    #include <pwd.h>
    #include <grp.h>
    #include <string.h>
    
    void listdir(char *);
    char get_type(struct stat *);
    
    int main(int argc,char * argv[])
    {
    	if(argc == 1)
    		listdir(".");
    	else
    	{
    		int index = 1;
    		while(argc > 1)
    		{
    			listdir(argv[index]);
    			index++;
    			argc--;
    		}
    	}
    	return 0;
    }
    
    void listdir(char * dirname)
    {
    	DIR * dir;
    	struct stat info;
    	//char pointer[];
    	struct dirent * direntp;
    	if((dir = opendir(dirname)) != NULL)
    	{
    		printf("%s:
    ",dirname);
    		while((direntp = readdir(dir)) != NULL)
    		{
    			char absolute_pathname[255];
    			strcpy(absolute_pathname,dirname);
    			strcat(absolute_pathname,"/");
    			strcat(absolute_pathname,direntp->d_name);
    			lstat(absolute_pathname,&info);
    			printf("%s",direntp->d_name);
    			printf("%c
    ",get_type(&info));
    		}
    		printf("
    ");
    		rewinddir(dir);
    		while((direntp = readdir(dir)) != NULL)
    		{
    			if(strcmp(direntp->d_name,".") == 0 || strcmp(direntp->d_name,"..") == 0)
    				continue;
    			char absolute_pathname[255];
    			strcpy(absolute_pathname,dirname);
    			strcat(absolute_pathname,"/");
    			strcat(absolute_pathname,direntp->d_name);
    			lstat(absolute_pathname,&info);
    			if(S_ISDIR((&info)->st_mode))
    				listdir(absolute_pathname);
    		}
    	}
    }
    
    char get_type(struct stat * info)
    {
    	if(S_ISCHR(info->st_mode))
    		return '*';
    	if(S_ISDIR(info->st_mode))
    		return '/';
    	if(S_ISSOCK(info->st_mode))
    		return '=';
    	if(S_ISBLK(info->st_mode))
    		return '>';
    	if(S_ISLNK(info->st_mode))
    		return '@';
    	if(S_ISFIFO(info->st_mode))
    		return '|';
    	return ' ';
    }
    


    
    

  • 相关阅读:
    剑指offer--面试题14--收获
    剑指offer--面试题14
    剑指offer--面试题13
    剑指offer--面试题12
    剑指offer--面试题11
    高质量代码
    剑指offer--面试题10--相关
    剑指offer--面试题10
    位运算及其操作
    负数在计算机中的表示方法
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/6852654.html
Copyright © 2011-2022 走看看