1 #include <fcntl.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <unistd.h>
6 
fprintf(FILE * restrict stream,const char * restrict format,...)7 int fprintf(FILE *restrict stream, const char *restrict format, ...)
8 {
9     const int bufsize = 65536 * 2;
10     char *buf = malloc(bufsize);
11     memset(buf, 0, bufsize);
12     va_list args;
13 
14     va_start(args, format);
15     vsprintf(buf, format, args);
16     va_end(args);
17 
18     int len = strlen(buf);
19     if (len > bufsize - 1)
20     {
21         len = bufsize - 1;
22         buf[bufsize - 1] = 0;
23     }
24     write(stream->fd, buf, len);
25     free(buf);
26 }
27 
puts(const char * s)28 int puts(const char *s)
29 {
30     return put_string(s, COLOR_WHITE, COLOR_BLACK);
31 }
32 
putchar(int c)33 int putchar(int c)
34 {
35     return printf("%c", (char)c);
36 }
37 
fflush(FILE * stream)38 int fflush(FILE *stream)
39 {
40     return 0;
41 }
42 
ferror(FILE * stream)43 int ferror(FILE *stream)
44 {
45     return 0;
46 }
47 
fclose(FILE * stream)48 int fclose(FILE *stream)
49 {
50     if (stream->fd >= 3)
51     {
52         int retcval = close(stream->fd);
53         free(stream);
54         return 0;
55     }
56     else
57         return 0;
58 }
59 
60 // FIXME: 请注意,这个函数的实现,没有遵照posix,行为也与Linux的不一致,请在将来用Rust重构时改变它,以使得它的行为与Linux的一致。
fopen(const char * restrict pathname,const char * restrict mode)61 FILE *fopen(const char *restrict pathname, const char *restrict mode)
62 {
63     FILE *stream = malloc(sizeof(FILE));
64     memset(stream, 0, sizeof(FILE));
65     int o_flags = 0;
66 
67     if (strcmp(mode, "r") == 0)
68         o_flags = O_RDONLY;
69     else if (strcmp(mode, "r+") == 0)
70         o_flags = O_RDWR;
71     else if (strcmp(mode, "w") == 0)
72         o_flags = O_WRONLY;
73     else if (strcmp(mode, "w+") == 0)
74         o_flags = O_RDWR | O_CREAT;
75     else if (strcmp(mode, "a") == 0)
76         o_flags = O_APPEND | O_CREAT;
77     else if (strcmp(mode, "a+") == 0)
78         o_flags = O_APPEND | O_CREAT;
79 
80     int fd = open(pathname, o_flags);
81     if (fd >= 0)
82         stream->fd = fd;
83     return stream;
84 }
85