Willem
8/27/2011 3:19:00 PM
pozz wrote:
) Consider the fopen:
)
) FILE * fopen (const char *filename, const char *opentype)
)
) The mechanism is simple: the I/O library doesn't know in advance how
) many files the user developer will want to manage at the same time, so
) fopen() dynamically allocates the FILE object and returns it if the
) operation is successful.
Not quite true, a lot of OSes have limits on how many files a program can
have open at a one time. Remember the days of DOS where you had to set
Files=255 in your startup files ?
) How may I mimic this behaviour in my API? Now I have two possibilities,
) but I couldn't choose one.
)
) First approach. The code that calls the function should allocate the
) FILE object and pass it to the API functions. The fopen function will be:
)
) int myfopen (FILE *stream, const char *filename, const char *opentype)
)
) The con of this approach is that the function interface is different so
) it will be costly, in the future, to switch to a platform with
) malloc/free facilities (where I'll use an interface similar to standard
) I/O functions).
That's a big con.
) Second approach. Adding an intermediate level that allocates and manage
) a maximum number of objects (configurable as a probject basis).
)
) /* middle_level.c */
) FILE files[CONFIG_MAXFILES];
)
) FILE * myfopen (const char *filename, const char *opentype) {
) FILE *freefile = NULL;
) unsigned int i;
) for (i = 0; i < CONFIG_MAXFILES; i++) {
) if (file_isused(&files[i])) {
ITYM: if (file_notused(&files[i]))
) freefile = &files[i];
Why not do:
myfopen_low(freefile, filename, opentype);
return freefile;
here, instead of the break ?
Anyway, you probably want:
if (myfopen_low(freefile, filename, opentype)) {
return freefile;
}
return NULL;
) break;
) }
) }
Then you don't need this code here
) if (freefile == NULL) {
However, you might want to set 'errno' here ?
) return NULL;
) }
) myfopen_low(freefile, filename, opentype);
) return freefile;
) }
)
) Every time I need a new FILE object (like in myfopen), instead of
) dynamically allocation, I have to search for a free (not used) object in
) the files[] array. In other words, I create a micro and simple dynamic
) allocation facilities that manage only FILE object.
Sounds like the better approach to me. And to you too, as you don't list
any cons. Well, the big con is obviously the (low?) limit on open files.
) What do you suggest? Are there any other better approaches?
A pool of file descriptors sounds good.
SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT