【问题标题】:How to check for character files in a directory如何检查目录中的字符文件
【发布时间】:2021-09-14 21:15:36
【问题描述】:

我从this post得到这个代码

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

void main()
{
    char* folder="/dev/input";                                     //folder to open

    DIR* dir_p;
    struct dirent* dir_element;
    struct stat file_info;

    // open directory
    dir_p=opendir(folder);

    // show some info for each file in given directory
    while(dir_element = readdir(dir_p)) {

        lstat(dir_element->d_name, &file_info);          //getting a file stats

        puts(dir_element->d_name);                       // show current filename
        printf("file mode: %d\n", file_info.st_mode);

        // print what kind of file we are dealing with
        if (file_info.st_mode == S_IFDIR) puts("|| directory");
        if (file_info.st_mode == S_IFREG) puts("|| regular file");
        if (file_info.st_mode == S_IFLNK) puts("|| symbolic link");
        if (S_ISCHR(file_info.st_mode)) puts("|| character file");
    }
}

我对其进行了一些修改,以便它打印/dev/input 中的文件是否为字符文件。但是当我运行它时(即使使用 sudo),它只打印文件名、文件模式,没有别的。

【问题讨论】:

    标签: c linux operating-system file-attributes


    【解决方案1】:

    首先,file_info.st_mode 是位域,因此您应该检查是否使用 &amp; 运算符设置了各个位。

    也就是说,

    if (file_info.st_mode & S_IFDIR) puts("|| directory");
    

    但是,使用 S_ISXXX 宏会更明确,就像您在上一个中所做的那样。

    其次,dir_element-&gt;d_name 仅包含路径的基本名称。因此,在将其输入 lstat 之前,您应该在其前面加上 folder。如果你检查了lstat 的返回值,你就知道它没有成功。 所以你可以做类似的事情

    // 2 is for '/' and '\0'
    char *full_path = malloc(strlen(folder) + strlen(dir_element->d_name) + 2;
    // please do check if malloc failed
    // I'm sure FULL_PATH has sufficient memory, but use strncpy/strncat if in doubt
    strcpy(full_path, folder);
    strcat(full_path, "/");
    strcat(full_path, dir_element->d_name);
    lstat(full_path, &file_info);
    free(full_path);
    

    【讨论】:

      猜你喜欢
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 2017-10-30
      相关资源
      最近更新 更多