2

I trying to get size of files in a directory by using dirent.h headers. However

stat(ent->d_name, &statbuf)

returns always -1 and I can't get the size properly. What could be the reason?

thetux4
  • 1,583
  • 10
  • 25
  • 38

2 Answers2

8

d_name contains the name of the file within that directory. stat wants a name including the directory part, unless it's the current directory.

Make a temporary string containing the full path to the d_name file.

EDIT: Sample

char const * DirName = "/tmp";
....
char * FullName = (char*) malloc(strlen(DirName) + strlen(ent->d_name) + 2); 
strcpy(FullName, DirName);
strcat(FullName, "/");
strcat(FullName, ent->d_name);
stat(FullName, &statbuf);
free(FullName);
anilbey
  • 1,817
  • 4
  • 22
  • 38
Erik
  • 88,732
  • 13
  • 198
  • 189
  • After i gave directory name to the stat, it always returned 4096 per file. – thetux4 Apr 01 '11 at 14:49
  • 2
    thetux4: You need to give a string consisting of *directory* and *file* to stat. If you give just a directory name, you'll get the size of the directory, which typically starts at 4096 – Erik Apr 01 '11 at 14:50
1

I use C++ and I thought the above code would work, but it didn't because it still needed a conversion from void to char*:

char *fullName = (char*) malloc(strlen(path) + strlen(entry->d_name) + 2);

hopefully this can help someone :)

mr_kazz
  • 91
  • 1
  • 5