我有一个文件路径,如何检查它是否可执行?(Unix,C++)
访问(2):
#include <unistd.h>
if (! access (path_name, X_OK))
// executable
调用stat(2)函数时,填充结构体的开销较大。除非你需要那些额外的信息。
access()
。 - David R Tribble检查权限(状态)位。
#include <sys/stat.h>
bool can_exec(const char *file)
{
struct stat st;
if (stat(file, &st) < 0)
return false;
if ((st.st_mode & S_IEXEC) != 0)
return true;
return false;
}
#include <unistd.h>
#include <stdio.h>
int can_exec(const char *file)
{
return !access(file, X_OK);
}
int main(int ac, char **av) {
while(av++,--ac) {
printf("%s: %s executable\n", *av, can_exec(*av)?"IS":"IS NOT");
}
}
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int is_executable_file(char const * file_path)
{
struct stat sb;
return
(stat(file_path, &sb) == 0) &&
S_ISREG(sb.st_mode) &&
(access(file_path, X_OK) == 0);
}
access()
呢?因为它可以接受可以递归的目录,而这些目录并非可执行文件。#include <filesystem>
#include <unistd.h>
int is_executable_file(const std::filesystem::path& file_path)
{
return
std::filesystem::is_regular_file(file_path) &&
(access(file_path.c_str(), X_OK) == 0);
}
stat()
? - Jesper Juhl