linux 遍历文件目录

#include <stdio.h>
#include <dirent.h> 
#include <stdlib.h> 
#include <string.h>
#include <unistd.h>
#include <error.h>
#include <sys/stat.h>  

#define MAX_FILE_NAME_LEN 256

typedef struct foldernode_t {
	char *path;                // point to foldername or filename path
	struct foldernode_t *next;
} foldernode;

static void travel_files(const char *path)
{
	DIR *dir;
	struct dirent *ptr;
	char foldername[MAX_FILE_NAME_LEN] = { 0 };
	char folderpath[MAX_FILE_NAME_LEN] = { 0 };

	foldernode *folderstart;
	folderstart = (foldernode *)calloc(1, sizeof(foldernode));/* ignore err case */
	folderstart->path = (char *)calloc(1, MAX_FILE_NAME_LEN + 1);
	strncpy(folderstart->path, path, MAX_FILE_NAME_LEN);
	folderstart->next = NULL;

	foldernode *folderfirst = folderstart; /* use to search */
	foldernode *folderlast = folderstart; /* use to add foldernode */
	foldernode *oldfirst = NULL;

	while (folderfirst != NULL) {
		printf("dir=%s\n", folderfirst->path);
		if ((dir = opendir(folderfirst->path)) != NULL) {
			while ((ptr = readdir(dir)) != NULL) {
				if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) {
					continue;
				}
				else if (ptr->d_type == DT_REG) { /* regular file */
					printf("%s\n", ptr->d_name);
				}
				else if (ptr->d_type == DT_DIR) { /* dir */
					bzero(foldername, sizeof(foldername));
					bzero(folderpath, sizeof(folderpath));
					strncpy(foldername, ptr->d_name, sizeof(foldername));
					snprintf(folderpath, sizeof(folderpath), "%s/%s", folderfirst->path, foldername);
					printf("%s\n", folderpath);

					foldernode *foldernew;
					foldernew = (foldernode *)calloc(1, sizeof(foldernode));
					foldernew->path = (char *)calloc(1, MAX_FILE_NAME_LEN + 1);
					strncpy(foldernew->path, folderpath, MAX_FILE_NAME_LEN);
					foldernew->next = NULL;

					folderlast->next = foldernew;
					folderlast = foldernew;

				}
			}
		}
		else {
			printf("opendir[%s] error: %m\n", folderfirst->path);
			return;
		}
		oldfirst = folderfirst;
		folderfirst = folderfirst->next; // change folderfirst point to next foldernode
		if (oldfirst) {
			if (oldfirst->path) {
				free(oldfirst->path);
				oldfirst->path = NULL;
			}
			free(oldfirst);
			oldfirst = NULL;
		}
		closedir(dir);
	}
}

int main(int argc, char **argv)
{

	travel_files("/sys");
	getchar();
	return 0;
}

上一篇:智能指针的详解


下一篇:std::move使用实例