2022-10-10 19:18:24 +00:00
|
|
|
#include <errno.h>
|
2022-10-10 19:08:57 +00:00
|
|
|
#include <fcntl.h>
|
|
|
|
#include <luna.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
|
|
|
|
extern "C"
|
|
|
|
{
|
|
|
|
int fclose(FILE* stream)
|
|
|
|
{
|
2022-10-11 14:57:08 +00:00
|
|
|
int status = close(stream->f_fd);
|
2022-10-10 19:18:24 +00:00
|
|
|
if (status < 0)
|
|
|
|
{
|
|
|
|
int savederr = errno;
|
|
|
|
free(stream); // We do not want to leak memory. man fclose(3) says that whether fclose() fails or not, any
|
|
|
|
// further operation on the stream results in undefined behavior. So we are free to free the
|
|
|
|
// stream.
|
|
|
|
errno = savederr; // free might reset errno. We don't want that.
|
|
|
|
}
|
|
|
|
else { free(stream); }
|
2022-10-10 19:08:57 +00:00
|
|
|
return status;
|
|
|
|
}
|
|
|
|
|
|
|
|
int fflush(FILE*)
|
|
|
|
{
|
|
|
|
return 0; // FIXME: Implement buffered IO.
|
|
|
|
}
|
|
|
|
|
|
|
|
FILE* fopen(const char* pathname, const char*)
|
|
|
|
{
|
|
|
|
int fd = open(pathname, O_RDONLY); // FIXME: Use the mode string.
|
|
|
|
if (fd < 0) { return 0; }
|
|
|
|
FILE* stream = (FILE*)malloc(sizeof(FILE));
|
2022-10-11 14:57:08 +00:00
|
|
|
stream->f_fd = fd;
|
|
|
|
clearerr(stream);
|
2022-10-10 19:08:57 +00:00
|
|
|
return stream;
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t fread(void* buf, size_t size, size_t nmemb, FILE* stream)
|
|
|
|
{
|
2022-10-11 14:57:08 +00:00
|
|
|
ssize_t status = read(stream->f_fd, buf, size * nmemb);
|
2022-10-10 19:08:57 +00:00
|
|
|
if (status < 0)
|
2022-10-11 14:57:08 +00:00
|
|
|
{
|
|
|
|
stream->f_err = 1;
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
if (status == 0) stream->f_eof = 1;
|
2022-10-10 19:08:57 +00:00
|
|
|
return (size_t)status;
|
|
|
|
}
|
|
|
|
|
2022-10-11 14:57:08 +00:00
|
|
|
int ferror(FILE* stream)
|
|
|
|
{
|
|
|
|
return stream->f_err;
|
|
|
|
}
|
|
|
|
|
|
|
|
int feof(FILE* stream)
|
|
|
|
{
|
|
|
|
return stream->f_eof;
|
|
|
|
}
|
|
|
|
|
|
|
|
void clearerr(FILE* stream)
|
|
|
|
{
|
|
|
|
stream->f_err = stream->f_eof = 0;
|
|
|
|
}
|
|
|
|
|
2022-10-10 19:08:57 +00:00
|
|
|
int fseek(FILE*, long, int)
|
|
|
|
{
|
|
|
|
NOT_IMPLEMENTED("fseek");
|
|
|
|
}
|
|
|
|
|
|
|
|
long ftell(FILE*)
|
|
|
|
{
|
|
|
|
NOT_IMPLEMENTED("ftell");
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t fwrite(const void*, size_t, size_t, FILE*)
|
|
|
|
{
|
|
|
|
NOT_IMPLEMENTED("fwrite");
|
|
|
|
}
|
|
|
|
|
|
|
|
void setbuf(FILE*, char*)
|
|
|
|
{
|
|
|
|
NOT_IMPLEMENTED("setbuf");
|
|
|
|
}
|
|
|
|
}
|