Skip to content

Instantly share code, notes, and snippets.

@Rajssss
Last active January 25, 2022 15:30
Show Gist options
  • Save Rajssss/d395c18632763975559eab3ddff7e3b8 to your computer and use it in GitHub Desktop.
Save Rajssss/d395c18632763975559eab3ddff7e3b8 to your computer and use it in GitHub Desktop.
Some useful function around files C
/*
* 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);
}
@Rajssss
Copy link
Author

Rajssss commented Jan 25, 2022

Sample O/P of list_files_as_tree():

--1.txt
--directory2
  --3.txt
--directory
  --2.txt
--index.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment