PatchworkOS
Loading...
Searching...
No Matches
fopen.c
Go to the documentation of this file.
1#include <stdio.h>
2
3#include "user/common/file.h"
5
6static const char* _flags_to_string(_file_flags_t flags)
7{
8 switch (flags & (_FILE_READ | _FILE_WRITE | _FILE_APPEND | _FILE_RW))
9 {
10 case _FILE_READ:
11 return "";
12 case _FILE_WRITE:
13 return ":create:trunc";
14 case _FILE_APPEND:
15 return ":append:create";
16 case _FILE_READ | _FILE_RW:
17 return "";
18 case _FILE_WRITE | _FILE_RW:
19 return ":trunc:create";
21 return ":append:create";
22 default:
23 return "";
24 }
25}
26
27FILE* fopen(const char* _RESTRICT filename, const char* _RESTRICT mode)
28{
29 _file_flags_t flags = _file_flags_parse(mode);
30 if (flags == 0)
31 {
32 errno = EINVAL;
33 return NULL;
34 }
35
36 if (filename == NULL || filename[0] == '\0')
37 {
38 errno = EINVAL;
39 return NULL;
40 }
41
42 fd_t fd = openf("%s%s", filename, _flags_to_string(flags));
43 if (fd == ERR)
44 {
45 return NULL;
46 }
47
48 FILE* stream = _file_new();
49 if (stream == NULL)
50 {
51 errno = ENOMEM;
52 close(fd);
53 return NULL;
54 }
55
56 if (_file_init(stream, fd, flags | _FILE_FULLY_BUFFERED, NULL, BUFSIZ) == ERR)
57 {
58 errno = ENOMEM;
59 close(fd);
60 _file_free(stream);
61 return NULL;
62 }
63
64 _files_push(stream);
65 return stream;
66}
static const char * _flags_to_string(_file_flags_t flags)
Definition fopen.c:6
FILE * fopen(const char *_RESTRICT filename, const char *_RESTRICT mode)
Definition fopen.c:27
#define EINVAL
Invalid argument.
Definition errno.h:142
#define ENOMEM
Out of memory.
Definition errno.h:92
#define errno
Error number variable.
Definition errno.h:27
uint64_t close(fd_t fd)
System call for closing files.
Definition close.c:9
fd_t openf(const char *_RESTRICT format,...)
Wrapper for opening files with a formatted path.
Definition openf.c:9
#define NULL
Pointer error value.
Definition NULL.h:23
#define ERR
Integer error value.
Definition ERR.h:17
__UINT64_TYPE__ fd_t
A file descriptor.
Definition fd_t.h:12
#define _RESTRICT
Definition config.h:17
FILE * _file_new(void)
Definition file.c:80
void _files_push(FILE *file)
Definition file.c:264
void _file_free(FILE *stream)
Definition file.c:92
_file_flags_t _file_flags_parse(const char *mode)
Definition file.c:12
uint64_t _file_init(FILE *stream, fd_t fd, _file_flags_t flags, void *buffer, uint64_t bufferSize)
Definition file.c:100
_file_flags_t
Definition file.h:9
@ _FILE_READ
Definition file.h:10
@ _FILE_WRITE
Definition file.h:11
@ _FILE_FULLY_BUFFERED
Definition file.h:16
@ _FILE_RW
Definition file.h:12
@ _FILE_APPEND
Definition file.h:13
#define BUFSIZ
Definition stdio.h:26
Definition file.h:34