简体   繁体   中英

C Programming: ls function sort by file, executable and directory

I have been able to sort it by "File" and "Directory" so far, but I don't know how to check whether it is "Executable."

I was thinking of concatenating my CWD with "/" and d_name and store it into a variable, and check it with access().But I have no idea how.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<dirent.h>
#include<unistd.h>


int main(int argc,char **argv)
{
    char *buf;
    char cwd[PATH_MAX+1];

    //Print the PWD
    getcwd(cwd,100);
    printf("Current Directory: %s \n",cwd);

    //Print the Directory Listing
    printf("***Directory Listing as follows***\n");

    struct dirent **namelist;
    int n;

    if(argc < 1)
    {
        exit(EXIT_FAILURE);
    }
    else if (argc == 1)
    {
        n=scandir(".",&namelist,NULL,alphasort);
    }
    else
    {
        n = scandir(argv[1], &namelist, NULL, alphasort);
    }
    if(n < 0)
    {
        perror("scandir");
        exit(EXIT_FAILURE);
    }
    else
    {
        while (n--)
        {
            if(namelist[n]->d_name[0] !=46) /*Exclude d_name starts with "." (ASCII) */
            {
                if(namelist[n]->d_type ==DT_REG) /*Check whether it's REGULAR FILE*/
                {
                   /*if( access(path_and_name,X_OK) != 1 )
                    {
                    printf("Executable, \n %s \n",cwd);
                    }
                    */

                printf("File: ");
                }
                if(namelist[n]->d_type ==DT_DIR) /*Check whether it's DIRECTORY*/
                {
                printf("Directory: ");
                }
                printf("%s\n",namelist[n]->d_name);
                free(namelist[n]);
            }
       }
        free(namelist);
    }
    exit(EXIT_SUCCESS);
}

You can use stat to do this. You have to use S_IXUSR to check if file has execute permission. The stat man page will give you more information.

if (stat(file, &sb) == 0 && sb.st_mode & S_IXUSR) 
    /* executable */
else  
    /* non-executable */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM