[project @ 1998-12-02 13:17:09 by simonm]
[ghc-hetmet.git] / ghc / lib / std / cbits / getBufferMode.c
1 /* 
2  * (c) The GRASP/AQUA Project, Glasgow University, 1994-1998
3  *
4  * $Id: getBufferMode.c,v 1.3 1998/12/02 13:27:35 simonm Exp $
5  *
6  * hIs...Buffered 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 /*
21  * We try to guess what the default buffer mode is going to be based 
22  * on the type of file we're attached to.
23  */
24
25 #define GBM_NB (0)
26 #define GBM_LB (-1)
27 #define GBM_BB (-2)
28 #define GBM_ERR (-3)
29
30 StgInt
31 getBufferMode(ptr)
32 StgForeignPtr ptr;
33 {
34     IOFileObject* fo = (IOFileObject*)ptr;
35     struct stat sb;
36     int fd = fo->fd;
37
38     /* Try to find out the file type */
39     while (fstat(fd, &sb) < 0) {
40         /* highly unlikely */
41         if (errno != EINTR) {
42             cvtErrno();
43             stdErrno();
44             return GBM_ERR;
45         }
46     }
47     /* Terminals are line-buffered by default */
48     if (S_ISCHR(sb.st_mode) && isatty(fd) == 1) {
49         fo ->flags |= FILEOBJ_LB;
50         return GBM_LB;
51     /* Default size block buffering for the others */
52     } else {
53         fo ->flags |= FILEOBJ_BB;
54         return GBM_BB;
55     }
56 }