diff options
Diffstat (limited to 'fileop.c')
-rw-r--r-- | fileop.c | 106 |
1 files changed, 106 insertions, 0 deletions
diff --git a/fileop.c b/fileop.c new file mode 100644 index 0000000..52e5b6d --- /dev/null +++ b/fileop.c @@ -0,0 +1,106 @@ +/* ------------------------------------------------------------------ + * fileop.c + * File related operations, such as searching file in path, list of + * files in some dir. + * ----------------------------------------------------------------*/ + +#include <sys/types.h> +#include <sys/stat.h> +#include <unistd.h> +#include <dirent.h> +#include <string.h> +#include <stdlib.h> +#include <stdio.h> + +#include "test_commands.h" + +#define MAX_FILEPATH_LENGTH (256) + +/* to check wether a given name is a directory or not + * Input: + * - name: the name to be checked. +Return: + * - 1: if is a directory + * - 0: if not a directory, or file <name> doesn't exist, error + */ +static int is_dir(const char* name) +{ + struct stat buf; + + if (lstat(name, &buf) < 0) + return 0; /* if not exist, error */ + + /*if is directory return 1 ,else return 0*/ + return S_ISDIR(buf.st_mode); +} + + +/* search target file with <name> in directory <path> + * Input: + * - path: the path to be searched in + * - name: file name to be searched + * Return: + * - -1: error + * - 1: found + * - 0: not found + */ +int search_file(const char* path, const char* name) +{ + int ret = -1; + DIR* directory; + struct dirent* dir_entry; + char current_filename[MAX_FILEPATH_LENGTH]; + + TDBG("Enter %s. name=%s; path=%s\n", __FUNCTION__, name, path); + if ((directory = opendir(path)) == NULL) { + printf("Error opendir(%s)\n", path); + return -1; + } + + while (dir_entry = readdir(directory)) { + TDBG("dir_entry->d_name is \"%s\"\n", dir_entry->d_name); + /* To check wether this is a directory */ + if (!strcmp(dir_entry->d_name, ".") || + !strcmp(dir_entry->d_name, "..")) { + /* skip */ + continue; + } + else { + /* if is root directory */ + if ((strcmp(path, "/")) == 0) + ret = snprintf(current_filename, MAX_FILEPATH_LENGTH, "%s%s", path, dir_entry->d_name); + /* if is not root directory */ + else + ret = snprintf(current_filename, MAX_FILEPATH_LENGTH, "%s%s", path, dir_entry->d_name); + /* check if truncated */ + if (ret >= MAX_FILEPATH_LENGTH) { + printf("Critical error: exceed MAX_FILEPATH_LENGTH.\n"); + closedir(directory); + return -1; + } + } + + TDBG("Now tracking file (full path): %s\n", current_filename); + + /* if is a directory, recursively call search_file */ + if (is_dir(current_filename)) { + ret = search_file(current_filename, name); + if (ret == 1) { + TDBG("File: %s is found in directory %s\n", name, current_filename); + closedir(directory); + return ret; + } + } + else { + if (strcmp(dir_entry->d_name, name) == 0) { + TDBG("File: %s is found in directory %s.\n", name, current_filename); + closedir(directory); + return 1; + } + } + } + closedir(directory); + + /* no findings */ + return 0; +} |