[project @ 1998-12-02 13:17:09 by simonm]
[ghc-hetmet.git] / ghc / lib / std / cbits / flushFile.c
1 /* 
2  * (c) The GRASP/AQUA Project, Glasgow University, 1994-1998
3  *
4  * $Id: flushFile.c,v 1.3 1998/12/02 13:27:32 simonm Exp $
5  *
6  * hFlush Runtime Support
7  */
8
9 #include "Rts.h"
10 #include "stgio.h"
11
12 StgInt
13 flushFile(ptr)
14 StgForeignPtr ptr;
15 {
16     IOFileObject* fo = (IOFileObject*)ptr;
17     int rc = 0;
18
19     if ( (fo->flags & FILEOBJ_FLUSH) && !FILEOBJ_BUFFER_EMPTY(fo) ) {
20        rc = writeBuffer(ptr,fo->bufWPtr - fo->bufRPtr);
21     }
22
23     return rc;
24 }
25
26 StgInt
27 flushBuffer(ptr)
28 StgForeignPtr ptr;
29 {
30     IOFileObject* fo = (IOFileObject*)ptr;
31     int rc = 0;
32
33     /* If the file object is writeable, or if its
34        RW and the last operation on it was a write,
35        flush it.
36     */
37     if ( (!FILEOBJ_READABLE(fo) && FILEOBJ_WRITEABLE(fo)) || (FILEOBJ_RW(fo) && FILEOBJ_JUST_WRITTEN(fo)) ) {
38        rc = flushFile(ptr);
39        if (rc<0) return rc;
40     }
41     
42     /* Reset read & write pointer for input buffers */
43     if ( (fo->flags & FILEOBJ_READ) ) {
44        fo->bufRPtr=0;
45        fo->bufWPtr=0;
46     }
47     return 0;
48 }
49
50 /*
51  For RW file objects, flushing input buffers doesn't just involve 
52  resetting the read & write pointers, we also have to change the
53  underlying file position to point to the effective read position.
54
55  (Sigh, I now understand the real reason for why stdio opted for
56  the solution of leaving this to the programmer!)
57 */
58 StgInt
59 flushReadBuffer(ptr)
60 StgForeignPtr ptr;
61 {
62     IOFileObject* fo = (IOFileObject*)ptr;
63     int delta;
64
65     delta = fo->bufWPtr - fo->bufRPtr;
66
67     if ( delta > 0 ) {
68        while ( lseek(fo->fd, -delta, SEEK_CUR) == -1) {
69           if (errno != EINTR) {
70              cvtErrno();
71              stdErrno();
72              return -1;
73           }
74        }
75     }
76
77     fo->bufRPtr=0;
78     fo->bufWPtr=0;
79     return 0;
80 }