Link to home
Start Free TrialLog in
Avatar of gsbabu
gsbabu

asked on

Details of a file.

Hi, In an environ, gcc running under solaris, i need to check whether a file is a directory or a simple file. Could anyone let me know how to do this.

-gsbabu
Avatar of ori_b
ori_b

Try the following :

#include <sys/types.h>
#include <sys/stat.h>

struct stat buf;
         
if (stat("file_name", &buf) == 0) {
 if ((buf.st_mode & S_IFMT) == _IFDIR)  {
      // it is a directory
}
Avatar of gsbabu

ASKER

ori_b
>> f ((buf.st_mode & S_IFMT) == _IFDIR)  {

on compiling, i get _IFDIR undeclared, i don't know more about, where it could be defined. help.

-gsbabu
ASKER CERTIFIED SOLUTION
Avatar of ori_b
ori_b

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gsbabu

ASKER

thanks, it is ok, also could i know how to make this in a loop, that is if in a directory there are some entries, which could be plain file or directory, i need to loop for the number of entries in the directory. could you help me. thanks for your previous help, let me know if you want me to post this as a new question.

--gsbabu.
You can try this (if I understood your question correctly) :

int     DirLoop(const char* path) {
 
  DIR *dirp;
  struct dirent *direntp;

  char file_name[256];
 
  printf("opening directory %s\n",path);
 
  dirp = opendir( path );
  if (dirp == NULL) {
      printf("Error %s : %s\n", path,strerror(errno));
      return -1;
  }
 
  while ( (direntp = readdir( dirp )) != NULL ) {
      if (direntp == NULL) {
        printf("Erorr %s : %s \n", path,strerror(errno));
        return -1;
      }


    // skip the ./ and ../ files        
    if (direntp->d_name[0] != '.') {

        // build the full path
        strcpy (file_name,path);
        strcat (file_name,"/");
        strcat (file_name,direntp->d_name);

        struct stat buf;
        
        // Find file's type
        if (stat(file_name, &buf) == 0) {
            if ((buf.st_mode & S_IFMT) == S_IFDIR) {
              // it is a directory
              DirLoop(file_name);
            }

            else {
              // A regular file - Do What you want to ...
              printf("%s\n",file_name);
            }
        }

        else {
            printf("Fail to stat file %s : %s\n",file_name, strerror(errno ));
            return -1;
        }
      
      }
  }

 
  if (closedir( dirp ) == -1) {
      printf("Erorr closedir of %s : %s \n", path,strerror(errno));
      return -1;
  }

  return 0;
}

You will need these #include  :

#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

Avatar of gsbabu

ASKER


Thanks very much Master Ori, It really worked pretty well.

 -gsbabu
 ugnasu01@thiru.vetri.com
glad to help