user1827257
user1827257

Reputation: 1640

Get file parrameters in c

I have this recursive function to search the tree structure of files. And I need to find out the parameters of each file (type, owner, group, permissions, creation date, last modification date, ..) How to do it?

void search(const char * path)
{
  char newpath[PATH_SIZE + 1];

  DIR * dp;
  struct dirent * ep;

  dp = opendir(path);
  if (dp == NULL)
    return;

  while ((ep = readdir(dp)) != NULL)
  {
    if (strcmp(".",  ep->d_name) == 0 ||
        strcmp("..", ep->d_name) == 0)
    {
      continue;
    }

    printf("%s/%s\n", path, ep->d_name);


    if ((ep->d_type & DT_DIR) == DT_DIR)
    {
      if (strlen(path) + strlen(ep->d_name) + 1 <= PATH_SIZE)
      {
        sprintf(newpath, "%s/%s", path, ep->d_name);
        search(newpath);
      }
    }
  }

  closedir(dp);

  return;
}

I only know the type of file (ep-> d_type);

Upvotes: 0

Views: 90

Answers (2)

Akshay Patil
Akshay Patil

Reputation: 970

The answer given by @gustaf r is absolutely correct . But , I want to add 1 more point which you can be found in MAN page also.

These functions return information about a file.   No  permissions  are
   required  on  the  file itself, but—in the case of stat() and lstat() —
   execute (search) permission is required on all of  the  directories  in
   path that lead to the file.

So, the directory you are working on should have appropriate permissions.

Upvotes: 1

gustaf r
gustaf r

Reputation: 1234

By the stat() function:

Manual: man 2 stat

Prototype:

   int stat(const char *path, struct stat *buf);
   int fstat(int fd, struct stat *buf);
   int lstat(const char *path, struct stat *buf);

where the stat structure is defined as:

   struct stat {
       dev_t     st_dev;     /* ID of device containing file */
       ino_t     st_ino;     /* inode number */
       mode_t    st_mode;    /* protection */
       nlink_t   st_nlink;   /* number of hard links */
       uid_t     st_uid;     /* user ID of owner */
       gid_t     st_gid;     /* group ID of owner */
       dev_t     st_rdev;    /* device ID (if special file) */
       off_t     st_size;    /* total size, in bytes */
       blksize_t st_blksize; /* blocksize for file system I/O */
       blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
       time_t    st_atime;   /* time of last access */
       time_t    st_mtime;   /* time of last modification */
       time_t    st_ctime;   /* time of last status change */
   };

Upvotes: 1

Related Questions