/* filestats.c zilla 	various info about file
 * modified:
 * 26sep
 * 5dec         add filedirp
 * 5sep         remove filetime to separate file
 * 29aug        minor
 * aug  	unix version
 */

/*@DOCINIT
 (@HEADERFILE filestats.H)
 (@MANPAGE filestats.MAN filestats 3 unknown portable file information library
*/

/*@SECTION DESCRIPTION
because programs which use stat are not portable.
*/


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

/*@DOCENTRY 
long Zfilesize(char *path)
*/

long Zfilesize(path)
  char *path;
{
  struct stat s;
  int code;
  extern int errno;
  
  code = stat(path,&s);
  
  if (code < 0) {
    errno = 0;
    return((long)(-1));
  }
  
  else return((long)s.st_size);

} /*Zfilesize*/


/*@DOCENTRY 
long Zifilesizep(int fptr)
*/

long Zifilesize(fptr)
  int fptr;
{
  struct stat s;
  int code;
  extern int errno;
  
  code = fstat(fptr,&s);
  
  if (code < 0) {
    errno = 0;
    return((long)(-1));
  }
  else return((long)s.st_size);
  
} /*Zifilesize*/



/*@DOCENTRY
long Zfilesizeext(char *fname,*ext,*errmsg)
*/

/*extern char *Zfileop();*/

long Zfilesizeext(fname,ext,errmsg)
  char *fname,*ext,*errmsg;
{
  struct stat s;
  int f;
  char path[512];
  extern int errno;
  
  if ((f = stat(fname,&s)) < 0) {	/* fname */
    (void)str_cpy(path,fname);
    (void)str_cat(path,ext);
    f = stat(path,&s);		/* fname.ext */
  }
  
  if (f < 0) {
    fflush(stdout);
    if (errmsg && *errmsg) fprintf(stderr,"%s: ",errmsg);
    fprintf(stderr,"can't find %s or %s\n",fname,path);
    exit(1);
  } else errno = 0;
  
  return((long)s.st_size);
  
} /*fsizeext*/


/*@DOCENTRY 
long Zfiledirp(char *path)
*/

bool Zfiledirp(path)
  char *path;
{
  struct stat s;
  int f;
  
  if ((f = stat(path,&s)) < 0) {
    perror("Zfiledirp");
    Zfail("Zfiledirp");
  }
  
  return S_ISDIR(s.st_mode);
} /*filedirp*/


#ifdef TESTIT /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

/*% cc -DTESTIT % -lZ -o filestatsTST %*/

main(ac,av)
  int ac;
  char *av[];
{
  long (*func)();
  if (str_eq(av[1],"Zfilesize"))
    func = Zfilesize;
  else if (str_eq(av[1],"fsizeext"))
    func = fsizeext;
  else quit(1,"badfunc\n");
  printf("%ld\n",(*func)(av[2]));
  exit(0);
}

#endif /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
