[project @ 1998-12-02 13:17:09 by simonm]
[ghc-hetmet.git] / ghc / lib / std / cbits / fileSize.c
1 /* 
2  * (c) The GRASP/AQUA Project, Glasgow University, 1994-1998
3  *
4  * $Id: fileSize.c,v 1.3 1998/12/02 13:27:30 simonm Exp $
5  *
6  * hClose Runtime Support
7  */
8
9 #include "Rts.h"
10 #include "stgio.h"
11
12 #ifdef HAVE_SYS_TYPES_H
13 #include <sys/types.h>
14 #endif
15
16 #ifdef HAVE_SYS_STAT_H
17 #include <sys/stat.h>
18 #endif
19   
20 StgInt
21 fileSize(ptr, result)
22 StgForeignPtr ptr;
23 StgByteArray result;
24 {
25     IOFileObject* fo = (IOFileObject*)ptr;
26     struct stat sb;
27     int rc = 0;
28
29     /* Flush buffer in order to get as an accurate size as poss. */
30     rc = flushFile(ptr);
31     if (rc < 0) return rc;
32
33    while (fstat(fo->fd, &sb) < 0) {
34         /* highly unlikely */
35         if (errno != EINTR) {
36             cvtErrno();
37             stdErrno();
38             return -1;
39         }
40     }
41     if (S_ISREG(sb.st_mode)) {
42         /* result will be word aligned */
43         *(off_t *) result = sb.st_size;
44         return 0;
45     } else {
46         ghc_errtype = ERR_INAPPROPRIATETYPE;
47         ghc_errstr = "not a regular file";
48         return -1;
49     }
50 }
51
52 StgInt
53 fileSize_int64(ptr, result)
54 StgForeignPtr ptr;
55 StgByteArray result;
56 {
57     IOFileObject* fo = (IOFileObject*)ptr;
58     struct stat sb;
59     int rc = 0;
60
61     /* Flush buffer in order to get as an accurate size as poss. */
62     rc = flushFile(ptr);
63     if (rc < 0) return rc;
64
65    while (fstat(fo->fd, &sb) < 0) {
66         /* highly unlikely */
67         if (errno != EINTR) {
68             cvtErrno();
69             stdErrno();
70             return -1;
71         }
72     }
73     if (S_ISREG(sb.st_mode)) {
74         /* result will be word aligned */
75         *(StgInt64*) result = (StgInt64)sb.st_size;
76         return 0;
77     } else {
78         ghc_errtype = ERR_INAPPROPRIATETYPE;
79         ghc_errstr = "not a regular file";
80         return -1;
81     }
82 }
83