[project @ 2001-03-01 12:25:32 by rrt]
[ghc-hetmet.git] / ghc / lib / std / cbits / closeFile.c
index 1addd3f..82fdc51 100644 (file)
@@ -1,13 +1,14 @@
 /* 
  * (c) The GRASP/AQUA Project, Glasgow University, 1994-1998
  *
- * $Id: closeFile.c,v 1.7 1999/11/25 16:54:14 simonmar Exp $
+ * $Id: closeFile.c,v 1.10 2000/09/25 10:48:50 simonmar Exp $
  *
  * hClose Runtime Support
  */
 
 #include "Rts.h"
 #include "stgio.h"
+#include <errno.h>
 
 #if defined(HAVE_WINSOCK_H) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
 #define USE_WINSOCK
@@ -31,8 +32,9 @@ closeFile(StgForeignPtr ptr, StgInt flush_buf)
        return 0;
     }
 
-    if ( flush_buf != 0 && (fo->flags & FILEOBJ_WRITE) ) {
-       writeFileObject(ptr,fo->bufWPtr);
+    /* Flush buffer if we have unwritten data */
+    if ( flush_buf != 0 ) {
+       flushBuffer(fo);
     }
 
     /* If the flush failed, we ignore this and soldier on.. */
@@ -59,6 +61,14 @@ closeFile(StgForeignPtr ptr, StgInt flush_buf)
        
     }
 
+    /* Free the buffer straight away.  We can't free the file object
+     * itself until the finalizer runs.
+     */
+    if ( fo->buf != NULL ) {
+       free(fo->buf);
+       fo->buf = NULL;
+    }
+
     /* Closing file descriptors that refer to standard channels
        is problematic, so we back off from doing this by default,
        just closing them at the Handle level. If you insist on
@@ -88,6 +98,8 @@ closeFile(StgForeignPtr ptr, StgInt flush_buf)
        }
       }
     }
+
     fo->fd = -1;
+
     return 0;
 }