Sign in to follow this  
AcidZombie24

enumerating files on linux, readdir?

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 this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this