使用stat来检查文件在C中是否可执行

问题描述 投票:11回答:3

对于家庭作业,我必须编写一个C程序,它必须做的一件事就是检查文件是否存在以及它是否可由所有者执行。

使用(stat(path[j], &sb) >= 0我能够看到路径[j]指示的文件是否存在。

我查看了man page,stackoverflow上的很多问题和答案,以及几个网站,但我无法完全理解如何使用stat检查文件是否可执行。我认为它会像((stat(path[j], &sb) >= 0) && (sb.st_mode > 0) && (S_IEXEC)一样简单,但据我测试它,它似乎忽略了这些文件不可执行的事实。

我认为也许统计数据不像我认为的那样有效。假设我使用stat,我该怎么办呢?

c stat
3个回答
13
投票

你确实可以使用stat来做到这一点。您只需使用S_IXUSRS_IEXECS_IXUSR的旧同义词)来检查您是否具有执行权限。按位AND运算符(&)检查是否设置了S_IXUSR的位。

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

例:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    if (argc > 1) {
        struct stat sb;
        printf("%s is%s executable.\n", argv[1], stat(argv[1], &sb) == 0 &&
                                                 sb.st_mode & S_IXUSR ? 
                                                 "" : " not");
    }
    return 0;
}   

4
投票

尝试:

((stat(path[j], &sb) >= 0) && (sb.st_mode > 0) && (S_IEXEC & sb.st_mode)


0
投票

我们可以利用随文件(1)实用程序一起提供的libmagic.so库。它可以检测所有可执行文件,如ELF,bash / python / perl脚本等

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "magic.h"

int
main(int argc, char **argv)
{
   struct magic_set *ms;
   const char *result;
   char *desired;
   size_t desired_len;
   int i;
   FILE *fp;

   ms = magic_open(MAGIC_RAW);
   if (ms == NULL) {
      (void)fprintf(stderr, "ERROR opening MAGIC_NONE: out of memory\n");
      return -1;
   }
   if (magic_load(ms, NULL) == -1) {
      (void)fprintf(stderr, "ERROR loading with NULL file: %s\n", magic_error(ms));
      return 11;
   }

   if (argc > 1) {
      if (argc != 2) {
         (void)fprintf(stderr, "Usage:  ./a.out </path/to/file>\n");
      } else {
         if ((result = magic_file(ms, argv[1])) == NULL) {
            (void)fprintf(stderr, "ERROR loading file %s: %s\n", argv[1], magic_error(ms));
            return -1;
         } else {
             if (strstr(result, (const char *)"executable")) {
                printf("%s: is executable\n", argv[1], result);
             }
         }
      }
   }
   magic_close(ms);
   return 0;
}

$ gcc test.c -I / path / to / magic.h /usr/lib/libmagic.so.1

./a.out / bin / ls

./a.out a.out

./a.out test.c

© www.soinside.com 2019 - 2024. All rights reserved.