summaryrefslogtreecommitdiff
path: root/lib/libc/stdio/fflush.c
diff options
context:
space:
mode:
authorKacper <kacper@mail.openlinux.dev>2025-12-22 23:27:56 +0100
committerKacper <kacper@mail.openlinux.dev>2025-12-22 23:30:32 +0100
commit0f30d227497418c6d3bef7d52244407e30454504 (patch)
tree0e1ac19623d3268380cf74328cdf643648a2f43c /lib/libc/stdio/fflush.c
parent90dad97fc07f049383903a166631e2c257f9b8c1 (diff)
Added c11 threads, fixed some locks and add *_unlocked functions
Diffstat (limited to 'lib/libc/stdio/fflush.c')
-rw-r--r--lib/libc/stdio/fflush.c73
1 files changed, 7 insertions, 66 deletions
diff --git a/lib/libc/stdio/fflush.c b/lib/libc/stdio/fflush.c
index 1cf4b7bd..b3fca8bd 100644
--- a/lib/libc/stdio/fflush.c
+++ b/lib/libc/stdio/fflush.c
@@ -3,74 +3,15 @@
#include <atomic.h> // for LIBC_UNLOCK, LIBC_LOCK
#include <errno.h> // for errno, EBADF, EIO
-#include <fcntl.h> // for O_ACCMODE, O_RDONLY
-#include <stdio.h> // for EOF, FILE, fflush
-#include <string.h> // for memmove
-#include <unistd.h> // for size_t, write, ssize_t
+#include <stdio.h>
-int fflush(FILE *stream)
+int fflush(struct __FILE *stream)
{
- if (stream == NULL) {
- // TODO: Implement flushing all open streams
- // For now, just return success
- return 0;
- }
+ int r;
- if (__FILE(stream)->buf_len == 0) {
- return 0;
- }
+ flockfile(stream);
+ r = fflush_unlocked(stream);
+ funlockfile(stream);
- if (__FILE(stream)->fd == -1) {
- __FILE(stream)->buf_len = 0;
- return 0;
- }
-
- if (__FILE(stream)->flags & _IO_ERR) {
- errno = EIO;
- return EOF;
- }
-
- if ((__FILE(stream)->flags & O_ACCMODE) == O_RDONLY) {
- errno = EBADF;
- return EOF;
- }
-
- LIBC_LOCK(__FILE(stream)->lock);
-
- size_t bytes_to_write = __FILE(stream)->buf_len;
- size_t total_written = 0;
- char *buf_ptr = __FILE(stream)->buf;
-
- while (total_written < bytes_to_write) {
- ssize_t result = write(__FILE(stream)->fd,
- buf_ptr + total_written,
- bytes_to_write - total_written);
-
- if (result < 0) {
- __FILE(stream)->flags |= _IO_ERR;
- LIBC_UNLOCK(__FILE(stream)->lock);
- return EOF;
- }
-
- if (result == 0) {
- break;
- }
-
- total_written += result;
- }
-
- if (total_written == bytes_to_write) {
- __FILE(stream)->buf_len = 0;
- __FILE(stream)->buf_pos = 0;
- } else {
- size_t remaining = bytes_to_write - total_written;
- memmove(__FILE(stream)->buf,
- __FILE(stream)->buf + total_written, remaining);
- __FILE(stream)->buf_len = remaining;
- __FILE(stream)->buf_pos = 0;
- }
-
- LIBC_UNLOCK(__FILE(stream)->lock);
-
- return (total_written == bytes_to_write) ? 0 : EOF;
+ return r;
}