diff options
| author | Kacper <kacper@mail.openlinux.dev> | 2025-12-22 23:27:56 +0100 |
|---|---|---|
| committer | Kacper <kacper@mail.openlinux.dev> | 2025-12-22 23:30:32 +0100 |
| commit | 0f30d227497418c6d3bef7d52244407e30454504 (patch) | |
| tree | 0e1ac19623d3268380cf74328cdf643648a2f43c /lib/libc/stdio/fflush_unlocked.c | |
| parent | 90dad97fc07f049383903a166631e2c257f9b8c1 (diff) | |
Added c11 threads, fixed some locks and add *_unlocked functions
Diffstat (limited to 'lib/libc/stdio/fflush_unlocked.c')
| -rw-r--r-- | lib/libc/stdio/fflush_unlocked.c | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/lib/libc/stdio/fflush_unlocked.c b/lib/libc/stdio/fflush_unlocked.c new file mode 100644 index 00000000..b4ee3e43 --- /dev/null +++ b/lib/libc/stdio/fflush_unlocked.c @@ -0,0 +1,64 @@ +#include <__stdio.h> +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <sys/cdefs.h> +#include <unistd.h> + +int fflush_unlocked(struct __FILE *stream) +{ + if (stream == NULL) { + // TODO: flush all streams + return 0; + } + + if (__predict_false(stream->fd) == -1) { + stream->buf_len = 0; + return 0; + } + + if (__predict_false(stream->buf == 0)) { + return 0; + } + + if (stream->flags & _IO_ERR) { + errno = EIO; + return EOF; + } + + if ((stream->flags & O_ACCMODE) == O_RDONLY) { + errno = EBADF; + return EOF; + } + + size_t bytes_to_write = stream->buf_len; + size_t total_written = 0; + char *buf_ptr = stream->buf; + + while (total_written < bytes_to_write) { + ssize_t result = write(stream->fd, buf_ptr + total_written, bytes_to_write - total_written); + + if (result < 0) { + stream->flags |= _IO_ERR; + return EOF; + } + + if (result == 0) { + break; + } + + total_written += result; + } + + if (total_written == bytes_to_write) { + stream->buf_len = 0; + stream->buf_pos = 0; + } else { + size_t remaining = bytes_to_write - total_written; + memmove(stream->buf, stream->buf + total_written, remaining); + stream->buf_len = remaining; + stream->buf_pos = 0; + } + + return (total_written == bytes_to_write) ? 0 : EOF; +} |
