libc: Parse the mode string
This commit is contained in:
parent
8ed0ff1381
commit
b2f321c0b8
@ -3,13 +3,14 @@
|
|||||||
#include <luna.h>
|
#include <luna.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
|
|
||||||
FILE* stderr;
|
FILE* stderr;
|
||||||
FILE* stdout;
|
FILE* stdout;
|
||||||
FILE* stdin;
|
FILE* stdin;
|
||||||
|
|
||||||
void file_read_buf(FILE* stream)
|
static void file_read_buf(FILE* stream)
|
||||||
{
|
{
|
||||||
if (!stream->f_buf)
|
if (!stream->f_buf)
|
||||||
{
|
{
|
||||||
@ -31,6 +32,29 @@ void file_read_buf(FILE* stream)
|
|||||||
stream->f_bufsize = nread;
|
stream->f_bufsize = nread;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static int file_parse_mode(const char* mode)
|
||||||
|
{
|
||||||
|
int flags = 0;
|
||||||
|
switch (mode[0])
|
||||||
|
{
|
||||||
|
case 'r': flags |= O_RDONLY; break;
|
||||||
|
case 'w':
|
||||||
|
flags |= O_WRONLY;
|
||||||
|
flags |= O_CREAT;
|
||||||
|
flags |= O_TRUNC;
|
||||||
|
break;
|
||||||
|
case 'a':
|
||||||
|
flags |= O_WRONLY;
|
||||||
|
flags |= O_CREAT;
|
||||||
|
flags |= O_APPEND;
|
||||||
|
break;
|
||||||
|
default: errno = EINVAL; return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (strchr(mode, '+')) flags |= O_RDWR;
|
||||||
|
return flags;
|
||||||
|
}
|
||||||
|
|
||||||
extern "C"
|
extern "C"
|
||||||
{
|
{
|
||||||
int fclose(FILE* stream)
|
int fclose(FILE* stream)
|
||||||
@ -56,7 +80,9 @@ extern "C"
|
|||||||
|
|
||||||
FILE* fopen(const char* pathname, const char* mode)
|
FILE* fopen(const char* pathname, const char* mode)
|
||||||
{
|
{
|
||||||
int fd = open(pathname, O_RDWR); // FIXME: Use the mode string.
|
int flags = file_parse_mode(mode);
|
||||||
|
if (flags < 0) return NULL;
|
||||||
|
int fd = open(pathname, flags, 0666); // If we create the file, create it as rw-rw-rw-.
|
||||||
if (fd < 0) { return 0; }
|
if (fd < 0) { return 0; }
|
||||||
return fdopen(fd, mode);
|
return fdopen(fd, mode);
|
||||||
}
|
}
|
||||||
@ -78,10 +104,12 @@ extern "C"
|
|||||||
return stream;
|
return stream;
|
||||||
}
|
}
|
||||||
|
|
||||||
FILE* freopen(const char* pathname, const char*,
|
FILE* freopen(const char* pathname, const char* mode,
|
||||||
FILE* stream) // FIXME: If pathname is NULL, open the original file with the new mode.
|
FILE* stream) // FIXME: If pathname is NULL, open the original file with the new mode.
|
||||||
{
|
{
|
||||||
int fd = open(pathname, O_RDWR); // FIXME: Use the mode string.
|
int flags = file_parse_mode(mode);
|
||||||
|
if (flags < 0) return NULL;
|
||||||
|
int fd = open(pathname, flags, 0666); // If we create the file, create it as rw-rw-rw-.
|
||||||
if (fd < 0) { return 0; }
|
if (fd < 0) { return 0; }
|
||||||
|
|
||||||
fflush(stream); // To make it future-proof.
|
fflush(stream); // To make it future-proof.
|
||||||
|
Loading…
Reference in New Issue
Block a user