[project @ 2001-04-02 16:10:32 by rrt]
[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.7 2001/04/02 16:10:32 rrt 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 #if defined( macosx_TARGET_OS )
42         *(W_ *) result = (W_)sb.st_size;
43 #else
44         *(off_t *) result = sb.st_size;
45 #endif
46         return 0;
47     } else {
48         ghc_errtype = ERR_INAPPROPRIATETYPE;
49         ghc_errstr = "not a regular file";
50         return -1;
51     }
52 }
53
54 StgInt
55 fileSize_int64(StgForeignPtr ptr, 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