summaryrefslogtreecommitdiff
path: root/ghc/lib/std/cbits/flushFile.c
blob: 5631f38f95e697cf984f5426886c810667a5a9aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/* 
 * (c) The GRASP/AQUA Project, Glasgow University, 1994-1998
 *
 * $Id: flushFile.c,v 1.7 2000/04/12 17:33:16 simonmar Exp $
 *
 * hFlush Runtime Support
 */

#include "Rts.h"
#include "stgio.h"

StgInt
flushFile(StgForeignPtr ptr)
{
    IOFileObject* fo = (IOFileObject*)ptr;
    int rc = 0;

    if ( (fo->flags & FILEOBJ_WRITE) && FILEOBJ_NEEDS_FLUSHING(fo) ) {
       rc = writeBuffer(ptr,fo->bufWPtr - fo->bufRPtr);
    }

    return rc;
}

StgInt
flushBuffer(StgForeignPtr ptr)
{
    IOFileObject* fo = (IOFileObject*)ptr;
    int rc = 0;

    /* If the file object is writeable, or if it's
       RW *and* the last operation on it was a write,
       flush it.
    */
    if ( (!FILEOBJ_READABLE(fo) && FILEOBJ_WRITEABLE(fo)) ||
         (FILEOBJ_RW(fo) && FILEOBJ_JUST_WRITTEN(fo)) ) {
       rc = flushFile(ptr);
       if (rc<0) return rc;
    }
    
    /* TODO: shouldn't we do the lseek stuff from flushReadBuffer
     * here???? --SDM
     */

    /* Reset read & write pointer for input buffers */
    if ( (fo->flags & FILEOBJ_READ) ) {
       fo->bufRPtr=0;
       fo->bufWPtr=0;
    }
    return 0;
}

/*
 For RW file objects, flushing input buffers doesn't just involve 
 resetting the read & write pointers, we also have to change the
 underlying file position to point to the effective read position.

 (Sigh, I now understand the real reason for why stdio opted for
 the solution of leaving this to the programmer!)
*/
StgInt
flushReadBuffer(StgForeignPtr ptr)
{
    IOFileObject* fo = (IOFileObject*)ptr;
    int delta;

    delta = fo->bufWPtr - fo->bufRPtr;

    if ( delta > 0 ) {
       while ( lseek(fo->fd, -delta, SEEK_CUR) == -1) {
	  if (errno != EINTR) {
	     cvtErrno();
	     stdErrno();
	     return -1;
	  }
       }
    }

    fo->bufRPtr=0;
    fo->bufWPtr=0;
    return 0;
}

void
flushConnectedBuf(StgForeignPtr ptr)
{
    StgInt rc;
    IOFileObject* fo = (IOFileObject*)ptr;
    
    /* if the stream is connected to an output stream, flush it. */
    if ( fo->connectedTo != NULL && fo->connectedTo->fd != -1 &&
         (fo->connectedTo->flags & FILEOBJ_WRITE) ) {
       rc = flushBuffer((StgForeignPtr)fo->connectedTo);
    }
    /* Willfully ignore the return code for now. */
    return;
}