繁体   English   中英

如何在c中确定linux中的目录或文件

[英]how to determine directory or file in linux in c

我只想打印文件名而不打印目录名。 所以,我实现了这个功能

void list_file(char* directory){
  DIR *d;
  struct dirent *dir;
  d = opendir(directory);
  if (d)
  {
    while ((dir = readdir(d)) != NULL)
    {
        printf("%c", dir->d_name[(int)strlen(dir->d_name)]);
        if(dir->d_name[(int)strlen(dir->d_name)-2] != '/')
            printf("%s\n", dir->d_name);
    }

    closedir(d);
  }
}

我检查了目录名称是否以“/”字符结尾。 因此,我检查了名称末尾是否有“/”字符,不要打印该名称,但是当我运行该函数时,所有这些都打印在选定目录中?

你能指导我如何检查目录名称的结尾吗?

您正在寻找的是stat或其变体之一。 具体看struct statst_mode字段。 您感兴趣的宏是S_ISDIR(x)

在下面找到您修改后的代码来演示您想要的内容:

void list_file(char* directory) {
  DIR *d;
  struct dirent *dir;
  int dir_len = strlen(directory);
  char* path = malloc(dir_len + NAME_MAX + 2); // +2, 1 for '/' and 1 for '\0'
  if(path == NULL) {
    fprintf(stderr, "malloc failed\n");
    return;
  }
  strcpy(path, directory);
  if(path[dir_len-1] != '/') {
    path[dir_len] = '/';
    dir_len++;
  }
  d = opendir(directory);
  if (d) {
    while ((dir = readdir(d)) != NULL)
    {
      struct stat buf;
      strcpy(&path[dir_len], dir->d_name);
      if(stat(path, &buf) < 0) {
        fprintf(stderr, "error\n");
      }
      else {if(!S_ISDIR(buf.st_mode)) {
          printf("%s\n", dir->d_name);
        }
      }
    }

    closedir(d);
  }
  free(path);
}

我已经删除了您的第一个打印,因为它正在打印字符串的空终止字符。

更新:

正如评论中所指出的,因为我们正在处理 Linux,您可以使用struct direntd_type字段(它不是POSIX 的一部分,而是Linux 的一部分)。

话虽如此,代码如下。

void list_file(char* directory){
  DIR *d;
  struct dirent *dir;

  d = opendir(directory);
  if (d) {
    while ((dir = readdir(d)) != NULL)
    {
      struct stat buf;
      if(dir->d_type == DT_DIR) {
         printf("%s\n", dir->d_name);
      }
    }

    closedir(d);
  }
}

它更干净,不需要malloc

Linux 上的man readdir

On Linux, the dirent structure is defined as follows:

       struct dirent {
           ino_t          d_ino;       /* inode number */
           off_t          d_off;       /* not an offset; see NOTES */
           unsigned short d_reclen;    /* length of this record */
           unsigned char  d_type;      /* type of file; not supported
                                          by all filesystem types */
           char           d_name[256]; /* filename */
       };
[...]
Other than Linux, the d_type field is available mainly only on BSD sys‐
tems.   This  field  makes  it possible to avoid the expense of calling
lstat(2) if further actions depend on the type of  the  file.   If  the
_BSD_SOURCE  feature test macro is defined, then glibc defines the fol‐
lowing macro constants for the value returned in d_type:

   DT_BLK      This is a block device.

   DT_CHR      This is a character device.

   DT_DIR      This is a directory.

   DT_FIFO     This is a named pipe (FIFO).

   DT_LNK      This is a symbolic link.

   DT_REG      This is a regular file.

   DT_SOCK     This is a UNIX domain socket.

   DT_UNKNOWN  The file type is unknown.

根据需要尝试使用stat, fstat, lstat 这用于获取文件状态。

用法:

int stat(const char *path, struct stat *buf);
int fstat(int fd, struct stat *buf);
int lstat(const char *path, struct stat *buf);
  1. stat() 统计path指向的文件并填充buf。

  2. lstat() 与 stat() 相同,除了如果 path 是符号链接,则链接本身是 stat-ed,而不是它引用的文件。

  3. fstat() 与 stat() 相同,除了要统计的文件由文件描述符 fd 指定。

它们都返回一个stat结构,其中包含以下字段:

struct stat {
               dev_t     st_dev;     /* ID of device containing file */
               ino_t     st_ino;     /* inode number */
               mode_t    st_mode;    /* protection */
               nlink_t   st_nlink;   /* number of hard links */
               uid_t     st_uid;     /* user ID of owner */
               gid_t     st_gid;     /* group ID of owner */
               dev_t     st_rdev;    /* device ID (if special file) */
               off_t     st_size;    /* total size, in bytes */
               blksize_t st_blksize; /* blocksize for filesystem I/O */
               blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
               time_t    st_atime;   /* time of last access */
               time_t    st_mtime;   /* time of last modification */
               time_t    st_ctime;   /* time of last status change */
           };

从这个尝试做:

buf.st_mode & S_IFMT                #assuming you have defined struct stat buf;

将该值与S_IFDIR进行比较以检查它是否为目录。

有关更多信息,请参阅: man 2 stat

使用struct stat也可以帮助您,因为它包含文件的许多不同信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM