source: mainline/uspace/lib/posix/source/stdio.c@ 6afc9d7

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

UNIX-like I/O functions should use errno to return error code for many reasons.

  • Property mode set to 100644
File size: 16.8 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 return negerrno(fflush, stream);
318}
319
320/**
321 * Print formatted output to the opened file.
322 *
323 * @param fildes File descriptor of the opened file.
324 * @param format Format description.
325 * @return Either the number of printed characters or negative value on error.
326 */
327int posix_dprintf(int fildes, const char *restrict format, ...)
328{
329 va_list list;
330 va_start(list, format);
331 int result = posix_vdprintf(fildes, format, list);
332 va_end(list);
333 return result;
334}
335
336/**
337 * Write ordinary string to the opened file.
338 *
339 * @param str String to be written.
340 * @param size Size of the string (in bytes)..
341 * @param fd File descriptor of the opened file.
342 * @return The number of written characters.
343 */
344static int _dprintf_str_write(const char *str, size_t size, void *fd)
345{
346 ssize_t wr = write(*(int *) fd, str, size);
347 if (wr < 0)
348 return errno;
349 return str_nlength(str, wr);
350}
351
352/**
353 * Write wide string to the opened file.
354 *
355 * @param str String to be written.
356 * @param size Size of the string (in bytes).
357 * @param fd File descriptor of the opened file.
358 * @return The number of written characters.
359 */
360static int _dprintf_wstr_write(const wchar_t *str, size_t size, void *fd)
361{
362 size_t offset = 0;
363 size_t chars = 0;
364 size_t sz;
365 char buf[4];
366
367 while (offset < size) {
368 sz = 0;
369 if (chr_encode(str[chars], buf, &sz, sizeof(buf)) != EOK) {
370 break;
371 }
372
373 if (write(*(int *) fd, buf, sz) != (ssize_t) sz) {
374 break;
375 }
376
377 chars++;
378 offset += sizeof(wchar_t);
379 }
380
381 return chars;
382}
383
384/**
385 * Print formatted output to the opened file.
386 *
387 * @param fildes File descriptor of the opened file.
388 * @param format Format description.
389 * @param ap Print arguments.
390 * @return Either the number of printed characters or negative value on error.
391 */
392int posix_vdprintf(int fildes, const char *restrict format, va_list ap)
393{
394 printf_spec_t spec = {
395 .str_write = _dprintf_str_write,
396 .wstr_write = _dprintf_wstr_write,
397 .data = &fildes
398 };
399
400 return printf_core(format, &spec, ap);
401}
402
403/**
404 * Print formatted output to the string.
405 *
406 * @param s Output string.
407 * @param format Format description.
408 * @return Either the number of printed characters (excluding null byte) or
409 * negative value on error.
410 */
411int posix_sprintf(char *s, const char *restrict format, ...)
412{
413 va_list list;
414 va_start(list, format);
415 int result = posix_vsprintf(s, format, list);
416 va_end(list);
417 return result;
418}
419
420/**
421 * Print formatted output to the string.
422 *
423 * @param s Output string.
424 * @param format Format description.
425 * @param ap Print arguments.
426 * @return Either the number of printed characters (excluding null byte) or
427 * negative value on error.
428 */
429int posix_vsprintf(char *s, const char *restrict format, va_list ap)
430{
431 return vsnprintf(s, STR_NO_LIMIT, format, ap);
432}
433
434/**
435 * Convert formatted input from the stream.
436 *
437 * @param stream Input stream.
438 * @param format Format description.
439 * @return The number of converted output items or EOF on failure.
440 */
441int posix_fscanf(FILE *restrict stream, const char *restrict format, ...)
442{
443 va_list list;
444 va_start(list, format);
445 int result = posix_vfscanf(stream, format, list);
446 va_end(list);
447 return result;
448}
449
450/**
451 * Convert formatted input from the standard input.
452 *
453 * @param format Format description.
454 * @return The number of converted output items or EOF on failure.
455 */
456int posix_scanf(const char *restrict format, ...)
457{
458 va_list list;
459 va_start(list, format);
460 int result = posix_vscanf(format, list);
461 va_end(list);
462 return result;
463}
464
465/**
466 * Convert formatted input from the standard input.
467 *
468 * @param format Format description.
469 * @param arg Output items.
470 * @return The number of converted output items or EOF on failure.
471 */
472int posix_vscanf(const char *restrict format, va_list arg)
473{
474 return posix_vfscanf(stdin, format, arg);
475}
476
477/**
478 * Convert formatted input from the string.
479 *
480 * @param s Input string.
481 * @param format Format description.
482 * @return The number of converted output items or EOF on failure.
483 */
484int posix_sscanf(const char *restrict s, const char *restrict format, ...)
485{
486 va_list list;
487 va_start(list, format);
488 int result = posix_vsscanf(s, format, list);
489 va_end(list);
490 return result;
491}
492
493/**
494 * Acquire file stream for the thread.
495 *
496 * @param file File stream to lock.
497 */
498void posix_flockfile(FILE *file)
499{
500 /* dummy */
501}
502
503/**
504 * Acquire file stream for the thread (non-blocking).
505 *
506 * @param file File stream to lock.
507 * @return Zero for success and non-zero if the lock cannot be acquired.
508 */
509int posix_ftrylockfile(FILE *file)
510{
511 /* dummy */
512 return 0;
513}
514
515/**
516 * Relinquish the ownership of the locked file stream.
517 *
518 * @param file File stream to unlock.
519 */
520void posix_funlockfile(FILE *file)
521{
522 /* dummy */
523}
524
525/**
526 * Get a byte from a stream (thread-unsafe).
527 *
528 * @param stream Input file stream.
529 * @return Either read byte or EOF.
530 */
531int posix_getc_unlocked(FILE *stream)
532{
533 return getc(stream);
534}
535
536/**
537 * Get a byte from the standard input stream (thread-unsafe).
538 *
539 * @return Either read byte or EOF.
540 */
541int posix_getchar_unlocked(void)
542{
543 return getchar();
544}
545
546/**
547 * Put a byte on a stream (thread-unsafe).
548 *
549 * @param c Byte to output.
550 * @param stream Output file stream.
551 * @return Either written byte or EOF.
552 */
553int posix_putc_unlocked(int c, FILE *stream)
554{
555 return putc(c, stream);
556}
557
558/**
559 * Put a byte on the standard output stream (thread-unsafe).
560 *
561 * @param c Byte to output.
562 * @return Either written byte or EOF.
563 */
564int posix_putchar_unlocked(int c)
565{
566 return putchar(c);
567}
568
569/**
570 * Remove a file or directory.
571 *
572 * @param path Pathname of the file that shall be removed.
573 * @return Zero on success, -1 (with errno set) otherwise.
574 */
575int posix_remove(const char *path)
576{
577 return negerrno(remove, path);
578}
579
580/**
581 * Rename a file or directory.
582 *
583 * @param old Old pathname.
584 * @param new New pathname.
585 * @return Zero on success, -1 (with errno set) otherwise.
586 */
587int posix_rename(const char *old, const char *new)
588{
589 return negerrno(rename, old, new);
590}
591
592/**
593 * Get a unique temporary file name (obsolete).
594 *
595 * @param s Buffer for the file name. Must be at least L_tmpnam bytes long.
596 * @return The value of s on success, NULL on failure.
597 */
598char *posix_tmpnam(char *s)
599{
600 assert(L_tmpnam >= posix_strlen("/tmp/tnXXXXXX"));
601
602 static char buffer[L_tmpnam + 1];
603 if (s == NULL) {
604 s = buffer;
605 }
606
607 posix_strcpy(s, "/tmp/tnXXXXXX");
608 posix_mktemp(s);
609
610 if (*s == '\0') {
611 /* Errno set by mktemp(). */
612 return NULL;
613 }
614
615 return s;
616}
617
618/**
619 * Get an unique temporary file name with additional constraints (obsolete).
620 *
621 * @param dir Path to directory, where the file should be created.
622 * @param pfx Optional prefix up to 5 characters long.
623 * @return Newly allocated unique path for temporary file. NULL on failure.
624 */
625char *posix_tempnam(const char *dir, const char *pfx)
626{
627 /* Sequence number of the filename. */
628 static int seq = 0;
629
630 size_t dir_len = posix_strlen(dir);
631 if (dir[dir_len - 1] == '/') {
632 dir_len--;
633 }
634
635 size_t pfx_len = posix_strlen(pfx);
636 if (pfx_len > 5) {
637 pfx_len = 5;
638 }
639
640 char *result = malloc(dir_len + /* slash*/ 1 +
641 pfx_len + /* three-digit seq */ 3 + /* .tmp */ 4 + /* nul */ 1);
642
643 if (result == NULL) {
644 errno = ENOMEM;
645 return NULL;
646 }
647
648 char *res_ptr = result;
649 posix_strncpy(res_ptr, dir, dir_len);
650 res_ptr += dir_len;
651 posix_strncpy(res_ptr, pfx, pfx_len);
652 res_ptr += pfx_len;
653
654 for (; seq < 1000; ++seq) {
655 snprintf(res_ptr, 8, "%03d.tmp", seq);
656
657 int orig_errno = errno;
658 errno = 0;
659 /* Check if the file exists. */
660 if (posix_access(result, F_OK) == -1) {
661 if (errno == ENOENT) {
662 errno = orig_errno;
663 break;
664 } else {
665 /* errno set by access() */
666 return NULL;
667 }
668 }
669 }
670
671 if (seq == 1000) {
672 free(result);
673 errno = EINVAL;
674 return NULL;
675 }
676
677 return result;
678}
679
680/**
681 * Create and open an unique temporary file.
682 * The file is automatically removed when the stream is closed.
683 *
684 * @param dir Path to directory, where the file should be created.
685 * @param pfx Optional prefix up to 5 characters long.
686 * @return Newly allocated unique path for temporary file. NULL on failure.
687 */
688FILE *posix_tmpfile(void)
689{
690 char filename[] = "/tmp/tfXXXXXX";
691 int fd = posix_mkstemp(filename);
692 if (fd == -1) {
693 /* errno set by mkstemp(). */
694 return NULL;
695 }
696
697 /* Unlink the created file, so that it's removed on close(). */
698 posix_unlink(filename);
699 return fdopen(fd, "w+");
700}
701
702/** @}
703 */
Note: See TracBrowser for help on using the repository browser.