Reputation: 5157
Basically this piece of code gives me names of the files in the directory....But I need to get their paths instead.. I tried to use function realpath(). But I am using it wrong I guess(I showed in code where i wanted to use it). Any ideas how to fix it?. One more thing: It gives me only names of subdirectories, but basically I need to get paths of the their files too.Thanks.
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
int main (int c, char *v[]) {
int len, n;
struct dirent *pDirent;
DIR *pDir;
int ecode=0;
struct stat dbuf;
for (n=1; n<c; n++){
if (lstat(v[n], &dbuf) == -1){
perror (v[n]);
ecode ++;
}
else if(S_ISDIR(dbuf.st_mode)){
printf("%s is a directory/n ", v[n]);
}
else{
printf("%s is not a directory\n", v[n]);
}
}
if (c < 2) {
printf ("Usage: testprog <dirname>\n");
return 1;
}
pDir = opendir (v[1]);
if (pDir == NULL) {
printf ("Cannot open directory '%s'\n", v[1]);
return 1;
}
while ((pDirent = readdir(pDir)) != NULL) {
// here I tried to use realpath()
printf ("[%s]\n", realpath(pDirent->d_name));
}
closedir (pDir);
return 0;
}
Upvotes: 4
Views: 26418
Reputation: 575
All you need is to add the second argument to realpath, because it needs a buffer to write into. I recommend you take the line out of the printf statement and give it its own line. realpath() can return a char*, but it wasn't designed to.
#include <limits.h> //For PATH_MAX
char buf[PATH_MAX + 1];
while ((pDirent = readdir(pDir)) != NULL) {
realpath(pDirent->d_name, buf);
printf ("[%s]\n", buf);
}
This appears to display the full paths properly on my system.
Upvotes: 3