source: mainline/uspace/lib/posix/stdio.c@ 051e6ac

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 051e6ac was cfbb5d18, checked in by Petr Koupy <petr.koupy@…>, 14 years ago

Correction of fgetpos().

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