source: mainline/uspace/lib/posix/source/stdio.c@ f1f7584

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since f1f7584 was 80bee81, checked in by Jiri Svoboda <jiri@…>, 10 years ago

freopen() goes home too.

  • Property mode set to 100644
File size: 17.1 KB
RevLine 
[09b0b1fb]1/*
2 * Copyright (c) 2011 Jiri Zarevucky
[4f4b4e7]3 * Copyright (c) 2011 Petr Koupy
[09b0b1fb]4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * - The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30/** @addtogroup libposix
31 * @{
32 */
[4cf8ca6]33/** @file Standard buffered input/output.
[09b0b1fb]34 */
35
[491e1ee]36#define LIBPOSIX_INTERNAL
[fdf97f6]37#define __POSIX_DEF__(x) posix_##x
[09b0b1fb]38
[9b1503e]39#include "internal/common.h"
[a3da2b2]40#include "posix/stdio.h"
[a6d908c1]41
[a3da2b2]42#include "posix/assert.h"
43#include "posix/errno.h"
44#include "posix/stdlib.h"
45#include "posix/string.h"
46#include "posix/sys/types.h"
47#include "posix/unistd.h"
[4f4b4e7]48
[32b3a12]49#include "libc/stdio.h"
[a6d908c1]50#include "libc/io/printf_core.h"
[3e6a98c5]51#include "libc/stdbool.h"
[a6d908c1]52#include "libc/str.h"
[08053f7]53#include "libc/malloc.h"
[fd4b636]54#include "libc/adt/list.h"
55#include "libc/sys/stat.h"
[a6d908c1]56
[8b5fb5e]57/** Clears the stream's error and end-of-file indicators.
58 *
[1978a5f]59 * @param stream Stream whose indicators shall be cleared.
[8b5fb5e]60 */
61void posix_clearerr(FILE *stream)
62{
[80bee81]63 clearerr(stream);
[8b5fb5e]64}
65
66/**
[1978a5f]67 * Generate a pathname for the controlling terminal.
[8b5fb5e]68 *
[1978a5f]69 * @param s Allocated buffer to which the pathname shall be put.
70 * @return Either s or static location filled with the requested pathname.
[8b5fb5e]71 */
72char *posix_ctermid(char *s)
73{
74 /* Currently always returns an error value (empty string). */
75 // TODO: return a real terminal path
76
77 static char dummy_path[L_ctermid] = {'\0'};
78
79 if (s == NULL) {
80 return dummy_path;
81 }
82
83 s[0] = '\0';
84 return s;
85}
86
[221afc9e]87/**
88 * Put a string on the stream.
89 *
90 * @param s String to be written.
91 * @param stream Output stream.
92 * @return Non-negative on success, EOF on failure.
93 */
94int posix_fputs(const char *restrict s, FILE *restrict stream)
95{
[7db5cfd]96 return fputs(s, stream);
[221afc9e]97}
98
[59f799b]99/**
[1978a5f]100 * Push byte back into input stream.
[59f799b]101 *
[1978a5f]102 * @param c Byte to be pushed back.
103 * @param stream Stream to where the byte shall be pushed.
[08053f7]104 * @return Provided byte on success or EOF if not possible.
[59f799b]105 */
106int posix_ungetc(int c, FILE *stream)
107{
[bd5414e]108 return ungetc(c, stream);
[59f799b]109}
110
[1978a5f]111/**
[08053f7]112 * Read a stream until the delimiter (or EOF) is encountered.
[1978a5f]113 *
[08053f7]114 * @param lineptr Pointer to the output buffer in which there will be stored
115 * nul-terminated string together with the delimiter (if encountered).
116 * Will be resized if necessary.
117 * @param n Pointer to the size of the output buffer. Will be increased if
118 * necessary.
119 * @param delimiter Delimiter on which to finish reading the stream.
120 * @param stream Input stream.
121 * @return Number of fetched characters (including delimiter if encountered)
122 * or -1 on error (set in errno).
[1978a5f]123 */
[8b5fb5e]124ssize_t posix_getdelim(char **restrict lineptr, size_t *restrict n,
125 int delimiter, FILE *restrict stream)
126{
[08053f7]127 /* Check arguments for sanity. */
128 if (!lineptr || !n) {
129 errno = EINVAL;
130 return -1;
131 }
132
133 size_t alloc_step = 80; /* Buffer size gain during reallocation. */
134 char *pos = *lineptr; /* Next free byte of the output buffer. */
135 size_t cnt = 0; /* Number of fetched characters. */
136 int c = fgetc(stream); /* Current input character. Might be EOF. */
137
138 do {
139 /* Mask EOF as NUL to terminate string. */
140 if (c == EOF) {
141 c = '\0';
142 }
143
144 /* Ensure there is still space left in the buffer. */
145 if (pos == *lineptr + *n) {
146 *lineptr = realloc(*lineptr, *n + alloc_step);
147 if (*lineptr) {
148 pos = *lineptr + *n;
149 *n += alloc_step;
150 } else {
151 errno = ENOMEM;
152 return -1;
153 }
154 }
155
156 /* Store the fetched character. */
157 *pos = c;
158
159 /* Fetch the next character according to the current character. */
160 if (c != '\0') {
161 ++pos;
162 ++cnt;
163 if (c == delimiter) {
164 /* Delimiter was just stored. Provide EOF as the next
165 * character - it will be masked as NUL and output string
166 * will be properly terminated. */
167 c = EOF;
168 } else {
169 /* Neither delimiter nor EOF were encountered. Just fetch
170 * the next character from the stream. */
171 c = fgetc(stream);
172 }
173 }
174 } while (c != '\0');
175
176 if (errno == EOK && cnt > 0) {
177 return cnt;
178 } else {
179 /* Either some error occured or the stream was already at EOF. */
180 return -1;
181 }
[8b5fb5e]182}
183
[1978a5f]184/**
[08053f7]185 * Read a stream until the newline (or EOF) is encountered.
[1978a5f]186 *
[08053f7]187 * @param lineptr Pointer to the output buffer in which there will be stored
188 * nul-terminated string together with the delimiter (if encountered).
189 * Will be resized if necessary.
190 * @param n Pointer to the size of the output buffer. Will be increased if
191 * necessary.
192 * @param stream Input stream.
193 * @return Number of fetched characters (including newline if encountered)
194 * or -1 on error (set in errno).
[1978a5f]195 */
[8b5fb5e]196ssize_t posix_getline(char **restrict lineptr, size_t *restrict n,
197 FILE *restrict stream)
198{
[08053f7]199 return posix_getdelim(lineptr, n, '\n', stream);
[8b5fb5e]200}
201
[4f4b4e7]202/**
[1978a5f]203 * Reopen a file stream.
[4f4b4e7]204 *
[1978a5f]205 * @param filename Pathname of a file to be reopened or NULL for changing
206 * the mode of the stream.
207 * @param mode Mode to be used for reopening the file or changing current
208 * mode of the stream.
209 * @param stream Current stream associated with the opened file.
210 * @return On success, either a stream of the reopened file or the provided
211 * stream with a changed mode. NULL otherwise.
[4f4b4e7]212 */
[46ac986]213FILE *posix_freopen(const char *restrict filename,
214 const char *restrict mode, FILE *restrict stream)
[09b0b1fb]215{
[80bee81]216 return freopen(filename, mode, stream);
[09b0b1fb]217}
218
[4f4b4e7]219/**
[1978a5f]220 * Write error messages to standard error.
[4f4b4e7]221 *
[1978a5f]222 * @param s Error message.
[4f4b4e7]223 */
[09b0b1fb]224void posix_perror(const char *s)
225{
[8b5fb5e]226 if (s == NULL || s[0] == '\0') {
227 fprintf(stderr, "%s\n", posix_strerror(errno));
228 } else {
229 fprintf(stderr, "%s: %s\n", s, posix_strerror(errno));
230 }
231}
232
233/** Restores stream a to position previously saved with fgetpos().
234 *
235 * @param stream Stream to restore
236 * @param pos Position to restore
237 * @return Zero on success, non-zero (with errno set) on failure
238 */
239int posix_fsetpos(FILE *stream, const posix_fpos_t *pos)
240{
241 return fseek(stream, pos->offset, SEEK_SET);
242}
243
244/** Saves the stream's position for later use by fsetpos().
245 *
246 * @param stream Stream to save
247 * @param pos Place to store the position
248 * @return Zero on success, non-zero (with errno set) on failure
249 */
250int posix_fgetpos(FILE *restrict stream, posix_fpos_t *restrict pos)
251{
252 off64_t ret = ftell(stream);
[cfbb5d18]253 if (ret != -1) {
254 pos->offset = ret;
255 return 0;
256 } else {
257 return -1;
[8b5fb5e]258 }
259}
260
261/**
[1978a5f]262 * Reposition a file-position indicator in a stream.
[8b5fb5e]263 *
[1978a5f]264 * @param stream Stream to seek in.
265 * @param offset Direction and amount of bytes to seek.
266 * @param whence From where to seek.
267 * @return Zero on success, -1 otherwise.
[8b5fb5e]268 */
269int posix_fseek(FILE *stream, long offset, int whence)
270{
271 return fseek(stream, (off64_t) offset, whence);
[09b0b1fb]272}
273
[b08ef1fd]274/**
[1978a5f]275 * Reposition a file-position indicator in a stream.
[b08ef1fd]276 *
[1978a5f]277 * @param stream Stream to seek in.
278 * @param offset Direction and amount of bytes to seek.
279 * @param whence From where to seek.
280 * @return Zero on success, -1 otherwise.
[b08ef1fd]281 */
282int posix_fseeko(FILE *stream, posix_off_t offset, int whence)
283{
[8b5fb5e]284 return fseek(stream, (off64_t) offset, whence);
285}
286
287/**
[1978a5f]288 * Discover current file offset in a stream.
[8b5fb5e]289 *
[1978a5f]290 * @param stream Stream for which the offset shall be retrieved.
291 * @return Current offset or -1 if not possible.
[8b5fb5e]292 */
293long posix_ftell(FILE *stream)
294{
295 return (long) ftell(stream);
[b08ef1fd]296}
297
298/**
[1978a5f]299 * Discover current file offset in a stream.
[b08ef1fd]300 *
[1978a5f]301 * @param stream Stream for which the offset shall be retrieved.
302 * @return Current offset or -1 if not possible.
[b08ef1fd]303 */
304posix_off_t posix_ftello(FILE *stream)
305{
[8b5fb5e]306 return (posix_off_t) ftell(stream);
307}
308
[221afc9e]309/**
310 * Discard prefetched data or write unwritten data.
311 *
312 * @param stream Stream that shall be flushed.
313 * @return Zero on success, EOF on failure.
314 */
315int posix_fflush(FILE *stream)
316{
317 int rc = fflush(stream);
318 if (rc < 0) {
319 errno = -rc;
320 return EOF;
321 } else {
322 return 0;
323 }
324}
325
[1978a5f]326/**
327 * Print formatted output to the opened file.
328 *
329 * @param fildes File descriptor of the opened file.
330 * @param format Format description.
331 * @return Either the number of printed characters or negative value on error.
332 */
[8b5fb5e]333int posix_dprintf(int fildes, const char *restrict format, ...)
334{
335 va_list list;
336 va_start(list, format);
337 int result = posix_vdprintf(fildes, format, list);
338 va_end(list);
339 return result;
340}
341
[1978a5f]342/**
343 * Write ordinary string to the opened file.
344 *
345 * @param str String to be written.
346 * @param size Size of the string (in bytes)..
347 * @param fd File descriptor of the opened file.
348 * @return The number of written characters.
349 */
[8b5fb5e]350static int _dprintf_str_write(const char *str, size_t size, void *fd)
351{
352 ssize_t wr = write(*(int *) fd, str, size);
353 return str_nlength(str, wr);
354}
355
[1978a5f]356/**
357 * Write wide string to the opened file.
358 *
359 * @param str String to be written.
360 * @param size Size of the string (in bytes).
361 * @param fd File descriptor of the opened file.
362 * @return The number of written characters.
363 */
[8b5fb5e]364static int _dprintf_wstr_write(const wchar_t *str, size_t size, void *fd)
365{
366 size_t offset = 0;
367 size_t chars = 0;
368 size_t sz;
369 char buf[4];
370
371 while (offset < size) {
372 sz = 0;
373 if (chr_encode(str[chars], buf, &sz, sizeof(buf)) != EOK) {
374 break;
375 }
376
377 if (write(*(int *) fd, buf, sz) != (ssize_t) sz) {
378 break;
379 }
380
381 chars++;
382 offset += sizeof(wchar_t);
383 }
384
385 return chars;
386}
387
[1978a5f]388/**
389 * Print formatted output to the opened file.
390 *
391 * @param fildes File descriptor of the opened file.
392 * @param format Format description.
393 * @param ap Print arguments.
394 * @return Either the number of printed characters or negative value on error.
395 */
[8b5fb5e]396int posix_vdprintf(int fildes, const char *restrict format, va_list ap)
397{
398 printf_spec_t spec = {
399 .str_write = _dprintf_str_write,
400 .wstr_write = _dprintf_wstr_write,
401 .data = &fildes
402 };
403
404 return printf_core(format, &spec, ap);
[b08ef1fd]405}
406
[59f799b]407/**
[1978a5f]408 * Print formatted output to the string.
[59f799b]409 *
[1978a5f]410 * @param s Output string.
411 * @param format Format description.
412 * @return Either the number of printed characters (excluding null byte) or
413 * negative value on error.
[59f799b]414 */
[08053f7]415int posix_sprintf(char *s, const char *restrict format, ...)
[59f799b]416{
[8b5fb5e]417 va_list list;
418 va_start(list, format);
419 int result = posix_vsprintf(s, format, list);
420 va_end(list);
421 return result;
[59f799b]422}
423
[823a929]424/**
[1978a5f]425 * Print formatted output to the string.
[823a929]426 *
[1978a5f]427 * @param s Output string.
428 * @param format Format description.
429 * @param ap Print arguments.
430 * @return Either the number of printed characters (excluding null byte) or
431 * negative value on error.
[823a929]432 */
[08053f7]433int posix_vsprintf(char *s, const char *restrict format, va_list ap)
[823a929]434{
[8b5fb5e]435 return vsnprintf(s, STR_NO_LIMIT, format, ap);
436}
437
438/**
[1978a5f]439 * Convert formatted input from the stream.
[8b5fb5e]440 *
[1978a5f]441 * @param stream Input stream.
442 * @param format Format description.
443 * @return The number of converted output items or EOF on failure.
[8b5fb5e]444 */
445int posix_fscanf(FILE *restrict stream, const char *restrict format, ...)
446{
447 va_list list;
448 va_start(list, format);
449 int result = posix_vfscanf(stream, format, list);
450 va_end(list);
451 return result;
452}
453
454/**
[1978a5f]455 * Convert formatted input from the standard input.
[8b5fb5e]456 *
[1978a5f]457 * @param format Format description.
458 * @return The number of converted output items or EOF on failure.
[8b5fb5e]459 */
460int posix_scanf(const char *restrict format, ...)
461{
462 va_list list;
463 va_start(list, format);
464 int result = posix_vscanf(format, list);
465 va_end(list);
466 return result;
467}
468
469/**
[1978a5f]470 * Convert formatted input from the standard input.
[8b5fb5e]471 *
[1978a5f]472 * @param format Format description.
473 * @param arg Output items.
474 * @return The number of converted output items or EOF on failure.
[8b5fb5e]475 */
476int posix_vscanf(const char *restrict format, va_list arg)
477{
478 return posix_vfscanf(stdin, format, arg);
479}
480
[59f799b]481/**
[1978a5f]482 * Convert formatted input from the string.
[59f799b]483 *
[1978a5f]484 * @param s Input string.
485 * @param format Format description.
486 * @return The number of converted output items or EOF on failure.
[59f799b]487 */
[08053f7]488int posix_sscanf(const char *restrict s, const char *restrict format, ...)
[8b5fb5e]489{
490 va_list list;
491 va_start(list, format);
492 int result = posix_vsscanf(s, format, list);
493 va_end(list);
494 return result;
495}
496
[1978a5f]497/**
498 * Acquire file stream for the thread.
499 *
500 * @param file File stream to lock.
501 */
[8b5fb5e]502void posix_flockfile(FILE *file)
503{
504 /* dummy */
505}
506
[1978a5f]507/**
508 * Acquire file stream for the thread (non-blocking).
509 *
510 * @param file File stream to lock.
511 * @return Zero for success and non-zero if the lock cannot be acquired.
512 */
[8b5fb5e]513int posix_ftrylockfile(FILE *file)
514{
515 /* dummy */
516 return 0;
517}
518
[1978a5f]519/**
520 * Relinquish the ownership of the locked file stream.
521 *
522 * @param file File stream to unlock.
523 */
[8b5fb5e]524void posix_funlockfile(FILE *file)
525{
526 /* dummy */
527}
528
[1978a5f]529/**
530 * Get a byte from a stream (thread-unsafe).
531 *
532 * @param stream Input file stream.
533 * @return Either read byte or EOF.
534 */
[8b5fb5e]535int posix_getc_unlocked(FILE *stream)
536{
537 return getc(stream);
538}
539
[1978a5f]540/**
541 * Get a byte from the standard input stream (thread-unsafe).
542 *
543 * @return Either read byte or EOF.
544 */
[8b5fb5e]545int posix_getchar_unlocked(void)
546{
547 return getchar();
548}
549
[1978a5f]550/**
551 * Put a byte on a stream (thread-unsafe).
552 *
553 * @param c Byte to output.
554 * @param stream Output file stream.
555 * @return Either written byte or EOF.
556 */
[8b5fb5e]557int posix_putc_unlocked(int c, FILE *stream)
558{
559 return putc(c, stream);
560}
561
[1978a5f]562/**
563 * Put a byte on the standard output stream (thread-unsafe).
564 *
565 * @param c Byte to output.
566 * @return Either written byte or EOF.
567 */
[8b5fb5e]568int posix_putchar_unlocked(int c)
569{
570 return putchar(c);
571}
572
[823a929]573/**
[58115ae]574 * Remove a file or directory.
[823a929]575 *
[1978a5f]576 * @param path Pathname of the file that shall be removed.
[58115ae]577 * @return Zero on success, -1 (with errno set) otherwise.
[823a929]578 */
579int posix_remove(const char *path)
580{
[58115ae]581 struct stat st;
582 int rc = stat(path, &st);
583
584 if (rc != EOK) {
585 errno = -rc;
586 return -1;
587 }
588
589 if (st.is_directory) {
590 rc = rmdir(path);
591 } else {
592 rc = unlink(path);
593 }
594
595 if (rc != EOK) {
596 errno = -rc;
597 return -1;
598 }
599 return 0;
[823a929]600}
601
[75406dc]602/**
603 * Rename a file or directory.
604 *
[2a53f71]605 * @param old Old pathname.
606 * @param new New pathname.
[75406dc]607 * @return Zero on success, -1 (with errno set) otherwise.
608 */
609int posix_rename(const char *old, const char *new)
610{
611 return errnify(rename, old, new);
612}
613
[823a929]614/**
[11544f4]615 * Get a unique temporary file name (obsolete).
616 *
617 * @param s Buffer for the file name. Must be at least L_tmpnam bytes long.
618 * @return The value of s on success, NULL on failure.
[823a929]619 */
620char *posix_tmpnam(char *s)
621{
[11544f4]622 assert(L_tmpnam >= posix_strlen("/tmp/tnXXXXXX"));
623
624 static char buffer[L_tmpnam + 1];
625 if (s == NULL) {
626 s = buffer;
627 }
628
629 posix_strcpy(s, "/tmp/tnXXXXXX");
630 posix_mktemp(s);
631
632 if (*s == '\0') {
633 /* Errno set by mktemp(). */
634 return NULL;
635 }
636
637 return s;
638}
639
640/**
641 * Get an unique temporary file name with additional constraints (obsolete).
642 *
643 * @param dir Path to directory, where the file should be created.
644 * @param pfx Optional prefix up to 5 characters long.
645 * @return Newly allocated unique path for temporary file. NULL on failure.
646 */
647char *posix_tempnam(const char *dir, const char *pfx)
648{
649 /* Sequence number of the filename. */
650 static int seq = 0;
651
652 size_t dir_len = posix_strlen(dir);
653 if (dir[dir_len - 1] == '/') {
654 dir_len--;
655 }
656
657 size_t pfx_len = posix_strlen(pfx);
658 if (pfx_len > 5) {
659 pfx_len = 5;
660 }
661
662 char *result = malloc(dir_len + /* slash*/ 1 +
663 pfx_len + /* three-digit seq */ 3 + /* .tmp */ 4 + /* nul */ 1);
664
665 if (result == NULL) {
666 errno = ENOMEM;
667 return NULL;
668 }
669
670 char *res_ptr = result;
671 posix_strncpy(res_ptr, dir, dir_len);
672 res_ptr += dir_len;
673 posix_strncpy(res_ptr, pfx, pfx_len);
674 res_ptr += pfx_len;
675
676 for (; seq < 1000; ++seq) {
677 snprintf(res_ptr, 8, "%03d.tmp", seq);
678
679 int orig_errno = errno;
680 errno = 0;
681 /* Check if the file exists. */
682 if (posix_access(result, F_OK) == -1) {
683 if (errno == ENOENT) {
684 errno = orig_errno;
685 break;
686 } else {
687 /* errno set by access() */
688 return NULL;
689 }
690 }
691 }
692
693 if (seq == 1000) {
694 free(result);
695 errno = EINVAL;
696 return NULL;
697 }
698
699 return result;
700}
701
702/**
703 * Create and open an unique temporary file.
704 * The file is automatically removed when the stream is closed.
705 *
706 * @param dir Path to directory, where the file should be created.
707 * @param pfx Optional prefix up to 5 characters long.
708 * @return Newly allocated unique path for temporary file. NULL on failure.
709 */
710FILE *posix_tmpfile(void)
711{
712 char filename[] = "/tmp/tfXXXXXX";
713 int fd = posix_mkstemp(filename);
714 if (fd == -1) {
715 /* errno set by mkstemp(). */
716 return NULL;
717 }
718
719 /* Unlink the created file, so that it's removed on close(). */
720 posix_unlink(filename);
721 return fdopen(fd, "w+");
[823a929]722}
723
[09b0b1fb]724/** @}
725 */
Note: See TracBrowser for help on using the repository browser.