[英]Using stat() and wordexp() to display executable and hidden files in C
[英]Using stat to check if a file is executable in C
對於家庭作業,我必須編寫一個C程序,它必須做的一件事就是檢查文件是否存在以及它是否可由所有者執行。
使用(stat(path[j], &sb) >= 0
我能看到路徑[j]指示的文件是否存在。
我查看了man page,stackoverflow上的很多問題和答案,以及幾個網站,但我無法完全理解如何使用stat檢查文件是否可執行。 我認為它會像((stat(path[j], &sb) >= 0) && (sb.st_mode > 0) && (S_IEXEC)
但據我所知,通過測試它似乎忽略了這些文件不可執行的事實。
我認為也許統計數據不像我認為的那樣有效。 假設我使用stat,我該怎么辦呢?
你確實可以使用stat
來做到這一點。 你只需要使用S_IXUSR
( S_IEXEC
是一個古老的代名詞S_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;
}
嘗試:
((stat(path[j], &sb) >= 0) && (sb.st_mode > 0) && (S_IEXEC & sb.st_mode)
我們可以利用隨文件(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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.