使用stat()和wordexp()在C中显示可执行文件和隐藏文件

时间:2015-02-28 22:56:17

标签: c

我是Linux C编程的新手,需要一些帮助,使用stat和wordexp函数显示可执行文件和隐藏文件。非常感谢。以下是我到目前为止的情况:

int main(int argc, char **argv)
{

    char fileName[60];

    char *pos;

    wordexp_t p;

    char **w;

    int i;

    struct stat st;

    fprintf(stdout,"Enter file name: ");
    fgets(fileName,sizeof(fileName),stdin);

    if((pos=rindex(fileName,'\n'))==(fileName+strlen(fileName)-1))
        *pos='\0';

    wordexp(fileName,&p,0);
    w = p.we_wordv;

    for(i = 0; i < p.we_wordc; i++)
    {
        printf("%s\n",w[i]);
        wordfree(&p);
    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

在Linux上,隐藏文件以点开头,因此您需要检查文件名的第一个字符。 可以通过检查文件模式来过滤可执行文件(您可以阅读更多相关信息here - 查找此结构的st_mode字段)。
下面是简单的应用程序,它列出了当前目录中的所有隐藏或可执行文件:

#include <dirent.h> 
#include <stdio.h> 
#include <string.h>
#include <sys/stat.h>

int main(void)
{
  DIR           *d;
  struct dirent *dir;
  struct stat buf;
  d = opendir(".");
  if (d)
    {
      while ((dir = readdir(d)) != NULL)
    {
      stat(dir->d_name, &buf);
      if ((strlen(dir->d_name) > && dir->d_name[0] == '.') || (buf.st_mode & S_IXGRP || buf.st_mode & S_IXUSR || buf.st_mode & S_IXOTH)
        printf("%s\n", dir->d_name);
    }

      closedir(d);
    }

  return(0);
}

你还应该记住两件事:

  • 目录通常具有可执行权限
  • linux中有两个特殊目录:&#39;。&#39;和&#39; ..&#39; 但我不知道你是否会过滤它。