Reputation: 699
Final update- Answer is in the comments of the accepted answer.
First of all I realize there are a lot of other answers to this question. I've been through most of them and this code is a combination of going through many other answers. All I want to do is get to the full path to every file in a directory.
#include <limits.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
DIR *d;
struct dirent * dir;
char fullpath[PATH_MAX + 1];
d = opendir("/home/adirectory");
if(d != NULL)
{
while((dir = readdir(d)) != NULL)
{
realpath(dir->d_name, fullpath);
printf("[%s]\n", fullpath);
printf("%s\n", dir->d_name);
}
// addition of the following line yields
// Value too large for defined data type
perror("Something isn't working: ");
closedir(d);
}
return 0;
}
Update #3:
The call that fails is dir = readdir(d)
, which is why I have perror
immediately after the while loop.
Update #2:
This works just fine on CentOS, and Ubuntu gcc 4.8.5 +. Does not work on Solaris gcc 4.5.2.
Update: There is an error message:
Value too large for defined data type
...but I'm not sure what could cause this.
This always just prints the current working directory that I'm running the program from. Even so, it doesn't actually list any of the files in that directory besides "." and ".." . What gives? Is there some kind of permission issue? Does this solution not work in 2017?
Upvotes: 2
Views: 11007
Reputation: 12384
the d_name
field contains the name of the file in the context of the directory it traverses. So, it does not contain any path, just the name.
So, in order for you to play with its path, you need to append the d_name
to the name of the directory, something like the following:
char *myHomeDir = "/home/adirectory";
d = opendir(myNomDir);
. . .
while((dir = readdir(d)) != NULL) {
char filepath[PATH_MAX + 1] ;
strcpy(filepath, myHomeDir);
strcat(filepath, "/");
strcat(filepath, dir->d_name);
realpath(filepath, fullpath);
Of course the stuff above is just a skeleton code for clarity. It could be optimized better and you should use strncpy
family of functions.
Upvotes: 1