scandir函数的用法
时间: 2023-10-15 11:07:18 浏览: 122
`scandir` 函数是一个C标准库函数,用于遍历目录,返回指向目录中文件名的指针数组。
函数原型如下:
```
int scandir(const char *dirp, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **, const struct dirent **));
```
其中,参数解释如下:
- `dirp`:需要扫描的目录路径。
- `namelist`:输出参数,指向一个指针数组,该数组存储了指向目录中每个文件的指针。这个指针数组需要由调用者分配内存,并且需要在使用完后释放内存。函数成功执行后,返回符合条件的文件数目。
- `filter`:指向一个函数,用于过滤需要返回的文件。如果传入 `NULL`,则返回所有文件。
- `compar`:指向一个函数,用于排序文件名。如果传入 `NULL`,则不排序。
函数返回值为符合条件的文件数目。
下面是一个示例代码,用于打印出目录下的所有文件名:
```c
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main(int argc, char const *argv[]) {
struct dirent **namelist;
int n;
if (argc != 2) {
fprintf(stderr, "Usage: %s directory_name\n", argv[0]);
exit(EXIT_FAILURE);
}
n = scandir(argv[1], &namelist, NULL, alphasort);
if (n < 0) {
perror("scandir");
exit(EXIT_FAILURE);
}
for (int i = 0; i < n; i++) {
printf("%s\n", namelist[i]->d_name);
free(namelist[i]);
}
free(namelist);
return 0;
}
```
这个示例程序通过命令行传入需要扫描的目录,然后调用 `scandir` 函数,将返回的文件名指针数组打印出来。需要注意的是,我们需要手动释放 `namelist` 指向的每个文件名指针,以及最后释放 `namelist` 数组本身的内存。