Maybe
ftw()
is a better fit? e.g.:
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <stdlib.h>
#include <ftw.h>
#include <string.h>
int display(const char *full_path, const struct stat *sb, int tflag, struct FTW *ftwb)
{
if(tflag == FTW_D) {
const char *child_path = strchr(full_path, '/');
if(child_path == NULL)
child_path = "";
else
child_path += 1;
printf("%s -> '%s', '%s'\n",
full_path,
child_path,
full_path+ftwb->base );
}
return 0;
(void)sb;
}
int main(int argc, char *argv[])
{
if(nftw(argv[1], display, 20, 0) == -1) {
perror("nftw");
return 1;
}
return 0;
(void)argc;
}
Also note we're not using
strtok()
, which I think is part of your problem.
strto()
uses the second argument as a list of characters to break the string on, so
strtok(path, "\n")
looks for a new-line char, replaces that with a nul ('\0') and returns a pointer to the beginning of the string. At best you want
strtok(path, "/")
which looks for a forward-slash.
Note also that
ftw()
omits the
.
and
..
directories for you