libc: Add fdopen()

This commit is contained in:
apio 2022-10-12 20:19:13 +02:00
parent 52944ba5d8
commit de6041fede
2 changed files with 16 additions and 0 deletions

View File

@ -32,6 +32,9 @@ extern "C"
/* Opens the file specified by pathname. Returns the file handle on success, or NULL on error. */ /* Opens the file specified by pathname. Returns the file handle on success, or NULL on error. */
FILE* fopen(const char* pathname, const char* mode); FILE* fopen(const char* pathname, const char* mode);
/* Returns a new file associated with the file descriptor fd. */
FILE* fdopen(int fd, const char* mode);
/* Writes formatted output according to the string format to the file stream. */ /* Writes formatted output according to the string format to the file stream. */
int fprintf(FILE* stream, const char* format, ...); int fprintf(FILE* stream, const char* format, ...);

View File

@ -40,6 +40,19 @@ extern "C"
return stream; return stream;
} }
FILE* fdopen(int fd, const char*)
{
if (fd < 0) // FIXME: Also check if the mode string is compatible with how fd was opened.
{
errno = EBADF;
return 0;
}
FILE* stream = (FILE*)malloc(sizeof(FILE));
stream->f_fd = fd;
clearerr(stream);
return stream;
}
size_t fread(void* buf, size_t size, size_t nmemb, FILE* stream) size_t fread(void* buf, size_t size, size_t nmemb, FILE* stream)
{ {
ssize_t status = read(stream->f_fd, buf, size * nmemb); ssize_t status = read(stream->f_fd, buf, size * nmemb);