source: mainline/uspace/lib/posix/src/stdio.c@ 777832e

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

fgetpos, fsetpos, perror.

  • Property mode set to 100644
File size: 11.7 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#include "internal/common.h"
37#include "posix/stdio.h"
38
39#include <assert.h>
40
41#include <errno.h>
42
43#include "posix/stdlib.h"
44#include "posix/string.h"
45#include "posix/sys/types.h"
46#include "posix/unistd.h"
47
48#include "libc/stdio.h"
49#include "libc/io/printf_core.h"
50#include "libc/str.h"
51#include "libc/malloc.h"
52#include "libc/adt/list.h"
53
54/**
55 * Generate a pathname for the controlling terminal.
56 *
57 * @param s Allocated buffer to which the pathname shall be put.
58 * @return Either s or static location filled with the requested pathname.
59 */
60char *ctermid(char *s)
61{
62 /* Currently always returns an error value (empty string). */
63 // TODO: return a real terminal path
64
65 static char dummy_path[L_ctermid] = { '\0' };
66
67 if (s == NULL) {
68 return dummy_path;
69 }
70
71 s[0] = '\0';
72 return s;
73}
74
75/**
76 * Read a stream until the delimiter (or EOF) is encountered.
77 *
78 * @param lineptr Pointer to the output buffer in which there will be stored
79 * nul-terminated string together with the delimiter (if encountered).
80 * Will be resized if necessary.
81 * @param n Pointer to the size of the output buffer. Will be increased if
82 * necessary.
83 * @param delimiter Delimiter on which to finish reading the stream.
84 * @param stream Input stream.
85 * @return Number of fetched characters (including delimiter if encountered)
86 * or -1 on error (set in errno).
87 */
88ssize_t getdelim(char **restrict lineptr, size_t *restrict n,
89 int delimiter, FILE *restrict stream)
90{
91 /* Check arguments for sanity. */
92 if (!lineptr || !n) {
93 errno = EINVAL;
94 return -1;
95 }
96
97 size_t alloc_step = 80; /* Buffer size gain during reallocation. */
98 char *pos = *lineptr; /* Next free byte of the output buffer. */
99 size_t cnt = 0; /* Number of fetched characters. */
100 int c = fgetc(stream); /* Current input character. Might be EOF. */
101
102 do {
103 /* Mask EOF as NUL to terminate string. */
104 if (c == EOF) {
105 c = '\0';
106 }
107
108 /* Ensure there is still space left in the buffer. */
109 if (pos == *lineptr + *n) {
110 *lineptr = realloc(*lineptr, *n + alloc_step);
111 if (*lineptr) {
112 pos = *lineptr + *n;
113 *n += alloc_step;
114 } else {
115 errno = ENOMEM;
116 return -1;
117 }
118 }
119
120 /* Store the fetched character. */
121 *pos = c;
122
123 /* Fetch the next character according to the current character. */
124 if (c != '\0') {
125 ++pos;
126 ++cnt;
127 if (c == delimiter) {
128 /*
129 * Delimiter was just stored. Provide EOF as the next
130 * character - it will be masked as NUL and output string
131 * will be properly terminated.
132 */
133 c = EOF;
134 } else {
135 /*
136 * Neither delimiter nor EOF were encountered. Just fetch
137 * the next character from the stream.
138 */
139 c = fgetc(stream);
140 }
141 }
142 } while (c != '\0');
143
144 if (errno == EOK && cnt > 0) {
145 return cnt;
146 } else {
147 /* Either some error occured or the stream was already at EOF. */
148 return -1;
149 }
150}
151
152/**
153 * Read a stream until the newline (or EOF) is encountered.
154 *
155 * @param lineptr Pointer to the output buffer in which there will be stored
156 * nul-terminated string together with the delimiter (if encountered).
157 * Will be resized if necessary.
158 * @param n Pointer to the size of the output buffer. Will be increased if
159 * necessary.
160 * @param stream Input stream.
161 * @return Number of fetched characters (including newline if encountered)
162 * or -1 on error (set in errno).
163 */
164ssize_t getline(char **restrict lineptr, size_t *restrict n,
165 FILE *restrict stream)
166{
167 return getdelim(lineptr, n, '\n', stream);
168}
169
170/**
171 * Reposition a file-position indicator in a stream.
172 *
173 * @param stream Stream to seek in.
174 * @param offset Direction and amount of bytes to seek.
175 * @param whence From where to seek.
176 * @return Zero on success, -1 otherwise.
177 */
178int fseeko(FILE *stream, off_t offset, int whence)
179{
180 return fseek64(stream, offset, whence);
181}
182
183/**
184 * Discover current file offset in a stream.
185 *
186 * @param stream Stream for which the offset shall be retrieved.
187 * @return Current offset or -1 if not possible.
188 */
189off_t ftello(FILE *stream)
190{
191 return ftell64(stream);
192}
193
194/**
195 * Print formatted output to the opened file.
196 *
197 * @param fildes File descriptor of the opened file.
198 * @param format Format description.
199 * @return Either the number of printed characters or negative value on error.
200 */
201int dprintf(int fildes, const char *restrict format, ...)
202{
203 va_list list;
204 va_start(list, format);
205 int result = vdprintf(fildes, format, list);
206 va_end(list);
207 return result;
208}
209
210/**
211 * Write ordinary string to the opened file.
212 *
213 * @param str String to be written.
214 * @param size Size of the string (in bytes)..
215 * @param fd File descriptor of the opened file.
216 * @return The number of written characters.
217 */
218static int _dprintf_str_write(const char *str, size_t size, void *fd)
219{
220 const int fildes = *(int *) fd;
221 size_t wr;
222 if (failed(vfs_write(fildes, &posix_pos[fildes], str, size, &wr)))
223 return -1;
224 return str_nlength(str, wr);
225}
226
227/**
228 * Write wide string to the opened file.
229 *
230 * @param str String to be written.
231 * @param size Size of the string (in bytes).
232 * @param fd File descriptor of the opened file.
233 * @return The number of written characters.
234 */
235static int _dprintf_wstr_write(const wchar_t *str, size_t size, void *fd)
236{
237 size_t offset = 0;
238 size_t chars = 0;
239 size_t sz;
240 char buf[4];
241
242 while (offset < size) {
243 sz = 0;
244 if (chr_encode(str[chars], buf, &sz, sizeof(buf)) != EOK) {
245 break;
246 }
247
248 const int fildes = *(int *) fd;
249 size_t nwr;
250 if (vfs_write(fildes, &posix_pos[fildes], buf, sz, &nwr) != EOK)
251 break;
252
253 chars++;
254 offset += sizeof(wchar_t);
255 }
256
257 return chars;
258}
259
260/**
261 * Print formatted output to the opened file.
262 *
263 * @param fildes File descriptor of the opened file.
264 * @param format Format description.
265 * @param ap Print arguments.
266 * @return Either the number of printed characters or negative value on error.
267 */
268int vdprintf(int fildes, const char *restrict format, va_list ap)
269{
270 printf_spec_t spec = {
271 .str_write = _dprintf_str_write,
272 .wstr_write = _dprintf_wstr_write,
273 .data = &fildes
274 };
275
276 return printf_core(format, &spec, ap);
277}
278
279/**
280 * Print formatted output to the string.
281 *
282 * @param s Output string.
283 * @param format Format description.
284 * @return Either the number of printed characters (excluding null byte) or
285 * negative value on error.
286 */
287int sprintf(char *s, const char *restrict format, ...)
288{
289 va_list list;
290 va_start(list, format);
291 int result = vsprintf(s, format, list);
292 va_end(list);
293 return result;
294}
295
296/**
297 * Print formatted output to the string.
298 *
299 * @param s Output string.
300 * @param format Format description.
301 * @param ap Print arguments.
302 * @return Either the number of printed characters (excluding null byte) or
303 * negative value on error.
304 */
305int vsprintf(char *s, const char *restrict format, va_list ap)
306{
307 return vsnprintf(s, INT_MAX, format, ap);
308}
309
310/**
311 * Acquire file stream for the thread.
312 *
313 * @param file File stream to lock.
314 */
315void flockfile(FILE *file)
316{
317 /* dummy */
318}
319
320/**
321 * Acquire file stream for the thread (non-blocking).
322 *
323 * @param file File stream to lock.
324 * @return Zero for success and non-zero if the lock cannot be acquired.
325 */
326int ftrylockfile(FILE *file)
327{
328 /* dummy */
329 return 0;
330}
331
332/**
333 * Relinquish the ownership of the locked file stream.
334 *
335 * @param file File stream to unlock.
336 */
337void funlockfile(FILE *file)
338{
339 /* dummy */
340}
341
342/**
343 * Get a byte from a stream (thread-unsafe).
344 *
345 * @param stream Input file stream.
346 * @return Either read byte or EOF.
347 */
348int getc_unlocked(FILE *stream)
349{
350 return getc(stream);
351}
352
353/**
354 * Get a byte from the standard input stream (thread-unsafe).
355 *
356 * @return Either read byte or EOF.
357 */
358int getchar_unlocked(void)
359{
360 return getchar();
361}
362
363/**
364 * Put a byte on a stream (thread-unsafe).
365 *
366 * @param c Byte to output.
367 * @param stream Output file stream.
368 * @return Either written byte or EOF.
369 */
370int putc_unlocked(int c, FILE *stream)
371{
372 return putc(c, stream);
373}
374
375/**
376 * Put a byte on the standard output stream (thread-unsafe).
377 *
378 * @param c Byte to output.
379 * @return Either written byte or EOF.
380 */
381int putchar_unlocked(int c)
382{
383 return putchar(c);
384}
385
386/**
387 * Get a unique temporary file name (obsolete).
388 *
389 * @param s Buffer for the file name. Must be at least L_tmpnam bytes long.
390 * @return The value of s on success, NULL on failure.
391 */
392char *tmpnam(char *s)
393{
394 assert(L_tmpnam >= strlen("/tmp/tnXXXXXX"));
395
396 static char buffer[L_tmpnam + 1];
397 if (s == NULL) {
398 s = buffer;
399 }
400
401 strcpy(s, "/tmp/tnXXXXXX");
402 mktemp(s);
403
404 if (*s == '\0') {
405 /* Errno set by mktemp(). */
406 return NULL;
407 }
408
409 return s;
410}
411
412/**
413 * Get an unique temporary file name with additional constraints (obsolete).
414 *
415 * @param dir Path to directory, where the file should be created.
416 * @param pfx Optional prefix up to 5 characters long.
417 * @return Newly allocated unique path for temporary file. NULL on failure.
418 */
419char *tempnam(const char *dir, const char *pfx)
420{
421 /* Sequence number of the filename. */
422 static int seq = 0;
423
424 size_t dir_len = strlen(dir);
425 if (dir[dir_len - 1] == '/') {
426 dir_len--;
427 }
428
429 size_t pfx_len = strlen(pfx);
430 if (pfx_len > 5) {
431 pfx_len = 5;
432 }
433
434 char *result = malloc(dir_len + /* slash*/ 1 +
435 pfx_len + /* three-digit seq */ 3 + /* .tmp */ 4 + /* nul */ 1);
436
437 if (result == NULL) {
438 errno = ENOMEM;
439 return NULL;
440 }
441
442 char *res_ptr = result;
443 strncpy(res_ptr, dir, dir_len);
444 res_ptr += dir_len;
445 strncpy(res_ptr, pfx, pfx_len);
446 res_ptr += pfx_len;
447
448 for (; seq < 1000; ++seq) {
449 snprintf(res_ptr, 8, "%03d.tmp", seq);
450
451 int orig_errno = errno;
452 errno = EOK;
453 /* Check if the file exists. */
454 if (access(result, F_OK) == -1) {
455 if (errno == ENOENT) {
456 errno = orig_errno;
457 break;
458 } else {
459 /* errno set by access() */
460 return NULL;
461 }
462 }
463 }
464
465 if (seq == 1000) {
466 free(result);
467 errno = EINVAL;
468 return NULL;
469 }
470
471 return result;
472}
473
474/**
475 * Create and open an unique temporary file.
476 * The file is automatically removed when the stream is closed.
477 *
478 * @param dir Path to directory, where the file should be created.
479 * @param pfx Optional prefix up to 5 characters long.
480 * @return Newly allocated unique path for temporary file. NULL on failure.
481 */
482FILE *tmpfile(void)
483{
484 char filename[] = "/tmp/tfXXXXXX";
485 int fd = mkstemp(filename);
486 if (fd == -1) {
487 /* errno set by mkstemp(). */
488 return NULL;
489 }
490
491 /* Unlink the created file, so that it's removed on close(). */
492 unlink(filename);
493 return fdopen(fd, "w+");
494}
495
496/** @}
497 */
Note: See TracBrowser for help on using the repository browser.