查找当前指定目录下“*.bin”的文件

#include 
#include 
#include 
#include 

#define FILENAME_LENGTH 100
#define MAX_ITE_NUM 10

int search(char *path) //  , struct io_match *input_list)
{
	int rval = 0;
	DIR *pDir = NULL;
	struct dirent *pEnt = NULL;
	int path_size = 0, file_size = 0, count = 0;
	char full_file_name[FILENAME_LENGTH];

	do {
		if (path == NULL) {
			printf("error: path is NULL\n");
			rval = -1;
			break;
		}

		pDir = opendir(path);
		if (pDir == NULL) {
			perror("opendir");
			rval = -1;
			break;
		}

		path_size = strlen(path);
		while (1) {
			pEnt = readdir(pDir);
			if (pEnt != NULL) {
				if (pEnt->d_type == DT_REG) { // This is a regular file. Exclude directories, etc.
					file_size = strlen(pEnt->d_name);

					// Make sure the file suffix is ".bin"
					if(strcmp((pEnt->d_name + (file_size - 4)) , ".bin") != 0) {
						continue;
					}

					// check file length
					if ((path_size + file_size) > FILENAME_LENGTH) {
						printf("File full path's length %d > %d!!!\n", (path_size + file_size), FILENAME_LENGTH);
						rval = -1;
						break;
					}

					memset(full_file_name, 0, FILENAME_LENGTH);
					strncpy(full_file_name, path, sizeof(full_file_name) - 1);
					if (path[path_size - 1] != '/') {
						strcat(full_file_name, "/");
					}

					strcat(full_file_name, pEnt->d_name);
					//strcpy(input_list->file_name[count], full_file_name);
					printf("full_file_name: %s\n", full_file_name);

					count ++;
					if (count > MAX_ITE_NUM) {
						printf("The number of file is %d > %d !!!\n", count, MAX_ITE_NUM);
						rval = -1;
						break;
					}
					//input_list->file_count = count;
					printf("count: %d\n", count);
				} else { // Not a regular file.
					continue;
				}
			} else {
				break;
			}
		}

		if (count == 0) {
			printf("No *.bin was found in the input_port_directory!");
			rval = -1;
			break;
		}

		if (pDir != NULL) {
			closedir(pDir);
		}
	} while (0);

	return rval;
}




int main (){
	char *path = "./img";

	search(path);

	return 0;
}
$ ll ./img/

drwxr-xr-x 13:18 ./
drwxr-xr-x 13:17 ../
-rwxr--r-- 13:17 1.bin*
-rwxr--r-- 13:18 1.txt*
-rwxr--r-- 13:17 2.bin*
-rwxr--r-- 13:18 3.bin*
drwxr-xr-x 13:18 dir/



打印

full_file_name: ./img/1.bin
count: 1
full_file_name: ./img/3.bin
count: 2
full_file_name: ./img/2.bin
count: 3


 

你可能感兴趣的:(查找当前指定目录下“*.bin”的文件)