home *** CD-ROM | disk | FTP | other *** search
/ The UNIX CD Bookshelf / OREILLY_TUCB_UNIX_CD.iso / upt / examples / SOURCES / TWIN / TWIN. / iread.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-07-24  |  1.2 KB  |  48 lines

  1. /* iread.c */
  2. /*************************************************
  3. * read file into malloc'd buffer, return file size
  4. * Istvan Mohos, 1987 --- in the Public Domain
  5. **************************************************/
  6.  
  7. #include "i.h"
  8.  
  9. int
  10. iread (fname, mallocp)
  11. char *fname;
  12. char **mallocp;
  13. {
  14.     struct stat sbuf;
  15.     int checkval, fd;
  16.     int count;
  17.  
  18.     if (BADCHARP (fname))
  19.         return (ierror ("iread: invalid file name"));
  20.  
  21.     if (mallocp == (char **) NULL) {
  22.         if (access (fname, R_OK) == -1)
  23.             return (-1); /* can't read it */
  24.         return (0);
  25.     }
  26.  
  27.     if ((fd = open (fname, 0)) == -1)
  28.         return (ierror ("iread: no file access"));
  29.         
  30.     if ((checkval = fstat (fd, &sbuf)) == -1)
  31.         return (ierror ("iread: fstat read error"));
  32.  
  33.     if ((count = (int)sbuf.st_size) == 0)
  34.         return (ierror ("iread: zero length file"));
  35.  
  36.     if (NULCHARP (*mallocp = malloc ((unsigned int) count+1)))
  37.         return (ierror ("iread: can't allocate read buffer"));
  38.  
  39.     if ((checkval = read (fd, *mallocp, count)) != count) {
  40.         sprintf (ierbuf+200,
  41.             "iread: expected: %d, read: %d", count, checkval);
  42.         return (ierror (ierbuf+200));
  43.     }
  44.     close (fd);
  45.     *(*mallocp + count) = 0;
  46.     return (checkval);
  47. }
  48.