#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <dirent.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #define MAX_FILE_NUM 128 #define MAX_PATH_LEN 128 char file_path[MAX_FILE_NUM][MAX_PATH_LEN]; char *pFilePath[MAX_FILE_NUM]; int total_file_num = 0; //排序文件 void SortFilePath(void) { char *pTemp; int i, j, k; for (i=0; i<MAX_FILE_NUM && file_path[i]; i++) pFilePath[i] = file_path[i]; for (i=0; i<total_file_num-1; i++) { if (pFilePath[i] == 0) break; k = i; for (j=i+1; j<total_file_num; j++) if (strcmp(pFilePath[k], pFilePath[j]) > 0) k = j; if (k != i) { pTemp = pFilePath[i]; pFilePath[i] = pFilePath[k]; pFilePath[k] = pTemp; } } } //判断文件路径是否存在 int is_path_exist(const char *root) { DIR *dir; dir = opendir(root); if (dir == NULL){ printf("error!\n"); return -1; } closedir(dir); return 0; } //返回该目录下文件的个数 int get_file_path(const char *root) { int count, status, len; DIR *dir; struct dirent *ptr; dir = opendir(root); if (dir == NULL) { printf("fail to open dir:%s\n", root); return -1; } count=0; chdir(root); while ((ptr = readdir(dir)) != NULL) { if (strcmp(ptr->d_name,".") ==0 || strcmp(ptr->d_name,"..")==0) //后面还可以加一个选项,排除文件夹 continue; strcpy(file_path[count], ptr->d_name); printf("mount: %s success!\n",ptr->d_name); count++; if (count == MAX_FILE_NUM) break; } closedir(dir); return count; } int main(void) { char *name = "C:/Users/se0803/Desktop/test"; struct dirent *ptr; int ret = is_path_exist(name); if(0 == ret) printf("path exist!\n"); int total_file_num = get_file_path(name); printf("total_file_num:%d\n",total_file_num); SortFilePath(); return 0 ; }
运行结果:
时间: 2025-01-19 17:47:13