OSDN Git Service

Initial revision
[pf3gnuchains/pf3gnuchains3x.git] / newlib / libc / stdio / fclose.c
1 /*
2 FUNCTION
3 <<fclose>>---close a file
4
5 INDEX
6         fclose
7
8 ANSI_SYNOPSIS
9         #include <stdio.h>
10         int fclose(FILE *<[fp]>);
11
12 TRAD_SYNOPSIS
13         #include <stdio.h>
14         int fclose(<[fp]>)
15         FILE *<[fp]>;
16
17 DESCRIPTION
18 If the file or stream identified by <[fp]> is open, <<fclose>> closes
19 it, after first ensuring that any pending data is written (by calling
20 <<fflush(<[fp]>)>>).
21
22 RETURNS
23 <<fclose>> returns <<0>> if successful (including when <[fp]> is
24 <<NULL>> or not an open file); otherwise, it returns <<EOF>>.
25
26 PORTABILITY
27 <<fclose>> is required by ANSI C.
28
29 Required OS subroutines: <<close>>, <<fstat>>, <<isatty>>, <<lseek>>,
30 <<read>>, <<sbrk>>, <<write>>.
31 */
32
33 /*
34  * Copyright (c) 1990 The Regents of the University of California.
35  * All rights reserved.
36  *
37  * Redistribution and use in source and binary forms are permitted
38  * provided that the above copyright notice and this paragraph are
39  * duplicated in all such forms and that any documentation,
40  * advertising materials, and other materials related to such
41  * distribution and use acknowledge that the software was developed
42  * by the University of California, Berkeley.  The name of the
43  * University may not be used to endorse or promote products derived
44  * from this software without specific prior written permission.
45  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
46  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
47  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
48  */
49
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include "local.h"
53
54 /*
55  * Close a file.
56  */
57
58 int
59 _DEFUN (fclose, (fp),
60         register FILE * fp)
61 {
62   int r;
63
64   if (fp == NULL)
65     return (0);                 /* on NULL */
66
67   CHECK_INIT (fp);
68
69   if (fp->_flags == 0)          /* not open! */
70     return (0);
71   r = fp->_flags & __SWR ? fflush (fp) : 0;
72   if (fp->_close != NULL && (*fp->_close) (fp->_cookie) < 0)
73     r = EOF;
74   if (fp->_flags & __SMBF)
75     _free_r (fp->_data, (char *) fp->_bf._base);
76   if (HASUB (fp))
77     FREEUB (fp);
78   if (HASLB (fp))
79     FREELB (fp);
80   fp->_flags = 0;               /* release this FILE for reuse */
81   return (r);
82 }