source: mainline/uspace/lib/posix/source/stdio.c@ 7db5cfd

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

fputs() and the incredible adventures of its return value.

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