source: mainline/uspace/lib/posix/source/stdio.c@ 8e3498b

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

vfs_read/write() should return error code separately from number of bytes transferred.

  • Property mode set to 100644
File size: 17.0 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/str.h"
52#include "libc/malloc.h"
53#include "libc/adt/list.h"
54
55/** Clears the stream's error and end-of-file indicators.
56 *
57 * @param stream Stream whose indicators shall be cleared.
58 */
59void posix_clearerr(FILE *stream)
60{
61 clearerr(stream);
62}
63
64/**
65 * Generate a pathname for the controlling terminal.
66 *
67 * @param s Allocated buffer to which the pathname shall be put.
68 * @return Either s or static location filled with the requested pathname.
69 */
70char *posix_ctermid(char *s)
71{
72 /* Currently always returns an error value (empty string). */
73 // TODO: return a real terminal path
74
75 static char dummy_path[L_ctermid] = {'\0'};
76
77 if (s == NULL) {
78 return dummy_path;
79 }
80
81 s[0] = '\0';
82 return s;
83}
84
85/**
86 * Put a string on the stream.
87 *
88 * @param s String to be written.
89 * @param stream Output stream.
90 * @return Non-negative on success, EOF on failure.
91 */
92int posix_fputs(const char *restrict s, FILE *restrict stream)
93{
94 return fputs(s, stream);
95}
96
97/**
98 * Push byte back into input stream.
99 *
100 * @param c Byte to be pushed back.
101 * @param stream Stream to where the byte shall be pushed.
102 * @return Provided byte on success or EOF if not possible.
103 */
104int posix_ungetc(int c, FILE *stream)
105{
106 return ungetc(c, stream);
107}
108
109/**
110 * Read a stream until the delimiter (or EOF) is encountered.
111 *
112 * @param lineptr Pointer to the output buffer in which there will be stored
113 * nul-terminated string together with the delimiter (if encountered).
114 * Will be resized if necessary.
115 * @param n Pointer to the size of the output buffer. Will be increased if
116 * necessary.
117 * @param delimiter Delimiter on which to finish reading the stream.
118 * @param stream Input stream.
119 * @return Number of fetched characters (including delimiter if encountered)
120 * or -1 on error (set in errno).
121 */
122ssize_t posix_getdelim(char **restrict lineptr, size_t *restrict n,
123 int delimiter, FILE *restrict stream)
124{
125 /* Check arguments for sanity. */
126 if (!lineptr || !n) {
127 errno = EINVAL;
128 return -1;
129 }
130
131 size_t alloc_step = 80; /* Buffer size gain during reallocation. */
132 char *pos = *lineptr; /* Next free byte of the output buffer. */
133 size_t cnt = 0; /* Number of fetched characters. */
134 int c = fgetc(stream); /* Current input character. Might be EOF. */
135
136 do {
137 /* Mask EOF as NUL to terminate string. */
138 if (c == EOF) {
139 c = '\0';
140 }
141
142 /* Ensure there is still space left in the buffer. */
143 if (pos == *lineptr + *n) {
144 *lineptr = realloc(*lineptr, *n + alloc_step);
145 if (*lineptr) {
146 pos = *lineptr + *n;
147 *n += alloc_step;
148 } else {
149 errno = ENOMEM;
150 return -1;
151 }
152 }
153
154 /* Store the fetched character. */
155 *pos = c;
156
157 /* Fetch the next character according to the current character. */
158 if (c != '\0') {
159 ++pos;
160 ++cnt;
161 if (c == delimiter) {
162 /* Delimiter was just stored. Provide EOF as the next
163 * character - it will be masked as NUL and output string
164 * will be properly terminated. */
165 c = EOF;
166 } else {
167 /* Neither delimiter nor EOF were encountered. Just fetch
168 * the next character from the stream. */
169 c = fgetc(stream);
170 }
171 }
172 } while (c != '\0');
173
174 if (errno == EOK && cnt > 0) {
175 return cnt;
176 } else {
177 /* Either some error occured or the stream was already at EOF. */
178 return -1;
179 }
180}
181
182/**
183 * Read a stream until the newline (or EOF) is encountered.
184 *
185 * @param lineptr Pointer to the output buffer in which there will be stored
186 * nul-terminated string together with the delimiter (if encountered).
187 * Will be resized if necessary.
188 * @param n Pointer to the size of the output buffer. Will be increased if
189 * necessary.
190 * @param stream Input stream.
191 * @return Number of fetched characters (including newline if encountered)
192 * or -1 on error (set in errno).
193 */
194ssize_t posix_getline(char **restrict lineptr, size_t *restrict n,
195 FILE *restrict stream)
196{
197 return posix_getdelim(lineptr, n, '\n', stream);
198}
199
200/**
201 * Reopen a file stream.
202 *
203 * @param filename Pathname of a file to be reopened or NULL for changing
204 * the mode of the stream.
205 * @param mode Mode to be used for reopening the file or changing current
206 * mode of the stream.
207 * @param stream Current stream associated with the opened file.
208 * @return On success, either a stream of the reopened file or the provided
209 * stream with a changed mode. NULL otherwise.
210 */
211FILE *posix_freopen(const char *restrict filename,
212 const char *restrict mode, FILE *restrict stream)
213{
214 return freopen(filename, mode, stream);
215}
216
217/**
218 * Write error messages to standard error.
219 *
220 * @param s Error message.
221 */
222void posix_perror(const char *s)
223{
224 if (s == NULL || s[0] == '\0') {
225 fprintf(stderr, "%s\n", posix_strerror(errno));
226 } else {
227 fprintf(stderr, "%s: %s\n", s, posix_strerror(errno));
228 }
229}
230
231/** Restores stream a to position previously saved with fgetpos().
232 *
233 * @param stream Stream to restore
234 * @param pos Position to restore
235 * @return Zero on success, non-zero (with errno set) on failure
236 */
237int posix_fsetpos(FILE *stream, const posix_fpos_t *pos)
238{
239 return fseek(stream, pos->offset, SEEK_SET);
240}
241
242/** Saves the stream's position for later use by fsetpos().
243 *
244 * @param stream Stream to save
245 * @param pos Place to store the position
246 * @return Zero on success, non-zero (with errno set) on failure
247 */
248int posix_fgetpos(FILE *restrict stream, posix_fpos_t *restrict pos)
249{
250 off64_t ret = ftell(stream);
251 if (ret != -1) {
252 pos->offset = ret;
253 return 0;
254 } else {
255 return -1;
256 }
257}
258
259/**
260 * Reposition a file-position indicator in a stream.
261 *
262 * @param stream Stream to seek in.
263 * @param offset Direction and amount of bytes to seek.
264 * @param whence From where to seek.
265 * @return Zero on success, -1 otherwise.
266 */
267int posix_fseek(FILE *stream, long offset, int whence)
268{
269 return fseek(stream, (off64_t) offset, whence);
270}
271
272/**
273 * Reposition a file-position indicator in a stream.
274 *
275 * @param stream Stream to seek in.
276 * @param offset Direction and amount of bytes to seek.
277 * @param whence From where to seek.
278 * @return Zero on success, -1 otherwise.
279 */
280int posix_fseeko(FILE *stream, posix_off_t offset, int whence)
281{
282 return fseek(stream, (off64_t) offset, whence);
283}
284
285/**
286 * Discover current file offset in a stream.
287 *
288 * @param stream Stream for which the offset shall be retrieved.
289 * @return Current offset or -1 if not possible.
290 */
291long posix_ftell(FILE *stream)
292{
293 return (long) ftell(stream);
294}
295
296/**
297 * Discover current file offset in a stream.
298 *
299 * @param stream Stream for which the offset shall be retrieved.
300 * @return Current offset or -1 if not possible.
301 */
302posix_off_t posix_ftello(FILE *stream)
303{
304 return (posix_off_t) ftell(stream);
305}
306
307/**
308 * Discard prefetched data or write unwritten data.
309 *
310 * @param stream Stream that shall be flushed.
311 * @return Zero on success, EOF on failure.
312 */
313int posix_fflush(FILE *stream)
314{
315 return negerrno(fflush, stream);
316}
317
318/**
319 * Print formatted output to the opened file.
320 *
321 * @param fildes File descriptor of the opened file.
322 * @param format Format description.
323 * @return Either the number of printed characters or negative value on error.
324 */
325int posix_dprintf(int fildes, const char *restrict format, ...)
326{
327 va_list list;
328 va_start(list, format);
329 int result = posix_vdprintf(fildes, format, list);
330 va_end(list);
331 return result;
332}
333
334/**
335 * Write ordinary string to the opened file.
336 *
337 * @param str String to be written.
338 * @param size Size of the string (in bytes)..
339 * @param fd File descriptor of the opened file.
340 * @return The number of written characters.
341 */
342static int _dprintf_str_write(const char *str, size_t size, void *fd)
343{
344 const int fildes = *(int *) fd;
345 size_t wr;
346 int rc = vfs_write(fildes, &posix_pos[fildes], str, size, &wr);
347 if (rc != EOK)
348 return rc;
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 const int fildes = *(int *) fd;
374 size_t nwr;
375 if (vfs_write(fildes, &posix_pos[fildes], buf, sz, &nwr) != EOK)
376 break;
377
378 chars++;
379 offset += sizeof(wchar_t);
380 }
381
382 return chars;
383}
384
385/**
386 * Print formatted output to the opened file.
387 *
388 * @param fildes File descriptor of the opened file.
389 * @param format Format description.
390 * @param ap Print arguments.
391 * @return Either the number of printed characters or negative value on error.
392 */
393int posix_vdprintf(int fildes, const char *restrict format, va_list ap)
394{
395 printf_spec_t spec = {
396 .str_write = _dprintf_str_write,
397 .wstr_write = _dprintf_wstr_write,
398 .data = &fildes
399 };
400
401 return printf_core(format, &spec, ap);
402}
403
404/**
405 * Print formatted output to the string.
406 *
407 * @param s Output string.
408 * @param format Format description.
409 * @return Either the number of printed characters (excluding null byte) or
410 * negative value on error.
411 */
412int posix_sprintf(char *s, const char *restrict format, ...)
413{
414 va_list list;
415 va_start(list, format);
416 int result = posix_vsprintf(s, format, list);
417 va_end(list);
418 return result;
419}
420
421/**
422 * Print formatted output to the string.
423 *
424 * @param s Output string.
425 * @param format Format description.
426 * @param ap Print arguments.
427 * @return Either the number of printed characters (excluding null byte) or
428 * negative value on error.
429 */
430int posix_vsprintf(char *s, const char *restrict format, va_list ap)
431{
432 return vsnprintf(s, STR_NO_LIMIT, format, ap);
433}
434
435/**
436 * Convert formatted input from the stream.
437 *
438 * @param stream Input stream.
439 * @param format Format description.
440 * @return The number of converted output items or EOF on failure.
441 */
442int posix_fscanf(FILE *restrict stream, const char *restrict format, ...)
443{
444 va_list list;
445 va_start(list, format);
446 int result = posix_vfscanf(stream, format, list);
447 va_end(list);
448 return result;
449}
450
451/**
452 * Convert formatted input from the standard input.
453 *
454 * @param format Format description.
455 * @return The number of converted output items or EOF on failure.
456 */
457int posix_scanf(const char *restrict format, ...)
458{
459 va_list list;
460 va_start(list, format);
461 int result = posix_vscanf(format, list);
462 va_end(list);
463 return result;
464}
465
466/**
467 * Convert formatted input from the standard input.
468 *
469 * @param format Format description.
470 * @param arg Output items.
471 * @return The number of converted output items or EOF on failure.
472 */
473int posix_vscanf(const char *restrict format, va_list arg)
474{
475 return posix_vfscanf(stdin, format, arg);
476}
477
478/**
479 * Convert formatted input from the string.
480 *
481 * @param s Input string.
482 * @param format Format description.
483 * @return The number of converted output items or EOF on failure.
484 */
485int posix_sscanf(const char *restrict s, const char *restrict format, ...)
486{
487 va_list list;
488 va_start(list, format);
489 int result = posix_vsscanf(s, format, list);
490 va_end(list);
491 return result;
492}
493
494/**
495 * Acquire file stream for the thread.
496 *
497 * @param file File stream to lock.
498 */
499void posix_flockfile(FILE *file)
500{
501 /* dummy */
502}
503
504/**
505 * Acquire file stream for the thread (non-blocking).
506 *
507 * @param file File stream to lock.
508 * @return Zero for success and non-zero if the lock cannot be acquired.
509 */
510int posix_ftrylockfile(FILE *file)
511{
512 /* dummy */
513 return 0;
514}
515
516/**
517 * Relinquish the ownership of the locked file stream.
518 *
519 * @param file File stream to unlock.
520 */
521void posix_funlockfile(FILE *file)
522{
523 /* dummy */
524}
525
526/**
527 * Get a byte from a stream (thread-unsafe).
528 *
529 * @param stream Input file stream.
530 * @return Either read byte or EOF.
531 */
532int posix_getc_unlocked(FILE *stream)
533{
534 return getc(stream);
535}
536
537/**
538 * Get a byte from the standard input stream (thread-unsafe).
539 *
540 * @return Either read byte or EOF.
541 */
542int posix_getchar_unlocked(void)
543{
544 return getchar();
545}
546
547/**
548 * Put a byte on a stream (thread-unsafe).
549 *
550 * @param c Byte to output.
551 * @param stream Output file stream.
552 * @return Either written byte or EOF.
553 */
554int posix_putc_unlocked(int c, FILE *stream)
555{
556 return putc(c, stream);
557}
558
559/**
560 * Put a byte on the standard output stream (thread-unsafe).
561 *
562 * @param c Byte to output.
563 * @return Either written byte or EOF.
564 */
565int posix_putchar_unlocked(int c)
566{
567 return putchar(c);
568}
569
570/**
571 * Remove a file or directory.
572 *
573 * @param path Pathname of the file that shall be removed.
574 * @return Zero on success, -1 (with errno set) otherwise.
575 */
576int posix_remove(const char *path)
577{
578 if (rcerrno(vfs_unlink_path, path) != EOK)
579 return -1;
580 else
581 return 0;
582}
583
584/**
585 * Rename a file or directory.
586 *
587 * @param old Old pathname.
588 * @param new New pathname.
589 * @return Zero on success, -1 (with errno set) otherwise.
590 */
591int posix_rename(const char *old, const char *new)
592{
593 int rc = rcerrno(vfs_rename_path, old, new);
594 if (rc != EOK)
595 return -1;
596 else
597 return 0;
598}
599
600/**
601 * Get a unique temporary file name (obsolete).
602 *
603 * @param s Buffer for the file name. Must be at least L_tmpnam bytes long.
604 * @return The value of s on success, NULL on failure.
605 */
606char *posix_tmpnam(char *s)
607{
608 assert(L_tmpnam >= posix_strlen("/tmp/tnXXXXXX"));
609
610 static char buffer[L_tmpnam + 1];
611 if (s == NULL) {
612 s = buffer;
613 }
614
615 posix_strcpy(s, "/tmp/tnXXXXXX");
616 posix_mktemp(s);
617
618 if (*s == '\0') {
619 /* Errno set by mktemp(). */
620 return NULL;
621 }
622
623 return s;
624}
625
626/**
627 * Get an unique temporary file name with additional constraints (obsolete).
628 *
629 * @param dir Path to directory, where the file should be created.
630 * @param pfx Optional prefix up to 5 characters long.
631 * @return Newly allocated unique path for temporary file. NULL on failure.
632 */
633char *posix_tempnam(const char *dir, const char *pfx)
634{
635 /* Sequence number of the filename. */
636 static int seq = 0;
637
638 size_t dir_len = posix_strlen(dir);
639 if (dir[dir_len - 1] == '/') {
640 dir_len--;
641 }
642
643 size_t pfx_len = posix_strlen(pfx);
644 if (pfx_len > 5) {
645 pfx_len = 5;
646 }
647
648 char *result = malloc(dir_len + /* slash*/ 1 +
649 pfx_len + /* three-digit seq */ 3 + /* .tmp */ 4 + /* nul */ 1);
650
651 if (result == NULL) {
652 errno = ENOMEM;
653 return NULL;
654 }
655
656 char *res_ptr = result;
657 posix_strncpy(res_ptr, dir, dir_len);
658 res_ptr += dir_len;
659 posix_strncpy(res_ptr, pfx, pfx_len);
660 res_ptr += pfx_len;
661
662 for (; seq < 1000; ++seq) {
663 snprintf(res_ptr, 8, "%03d.tmp", seq);
664
665 int orig_errno = errno;
666 errno = 0;
667 /* Check if the file exists. */
668 if (posix_access(result, F_OK) == -1) {
669 if (errno == ENOENT) {
670 errno = orig_errno;
671 break;
672 } else {
673 /* errno set by access() */
674 return NULL;
675 }
676 }
677 }
678
679 if (seq == 1000) {
680 free(result);
681 errno = EINVAL;
682 return NULL;
683 }
684
685 return result;
686}
687
688/**
689 * Create and open an unique temporary file.
690 * The file is automatically removed when the stream is closed.
691 *
692 * @param dir Path to directory, where the file should be created.
693 * @param pfx Optional prefix up to 5 characters long.
694 * @return Newly allocated unique path for temporary file. NULL on failure.
695 */
696FILE *posix_tmpfile(void)
697{
698 char filename[] = "/tmp/tfXXXXXX";
699 int fd = posix_mkstemp(filename);
700 if (fd == -1) {
701 /* errno set by mkstemp(). */
702 return NULL;
703 }
704
705 /* Unlink the created file, so that it's removed on close(). */
706 posix_unlink(filename);
707 return fdopen(fd, "w+");
708}
709
710/** @}
711 */
Note: See TracBrowser for help on using the repository browser.