branch update for HEAD-2003021201
[reactos.git] / lib / crtdll / stdio / allocfil.c
1 /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
2 #include <msvcrt/stdio.h>
3 #include <msvcrt/string.h>
4 #include <msvcrt/stdlib.h>
5 #include <msvcrt/internal/file.h>
6
7
8 FILE *  __alloc_file(void);
9
10 char __validfp (FILE *f)
11 {
12         if ( (unsigned int)f < 256)
13                 return FALSE;
14
15         if( f == NULL || (int)f== -1 )
16                 return FALSE;
17
18         return TRUE;
19 }
20
21 /* A FILE* is considered "free" if its flag is zero. */
22
23 FILE *__alloc_file(void)
24 {
25   __file_rec *fr = __file_rec_list;
26   __file_rec **last_fr = &__file_rec_list;
27   FILE *rv=0;
28   int i;
29    
30   /* Try to find an empty slot */
31   while (fr)
32   {
33     last_fr = &(fr->next);
34
35     /* If one of the existing slots is available, return it */
36     for (i=0; i<fr->count; i++)
37        {
38           if (fr->files[i]->_flag == 0)
39             {
40                return fr->files[i];
41             }
42        }
43
44     /* If this one is full, go to the next */
45     if (fr->count == __FILE_REC_MAX)
46       fr = fr->next;
47     else
48       /* it isn't full, we can add to it */
49       break;
50   }
51   if (!fr)
52   {
53     /* add another one to the end, make it empty */
54     fr = *last_fr = (__file_rec *)malloc(sizeof(__file_rec));
55     if (fr == 0)
56       return 0;
57     fr->next = 0;
58     fr->count = 0;
59   }
60   /* fr is a pointer to a rec with empty slots in it */
61   rv = fr->files[fr->count] = (FILE *)malloc(sizeof(FILE));
62   if (rv == 0)
63     return 0;
64   memset(rv, 0, sizeof(FILE));
65   fr->count ++;
66   return rv;
67 }
68
69
70 int _fcloseall( void )
71 {
72    __file_rec *fr = __file_rec_list;
73    __file_rec **last_fr = &__file_rec_list;
74   
75    int total_closed = 0;
76    int i = 0;
77
78    /* Try to find an empty slot */
79    while (fr)
80      {
81         last_fr = &(fr->next);
82         
83         /* If one of the existing slots is available, return it */
84         for (i=0; i<fr->count; i++)
85           if (fr->files[i]->_flag != 0) {
86              fclose(fr->files[i]);
87              total_closed++;
88           }
89         
90         /* If this one is full, go to the next */
91         if (fr->count == __FILE_REC_MAX)
92           fr = fr->next;
93         else
94           /* it isn't full, we can add to it */
95           break;
96      }
97    return total_closed; 
98 }