[project @ 2000-12-11 17:51:57 by simonmar]
[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.4 2000/12/11 17:51:57 simonmar 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(StgForeignPtr ptr, StgByteArray result)
22 {
23     IOFileObject* fo = (IOFileObject*)ptr;
24     struct stat sb;
25     int rc = 0;
26
27     /* Flush buffer in order to get as an accurate size as poss. */
28     rc = flushFile(ptr);
29     if (rc < 0) return rc;
30
31    while (fstat(fo->fd, &sb) < 0) {
32         /* highly unlikely */
33         if (errno != EINTR) {
34             cvtErrno();
35             stdErrno();
36             return -1;
37         }
38     }
39     if (S_ISREG(sb.st_mode)) {
40         /* result will be word aligned */
41         *(off_t *) result = sb.st_size;
42         return 0;
43     } else {
44         ghc_errtype = ERR_INAPPROPRIATETYPE;
45         ghc_errstr = "not a regular file";
46         return -1;
47     }
48 }
49
50 StgInt
51 fileSize_int64(StgForeignPtr ptr, StgByteArray result)
52 {
53     IOFileObject* fo = (IOFileObject*)ptr;
54     struct stat sb;
55     int rc = 0;
56
57     /* Flush buffer in order to get as an accurate size as poss. */
58     rc = flushFile(ptr);
59     if (rc < 0) return rc;
60
61    while (fstat(fo->fd, &sb) < 0) {
62         /* highly unlikely */
63         if (errno != EINTR) {
64             cvtErrno();
65             stdErrno();
66             return -1;
67         }
68     }
69     if (S_ISREG(sb.st_mode)) {
70         /* result will be word aligned */
71         *(StgInt64*) result = (StgInt64)sb.st_size;
72         return 0;
73     } else {
74         ghc_errtype = ERR_INAPPROPRIATETYPE;
75         ghc_errstr = "not a regular file";
76         return -1;
77     }
78 }
79