Change the mapping of file descriptors to FILE *
diff --git a/include/stdio.h b/include/stdio.h
index f57439f..31a1fe4 100644
--- a/include/stdio.h
+++ b/include/stdio.h
@@ -31,15 +31,22 @@
#define SEEK_CUR 1
#define SEEK_END 2
+/*
+ * Convert between a FILE * and a file descriptor. We don't actually
+ * have any in-memory data, so we just abuse the pointer itself to
+ * hold the data. Note, however, that for file descriptors, -1 is
+ * error and 0 is a valid value; for FILE *, NULL (0) is error and
+ * non-NULL are valid.
+ */
static __inline__ int fileno(FILE *__f)
{
/* This should really be intptr_t, but size_t should be the same size */
- return (int)(size_t)__f;
+ return (int)(size_t)__f - 1;
}
static __inline__ FILE * __create_file(int __fd)
{
- return (FILE *)(size_t)__fd;
+ return (FILE *)(size_t)(__fd + 1);
}
__extern FILE *fopen(const char *, const char *);
diff --git a/klibc/fopen.c b/klibc/fopen.c
index 5c84184..ee62c68 100644
--- a/klibc/fopen.c
+++ b/klibc/fopen.c
@@ -13,10 +13,9 @@
{
int flags = O_RDONLY;
int plus = 0;
- int fd;
while ( *mode ) {
- switch ( *mode ) {
+ switch ( *mode++ ) {
case 'r':
flags = O_RDONLY;
break;
@@ -30,17 +29,12 @@
plus = 1;
break;
}
- mode++;
}
if ( plus ) {
flags = (flags & ~(O_RDONLY|O_WRONLY)) | O_RDWR;
}
- fd = open(file, flags, 0666);
-
- if ( fd < 0 )
- return NULL;
- else
- return fdopen(fd, mode);
+ /* Note: __create_file(-1) == NULL, so this is safe */
+ return __create_file(open(file, flags, 0666));
}
diff --git a/klibc/include/stdio.h b/klibc/include/stdio.h
index f57439f..31a1fe4 100644
--- a/klibc/include/stdio.h
+++ b/klibc/include/stdio.h
@@ -31,15 +31,22 @@
#define SEEK_CUR 1
#define SEEK_END 2
+/*
+ * Convert between a FILE * and a file descriptor. We don't actually
+ * have any in-memory data, so we just abuse the pointer itself to
+ * hold the data. Note, however, that for file descriptors, -1 is
+ * error and 0 is a valid value; for FILE *, NULL (0) is error and
+ * non-NULL are valid.
+ */
static __inline__ int fileno(FILE *__f)
{
/* This should really be intptr_t, but size_t should be the same size */
- return (int)(size_t)__f;
+ return (int)(size_t)__f - 1;
}
static __inline__ FILE * __create_file(int __fd)
{
- return (FILE *)(size_t)__fd;
+ return (FILE *)(size_t)(__fd + 1);
}
__extern FILE *fopen(const char *, const char *);