# enumerating files on linux, readdir?

This topic is 3619 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

hey guys i am trying to enum through files and getting name, size and basic attributes (mainly if its a directory or a file) How do i do this? i manage to get the filename. I think i got directory or file correctly. However i cant figure out how to get the filesize. How do i do this? I know someone is going to say use boost, i am trying to do this w/o boost. For no good reason except as a learning exercise. Well, i have other reasons but none are as great.

##### Share on other sites
You will probably want to look into sys/stat.h I will be honest with you, I have never used it before, but it looks like the Posix way to do it. You can also try the less pretty, probably slower, slightly hacky, standard C way.

long int getFileSize(const char * filename){    FILE * fp = NULL;    long int file_size = 0;    fp = fopen(filename, 'rb');    fseek(fp, 0, SEEK_END);    file_size = ftell(fp);    fclose(fp);    return file_size;}

Heh, I think that will work :/ I would go the file stat way.

##### Share on other sites
You're starting out correctly with opendir+readdir (assuming you know your initial file is a directory). I assume you're iterating through said directory and using the filenames found in the d_name field in the dirent structure.

This name can be used to construct a path to the file and then be passed to stat (or probably lstat). The resulting statbuf struct contains all of the information you're looking for. See description.

PS: If I remember correctly, the inode from the dirent structure can't be trusted under the Posix standard... If you need an inode for a file get it from stat.

1. 1
2. 2
3. 3
4. 4
Rutin
16
5. 5

• 12
• 9
• 12
• 37
• 12
• ### Forum Statistics

• Total Topics
631419
• Total Posts
2999983
×