zfzhuman123 发表于 2011-8-20 17:32:53

linux下边自己写的一个列出指定目录的c文件

只加了一个选项-d    {:7_158:}来列出目录,其它的选项我会在后续完善!

文件名   只列出当前目录
文件名 -d目录名   列出指定目录

运行环境LINUX

#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<dirent.h>
#include<sys/stat.h>



int main( int argc, char **argv )
{
       
        void list_dir ( char *);

        char         dir_name={0};
        int         list_dir_option = 0;
        while ( *++argv != NULL && **argv == '-' ) {
        /*
        **dispose the parameter next '-'
        **
        */
       
                switch (*++*argv) {
                        case 'd':
                                list_dir_option = 1;
                                break;
                        default :
                                printf("Parameter is error !\n");
                                exit (0);
                }
        }
        if ( *argv != NULL ) {
                strcpy ( dir_name, *argv );
                if ( list_dir_option )
                        list_dir ( dir_name );
                else
                        printf("Please input the parameter !\n");
        }
        else if ( *argv == NULL ) {
                if ( !list_dir_option )
                        list_dir (".");
                else
                        printf("Please input directory !\n");
        }
        else
                printf("Parameter is error !\n");
}




/*
**To list the directory
*/
void
list_dir ( char *dir_names )
{
        DIR         *dp;
        struct         dirent         *entry;
        struct         stat        statbuf;

        if ( ( dp = opendir( dir_names ) ) == NULL ) {
                fprintf ( stderr, "cannot open the directory:%s\n",dir_names );
                return;
        }
        chdir ( dir_names );        /*into directory*/
        /*
        **Loop ergdic this directory and list the dir or file
        */
        while ( ( entry = readdir ( dp ) ) != NULL ) {
                /*
                **To detection the dir
                */
                lstat (entry->d_name, &statbuf );
                if ( S_ISDIR (statbuf.st_mode) ) {
                        /*
                        **skip "." and ".."
                        */
                        if ( strcmp ( entry->d_name, "." ) == 0 ||
                             strcmp ( entry->d_name, "..") == 0 )
                                continue;
                        printf("%s/\t<----------------------\n", entry->d_name );
                }
                else
                        printf("%s\n", entry->d_name );
                }
        chdir ("..");
        closedir (dp);
}




zhangbin101004 发表于 2011-9-16 13:46:53

个人感觉是不是调用系统命令像:ll,la之类的也可以啊。。。
要是带参数的话就用strcat连接起来,注意空格的话也可以吧{:5_109:}
没有试过。。猜的。。。

我爱软件开发 发表于 2016-4-14 10:43:22

没学过
页: [1]
查看完整版本: linux下边自己写的一个列出指定目录的c文件