/* stat - an example of using the stat() system call */

/* Usage: stat filename, prints out the stat details of that file */

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>



/* Definitions missing from stat.h */
#ifndef S_ISBLK
#define S_ISBLK(m)      (((m)&S_IFMT) == S_IFBLK)	/* Where m is the */
#define S_ISCHR(m)      (((m)&S_IFMT) == S_IFCHR)	/* st_mode in the */
#define S_ISDIR(m)      (((m)&S_IFMT) == S_IFDIR)	/* sppropriate stat */
#define S_ISFIFO(m)     (((m)&S_IFMT) == S_IFIFO)	/* structure. */
#define S_ISREG(m)      (((m)&S_IFMT) == S_IFREG)	/* Give non-zero */
#define S_ISLNK(m)      (((m)&S_IFMT) == S_IFLNK)	/* value if true. */
#define S_ISSOCK(m)     (((m)&S_IFMT) == S_IFSOCK)
#endif

int main(argc, argv)
  int argc;
  char *argv[];
{
  struct stat statbuf;		/* The buffer for the stat information */

  if (argc != 2) { printf("I need the name of the file!\n"); exit(1); }

  				/* Get the stat info for the file */
  				/* Note we pass the address of the buffer */
  if (stat(argv[1], &statbuf) == -1) { perror("stat"); exit(1); }

  				/* Print out the fields in the buffer */

  printf("File: %s\n", argv[1]);
  printf("Device number: %d\n", (int) statbuf.st_dev);
  printf("Inode number : %d\n", (int) statbuf.st_ino);
  printf("File mode:     0%o\n", statbuf.st_mode);
  printf("# links:       %d\n", statbuf.st_nlink);
  printf("Owner id:      %d\n", statbuf.st_uid);
  printf("Group id:      %d\n", statbuf.st_gid);
  printf("File size:     %d\n", (int) statbuf.st_size);
  printf("File  access time:   %s", ctime(&(statbuf.st_atime)));
  printf("File  modify time:   %s", ctime(&(statbuf.st_mtime)));
  printf("Inode modify time:   %s", ctime(&(statbuf.st_ctime)));

  if (S_ISBLK(statbuf.st_mode)) printf("File is a block device\n");
  if (S_ISCHR(statbuf.st_mode)) printf("File is a character device\n");
  if (S_ISDIR(statbuf.st_mode)) printf("File is a directory\n");
  if (S_ISFIFO(statbuf.st_mode)) printf("File is a fifo pipe\n");
  if (S_ISREG(statbuf.st_mode)) printf("File is a regular file\n");
  if (S_ISLNK(statbuf.st_mode)) printf("File is a symbolic link\n");
  if (S_ISSOCK(statbuf.st_mode)) printf("File is a socket\n");

  exit(0);
}
