summaryrefslogtreecommitdiff
path: root/userland/libc/stdio/fopen.c
blob: 6a3f374896c65871246215e2c4c4d04a7dbd4856 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/stat.h>

// FIXME: All modes not implemented
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html
FILE *fopen(const char *pathname, const char *mode) {
  uint8_t read = 0;
  uint8_t write = 0;
  uint8_t append = 0;
  // FIXME: Not parsed correctly
  for (; *mode; mode++) {
    // r or rb
    // Open file for reading.
    // w or wb
    // Truncate to zero length or create file for writing.
    // a or ab
    // Append; open or create file for writing at
    // end-of-file.
    switch (*mode) {
    case 'r':
      read = 1;
      break;
    case 'w':
      write = 1;
      break;
    case 'a':
      append = 1;
      break;
    }
  }
  int flag = 0;
  if (read)
    flag |= O_READ;
  if (write)
    flag |= O_WRITE;

  int fd = open(pathname, flag, 0);
  if (-1 == fd)
    return NULL;

  struct stat s;
  stat(pathname, &s);

  FILE *r = malloc(sizeof(FILE));
  r->read = read_fd;
  r->write = write_fd;
  r->seek = seek_fd;
  r->has_error = 0;
  r->is_eof = 0;
  r->offset_in_file = 0;
  r->file_size = s.st_size;
  r->cookie = NULL;
  r->fd = fd;
  r->read_buffer = NULL;
  r->read_buffer_stored = 0;
  return r;
}