用c语言写打印系统目录“/etc”下所有的文件和子目录的名字。修改程序,要求使用scandir实现相同的功能,输出的内容按字母顺序排列,
时间: 2024-02-13 20:01:44 浏览: 32
好的,以下是使用普通的C语言实现的程序:
```c
#include <stdio.h>
#include <dirent.h>
#include <string.h>
void listdir(const char *path)
{
DIR *dir;
struct dirent *entry;
if ((dir = opendir(path)) == NULL)
return;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
printf("%s/%s\n", path, entry->d_name);
listdir(entry->d_name);
} else {
printf("%s/%s\n", path, entry->d_name);
}
}
closedir(dir);
}
int main()
{
listdir("/etc");
return 0;
}
```
接下来是使用`scandir`函数实现的程序:
```c
#include <stdio.h>
#include <dirent.h>
#include <string.h>
int alphaSort(const struct dirent **a, const struct dirent **b)
{
return strcasecmp((*a)->d_name, (*b)->d_name);
}
void listdir(const char *path)
{
struct dirent **namelist;
int n;
n = scandir(path, &namelist, NULL, alphaSort);
if (n == -1)
return;
while (n--) {
if (strcmp(namelist[n]->d_name, ".") == 0 || strcmp(namelist[n]->d_name, "..") == 0)
continue;
printf("%s/%s\n", path, namelist[n]->d_name);
if (namelist[n]->d_type == DT_DIR) {
listdir(namelist[n]->d_name);
}
}
free(namelist);
}
int main()
{
listdir("/etc");
return 0;
}
```
第二个程序使用了`scandir`函数来获取目录下的文件和子目录,并且还使用了一个比较函数`alphaSort`来按字母顺序排序结果。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)