在Linux系統中,readdir
函數用于讀取目錄中的條目。但是,readdir
本身并不直接提供inode號。要獲取目錄中文件的inode號,你需要結合其他函數和結構體來實現。
以下是一個使用C語言編寫的示例,展示了如何使用opendir
、readdir
和stat
函數來獲取目錄中文件的inode號:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
struct stat file_stat;
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
printf("File: %s, Inode: %lu\n", entry->d_name, (unsigned long)file_stat.st_ino);
}
closedir(dir);
return 0;
}
這個程序接受一個目錄作為命令行參數,然后使用opendir
打開該目錄。接著,它使用readdir
遍歷目錄中的每個條目。對于每個條目,我們使用snprintf
構建文件的完整路徑,然后使用stat
函數獲取文件的狀態信息。stat
結構體中的st_ino
字段包含了文件的inode號。最后,程序輸出文件名和對應的inode號。
編譯并運行這個程序,你將看到類似以下的輸出:
$ gcc inode_example.c -o inode_example
$ ./inode_example /path/to/directory
File: file1.txt, Inode: 1234567
File: file2.txt, Inode: 2345678
...
請注意,這個示例僅適用于Linux系統。在其他類Unix系統(如macOS)上,你可能需要包含不同的頭文件或使用不同的函數。