[英]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. 我当时想将CWD与“ /”和d_name串联,并将其存储到变量中,然后使用access()进行检查。但是我不知道如何。
#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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.