Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
struct file_descriptor
{
// implementation goes here
int read(char * destination, int count);
int write(char * source, int count);
};
struct disk_file : public file_descriptor
{
// route requests to disk I/O functions
int read(char * destination, int count);
int write(char * source, int count);
}
struct socket_file : public file_descriptor
{
// route requests to network I/O functions
int read(char * destination, int count);
int write(char * source, int count);
}
// kernel keeps record of the list of file descriptors you have open
int file_descriptor_count = /* some value meaning the maximum number of open files you are permitted to have */
file_descriptor * descriptors = malloc(file_descriptor, sizeof(file_descriptor) * file_descriptor_count;
// read() will read `count` bytes from the _file descriptor_ and put into `destination`.
// it will return the number of bytes which were successfully read (which may be different from the count you requested
// or it will set errno to an appropriate _error reason_ and return -1 if an error occurred.
int read(int fd_value, char * destination, int count)
{
if ( (fd_value < 0) || (file_descriptor_count <= fd_value)|| (nullptr == destination) )
{
errno = /* something from #include <errno.h> which meands you gave bad function arguments */
return -1;
}
// hand the request off to the file descriptor
return descriptors[fd_value].read(destination, count);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment