枚举C中的可执行文件
Enumerating executable files in C
我正在尝试仅枚举设置了执行 (+x) 位的文件。我的代码似乎列出了所有文件。它似乎还枚举目录和我不想要的上述目录。示例:
..
should_not_be_executable.sh
.
有没有办法过滤“..”和“.”没有 strstr()?这是我的代码
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int
main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("/tmp/hi");
if (dp != NULL)
{
while (ep = readdir (dp))
{
struct stat sb;
if ((stat(ep->d_name, &sb) >= 0) && (sb.st_mode > 0) && (S_IEXEC & sb.st_mode));
puts(ep->d_name);
}
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
return 0;
}
提前致谢
ep->d_name
仅包含目录条目的相对路径名。所以你应该在调用 stat(2)
之前将当前工作目录更改为 /tmp/hi
if (chdir("/bin") != 0)
{
perror("chdir()");
exit(EXIT_FAILURE);
}
/* ... */
if (stat(ep->d_name, &sb) == -1)
{
perror("stat()");
exit(EXIT_FAILURE);
}
如@Andrew Medico 的评论所述,删除 if
行末尾的额外 ;
以避免不必要地打印 puts()
行。
readdir()
returns 到达目录末尾时的 NULL
指针,因此您应该按如下方式重写 while 循环以抑制编译器警告:
while (NULL != (ep = readdir(dp)))
{
/* loop */
}
为了避免打印 .
和 ..
,在 while
正文中使用这样的 if
条件:
if ((strcmp(ep->d_name, ".") == 0) || (strcmp(ep->d_name, "..") == 0))
continue;
if ((stat(ep->d_name, &sb) >= 0) && (sb.st_mode > 0) && (S_IEXEC & sb.st_mode))
if (!S_ISDIR(sb.st_mode))
puts(ep->d_name);
同样,你可以使用S_ISDIR(m)
宏来判断当前条目是否为目录,并选择不打印。
我正在尝试仅枚举设置了执行 (+x) 位的文件。我的代码似乎列出了所有文件。它似乎还枚举目录和我不想要的上述目录。示例:
..
should_not_be_executable.sh
.
有没有办法过滤“..”和“.”没有 strstr()?这是我的代码
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int
main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("/tmp/hi");
if (dp != NULL)
{
while (ep = readdir (dp))
{
struct stat sb;
if ((stat(ep->d_name, &sb) >= 0) && (sb.st_mode > 0) && (S_IEXEC & sb.st_mode));
puts(ep->d_name);
}
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
return 0;
}
提前致谢
ep->d_name
仅包含目录条目的相对路径名。所以你应该在调用 stat(2)
/tmp/hi
if (chdir("/bin") != 0)
{
perror("chdir()");
exit(EXIT_FAILURE);
}
/* ... */
if (stat(ep->d_name, &sb) == -1)
{
perror("stat()");
exit(EXIT_FAILURE);
}
如@Andrew Medico 的评论所述,删除 if
行末尾的额外 ;
以避免不必要地打印 puts()
行。
readdir()
returns 到达目录末尾时的 NULL
指针,因此您应该按如下方式重写 while 循环以抑制编译器警告:
while (NULL != (ep = readdir(dp)))
{
/* loop */
}
为了避免打印 .
和 ..
,在 while
正文中使用这样的 if
条件:
if ((strcmp(ep->d_name, ".") == 0) || (strcmp(ep->d_name, "..") == 0))
continue;
if ((stat(ep->d_name, &sb) >= 0) && (sb.st_mode > 0) && (S_IEXEC & sb.st_mode))
if (!S_ISDIR(sb.st_mode))
puts(ep->d_name);
同样,你可以使用S_ISDIR(m)
宏来判断当前条目是否为目录,并选择不打印。