I would like to know how I can navigate and edit folders and files through code in C. I have looked up the library dirent.h but I'm not sure which functions are used for traversing through directories. Am I even using the right library for this case, and if so, could you give a brief explanation of a few of the fundamental functions I will need to move around folders and change files. Also, do I have to use a pointer of some kind to keep track of which directory I am currently in, like I would with a linked list? Would I need to create a binary tree in order to have something that the pointer can point to?
Asked
Active
Viewed 8,563 times
1 Answers
8
The most important functions are:
opendir(const char *) - opens a directory and returns an object of type DIR
readdir(DIR *) - reads the content of a directory and returns an object of type dirent (struct)
closedir(DIR *) - closes a directory
For example, you can list the content of a directory using this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
char *pathcat(const char *str1, char *str2);
int main()
{
struct dirent *dp;
char *fullpath;
const char *path="C:\\test\\"; // Directory target
DIR *dir = opendir(path); // Open the directory - dir contains a pointer to manage the dir
while (dp=readdir(dir)) // if dp is null, there's no more content to read
{
fullpath = pathcat(path, dp->d_name);
printf("%s\n", fullpath);
free(fullpath);
}
closedir(dir); // close the handle (pointer)
return 0;
}
char *pathcat(const char *str1, char *str2)
{
char *res;
size_t strlen1 = strlen(str1);
size_t strlen2 = strlen(str2);
int i, j;
res = malloc((strlen1+strlen2+1)*sizeof *res);
strcpy(res, str1);
for (i=strlen1, j=0; ((i<(strlen1+strlen2)) && (j<strlen2)); i++, j++)
res[i] = str2[j];
res[strlen1+strlen2] = '\0';
return res;
}
The pathcat function simply concatenates 2 paths.
This code only scans the chosen directory (not its subdirectories). You must create your own code to perform an 'in-depth' scan (recursive function, etc.).

SpeedJack
- 139
- 2
- 8
-
3Note that `pathcat()` assumes the first path ends with an appropriate delimiter (separator; `'\\'` for Windows, or `'/'` for Unix), as it does in this code. A more general version would add the separator in the middle, but you'd need to adjust the memory allocation (add an extra character) to avoid overflow. The code might benefit from `sprintf()`; or it could use `memmove()` or `memcpy()` since you know the lengths of the strings. In fact, you should always know the lengths of the strings, so `memmove()` should always be an option. – Jonathan Leffler Aug 01 '14 at 05:53