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
Line 
1/*
2 * Copyright (c) 2011 Jiri Zarevucky
3 * Copyright (c) 2011 Petr Koupy
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 */
33/** @file Standard buffered input/output.
34 */
35
36#define LIBPOSIX_INTERNAL
37#define __POSIX_DEF__(x) posix_##x
38
39#include "internal/common.h"
40#include "posix/stdio.h"
41
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"
48
49#include "libc/stdio.h"
50#include "libc/io/printf_core.h"
51#include "libc/stdbool.h"
52#include "libc/str.h"
53#include "libc/malloc.h"
54#include "libc/adt/list.h"
55#include "libc/sys/stat.h"
56
57/** Clears the stream's error and end-of-file indicators.
58 *
59 * @param stream Stream whose indicators shall be cleared.
60 */
61void posix_clearerr(FILE *stream)
62{
63 clearerr(stream);
64}
65
66/**
67 * Generate a pathname for the controlling terminal.
68 *
69 * @param s Allocated buffer to which the pathname shall be put.
70 * @return Either s or static location filled with the requested pathname.
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
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{
96 return fputs(s, stream);
97}
98
99/**
100 * Push byte back into input stream.
101 *
102 * @param c Byte to be pushed back.
103 * @param stream Stream to where the byte shall be pushed.
104 * @return Provided byte on success or EOF if not possible.
105 */
106int posix_ungetc(int c, FILE *stream)
107{
108 return ungetc(c, stream);
109}
110
111/**
112 * Read a stream until the delimiter (or EOF) is encountered.
113 *
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).
123 */
124ssize_t posix_getdelim(char **restrict lineptr, size_t *restrict n,
125 int delimiter, FILE *restrict stream)
126{
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 }
182}
183
184/**
185 * Read a stream until the newline (or EOF) is encountered.
186 *
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).
195 */
196ssize_t posix_getline(char **restrict lineptr, size_t *restrict n,
197 FILE *restrict stream)
198{
199 return posix_getdelim(lineptr, n, '\n', stream);
200}
201
202/**
203 * Reopen a file stream.
204 *
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.
212 */
213FILE *posix_freopen(const char *restrict filename,
214 const char *restrict mode, FILE *restrict stream)
215{
216 return freopen(filename, mode, stream);
217}
218
219/**
220 * Write error messages to standard error.
221 *
222 * @param s Error message.
223 */
224void posix_perror(const char *s)
225{
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);
253 if (ret != -1) {
254 pos->offset = ret;
255 return 0;
256 } else {
257 return -1;
258 }
259}
260
261/**
262 * Reposition a file-position indicator in a stream.
263 *
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.
268 */
269int posix_fseek(FILE *stream, long offset, int whence)
270{
271 return fseek(stream, (off64_t) offset, whence);
272}
273
274/**
275 * Reposition a file-position indicator in a stream.
276 *
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.
281 */
282int posix_fseeko(FILE *stream, posix_off_t offset, int whence)
283{
284 return fseek(stream, (off64_t) offset, whence);
285}
286
287/**
288 * Discover current file offset in a stream.
289 *
290 * @param stream Stream for which the offset shall be retrieved.
291 * @return Current offset or -1 if not possible.
292 */
293long posix_ftell(FILE *stream)
294{
295 return (long) ftell(stream);
296}
297
298/**
299 * Discover current file offset in a stream.
300 *
301 * @param stream Stream for which the offset shall be retrieved.
302 * @return Current offset or -1 if not possible.
303 */
304posix_off_t posix_ftello(FILE *stream)
305{
306 return (posix_off_t) ftell(stream);
307}
308
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
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 */
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
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 */
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
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 */
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
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 */
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);
405}
406
407/**
408 * Print formatted output to the string.
409 *
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.
414 */
415int posix_sprintf(char *s, const char *restrict format, ...)
416{
417 va_list list;
418 va_start(list, format);
419 int result = posix_vsprintf(s, format, list);
420 va_end(list);
421 return result;
422}
423
424/**
425 * Print formatted output to the string.
426 *
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.
432 */
433int posix_vsprintf(char *s, const char *restrict format, va_list ap)
434{
435 return vsnprintf(s, STR_NO_LIMIT, format, ap);
436}
437
438/**
439 * Convert formatted input from the stream.
440 *
441 * @param stream Input stream.
442 * @param format Format description.
443 * @return The number of converted output items or EOF on failure.
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/**
455 * Convert formatted input from the standard input.
456 *
457 * @param format Format description.
458 * @return The number of converted output items or EOF on failure.
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/**
470 * Convert formatted input from the standard input.
471 *
472 * @param format Format description.
473 * @param arg Output items.
474 * @return The number of converted output items or EOF on failure.
475 */
476int posix_vscanf(const char *restrict format, va_list arg)
477{
478 return posix_vfscanf(stdin, format, arg);
479}
480
481/**
482 * Convert formatted input from the string.
483 *
484 * @param s Input string.
485 * @param format Format description.
486 * @return The number of converted output items or EOF on failure.
487 */
488int posix_sscanf(const char *restrict s, const char *restrict format, ...)
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
497/**
498 * Acquire file stream for the thread.
499 *
500 * @param file File stream to lock.
501 */
502void posix_flockfile(FILE *file)
503{
504 /* dummy */
505}
506
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 */
513int posix_ftrylockfile(FILE *file)
514{
515 /* dummy */
516 return 0;
517}
518
519/**
520 * Relinquish the ownership of the locked file stream.
521 *
522 * @param file File stream to unlock.
523 */
524void posix_funlockfile(FILE *file)
525{
526 /* dummy */
527}
528
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 */
535int posix_getc_unlocked(FILE *stream)
536{
537 return getc(stream);
538}
539
540/**
541 * Get a byte from the standard input stream (thread-unsafe).
542 *
543 * @return Either read byte or EOF.
544 */
545int posix_getchar_unlocked(void)
546{
547 return getchar();
548}
549
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 */
557int posix_putc_unlocked(int c, FILE *stream)
558{
559 return putc(c, stream);
560}
561
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 */
568int posix_putchar_unlocked(int c)
569{
570 return putchar(c);
571}
572
573/**
574 * Remove a file or directory.
575 *
576 * @param path Pathname of the file that shall be removed.
577 * @return Zero on success, -1 (with errno set) otherwise.
578 */
579int posix_remove(const char *path)
580{
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;
600}
601
602/**
603 * Rename a file or directory.
604 *
605 * @param old Old pathname.
606 * @param new New pathname.
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
614/**
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.
619 */
620char *posix_tmpnam(char *s)
621{
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+");
722}
723
724/** @}
725 */
Note: See TracBrowser for help on using the repository browser.