ubuntu readdir如何获取文件属性信息
导读:在Ubuntu中,你可以使用readdir函数来读取目录中的文件和子目录。但是,readdir本身并不直接提供文件属性信息。要获取文件属性信息,你需要结合其他函数,如stat。 以下是一个简单的示例,展示了如何使用readdir和stat函...
在Ubuntu中,你可以使用readdir函数来读取目录中的文件和子目录。但是,readdir本身并不直接提供文件属性信息。要获取文件属性信息,你需要结合其他函数,如stat。
以下是一个简单的示例,展示了如何使用readdir和stat函数获取目录中的文件属性信息:
#include <
stdio.h>
#include <
stdlib.h>
#include <
dirent.h>
#include <
sys/stat.h>
#include <
string.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
// 打开目录
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
// 读取目录中的条目
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录(".")和上级目录("..")
if (strcmp(entry->
d_name, ".") == 0 || strcmp(entry->
d_name, "..") == 0) {
continue;
}
// 构建文件的完整路径
char file_path[1024];
snprintf(file_path, sizeof(file_path), "./%s", entry->
d_name);
// 获取文件属性信息
if (stat(file_path, &
file_stat) == -1) {
perror("stat");
continue;
}
// 输出文件名和文件类型
printf("File name: %s\n", entry->
d_name);
printf("File type: ");
if (S_ISREG(file_stat.st_mode)) {
printf("Regular file\n");
}
else if (S_ISDIR(file_stat.st_mode)) {
printf("Directory\n");
}
else if (S_ISCHR(file_stat.st_mode)) {
printf("Character device\n");
}
else if (S_ISBLK(file_stat.st_mode)) {
printf("Block device\n");
}
else if (S_ISFIFO(file_stat.st_mode)) {
printf("FIFO\n");
}
else if (S_ISSOCK(file_stat.st_mode)) {
printf("Socket\n");
}
else {
printf("Other\n");
}
// 输出其他文件属性信息
printf("Size: %ld bytes\n", file_stat.st_size);
printf("Last modified: %s", ctime(&
file_stat.st_mtime));
}
// 关闭目录
closedir(dir);
return EXIT_SUCCESS;
}
这个示例程序会打开当前目录(“.”),然后使用readdir函数读取目录中的所有条目。对于每个条目,它使用stat函数获取文件属性信息,并输出文件名、文件类型和其他属性信息。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: ubuntu readdir如何获取文件属性信息
本文地址: https://pptw.com/jishu/748164.html
