Navigating through files using dirent.h? [duplicate]

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?

0

1 Answer

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.).

1

You Might Also Like