gpt4 book ai didi

C:检查文件类型。使用 lstat() 和宏不起作用

转载 作者:太空狗 更新时间:2023-10-29 14:56:38 25 4
gpt4 key购买 nike

我使用 opendir() 打开目录,然后使用 readdir() 和 lstat() 获取该目录中每个文件的统计信息。按照这个 manpage我写的代码并不像想象的那样工作。它确实列出了当前目录中的所有文件,但无论文件是常规文件、符号链接(symbolic link)还是目录,它都不会打印出来。

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

void main(){

char* folder="."; //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");
}

}

最佳答案

我知道这是多年后的事了,但为了后代你做错了:
@alk 是对的,st_mode 字段包含更多信息,例如文件类型、文件权限等
要提取文件类型,您可以在 st_mode 字段和文件类型掩码 S_IFMT 上按位执行。然后检查您想要的结果。 @Ernest Friedman-Hill 提到的宏就是这样做的。 swicth 更适合全面检查,即

对于一个简单的案例:

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

全面检查:

       struct stat st;
...

switch (st.st_mode & S_IFMT) {
case S_IFREG:
puts("|| regular file");
break;
case S_IFDIR:
puts("|| directory");
break;
case S_IFCHR:
puts("|| character device");
break;
case S_IFBLK:
puts("|| block device");
break;
case S_IFLNK:
puts("|| symbolic link");
break;
case S_IFIFO:
puts("|| pipe");
break;
case S_IFSOCK:
puts("|| socket");
break;
default:
puts("|| unknown");
}

关于C:检查文件类型。使用 lstat() 和宏不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7674287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com