Last active
January 25, 2022 15:30
-
-
Save Rajssss/d395c18632763975559eab3ddff7e3b8 to your computer and use it in GitHub Desktop.
Some useful function around files C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* List all directories and files recursively inside the given path | |
* as tree view | |
*/ | |
static void list_files_as_tree(char *basePath, const int root) | |
{ | |
/* | |
* Warning: This code requires hell lot of memory (stack) | |
*/ | |
int i; | |
char path[1000]; | |
struct dirent *dp; | |
DIR *dir = opendir(basePath); | |
if (!dir) | |
return; | |
while ((dp = readdir(dir)) != NULL) | |
{ | |
if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0) | |
{ | |
for (i=0; i<root; i++) | |
{ | |
if (i%2 == 0 || i == 0) | |
printf(" "); | |
else | |
printf(" "); | |
} | |
printf("--%s\n", dp->d_name); | |
strcpy(path, basePath); | |
strcat(path, "/"); | |
strcat(path, dp->d_name); | |
list_files_as_tree(path, root + 2); | |
} | |
} | |
closedir(dir); | |
} | |
/* | |
* print contents of a file to stdout (printf) | |
*/ | |
static void print_file(char *file_name) | |
{ | |
FILE *fptr = fopen(file_name, "r"); | |
if (fptr == NULL) { | |
ESP_LOGE(TAG, "print_file: Failed to open file for reading"); | |
fclose(fptr); | |
return; | |
} | |
ESP_LOGI(TAG, "print_file: printing file: %s\n", file_name); | |
char c = fgetc(fptr); | |
while (!feof(fptr)) | |
{ | |
printf ("%c", c); | |
c = fgetc(fptr); | |
} | |
printf("\n"); | |
fclose(fptr); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample O/P of list_files_as_tree():