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

/*
st_mode   Bit mask for file-mode information. The _S_IFDIR bit is set if path
specifies a directory; the _S_IFREG bit is set if path specifies an
ordinary file or a device.
*/


int main(void){
struct _stat buf;
int k,flag;
char s[256]; char *p;
FILE *fp;
  while(1){
    printf("Dir: "); gets(s);
    flag=0;
loop:
    k= _stat(s,(struct _stat *)&buf);
    /* k==0 means OK, k==1 means not found */
    if(k==1) {printf("File/Dir %s not found\n",s); continue;}
    if((_S_IFREG & buf.st_mode) != 0){
      printf("Regular file reported by stat\n");
    }
    if((_S_IFDIR & buf.st_mode) != 0){
      printf("Directory\n");
#if 1
      fp=fopen(s,"r");
      if(fp==(FILE *)0){
        printf("%s is NOT a file.",s);
        p=strrchr(s,'\\'); if(p!=(char *)0) p[1]=0;
        if(++flag==1){
          printf("Trying %s.\n",s);
        goto loop;
        }
        printf("\n");
      }
      else {
        fclose(fp);
        printf("Mistake - %s is a file.\n",s);
      }
#endif
    }
    printf("File size = %ld\n\n",(long)buf.st_size);

  }
  return 0; // C runtime cleans up the file opens
}
