[英]C Programming: ls function sort by file, executable and directory
到目前為止,我已經能夠按“文件”和“目錄”對它進行排序,但是我不知道如何檢查它是否為“可執行文件”。
我當時想將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);
}
您可以使用stat
來執行此操作。 您必須使用S_IXUSR
來檢查文件是否具有執行權限。 stat
手冊頁將為您提供更多信息。
if (stat(file, &sb) == 0 && sb.st_mode & S_IXUSR)
/* executable */
else
/* non-executable */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.