1 /* xbt_os_file.c -- portable interface to file-related functions */
3 /* Copyright (c) 2007-2010, 2012-2015. The SimGrid Team.
4 * All rights reserved. */
6 /* This program is free software; you can redistribute it and/or modify it
7 * under the terms of the license (GNU LGPL) which comes with this package. */
9 #include "xbt/sysdep.h"
10 #include "xbt/file.h" /* this module */
12 #include "src/portable.h"
15 #include "libgen.h" /* POSIX dirname */
18 /** @brief Get a single line from the stream (reimplementation of the GNU getline)
20 * This is a reimplementation of the GNU getline function, so that our code don't depends on the GNU libc.
22 * xbt_getline() reads an entire line from stream, storing the address of the
23 * buffer containing the text into *buf. The buffer is null-terminated and
24 * includes the newline character, if one was found.
26 * If *buf is NULL, then xbt_getline() will allocate a buffer for storing the
27 * line, which should be freed by the user program.
29 * Alternatively, before calling xbt_getline(), *buf can contain a pointer to a
30 * malloc()-allocated buffer *n bytes in size. If the buffer is not large
31 * enough to hold the line, xbt_getline() resizes it with realloc(), updating
32 * *buf and *n as necessary.
34 * In either case, on a successful call, *buf and *n will be updated to reflect
35 * the buffer address and allocated size respectively.
37 ssize_t xbt_getline(char **buf, size_t *n, FILE *stream)
43 if (ferror(stream) || feof(stream))
48 *buf = xbt_malloc(*n);
54 *buf = xbt_realloc(*buf, *n += 512);
56 } while (ch != '\n' && (ch = getc(stream)) != EOF);
59 *buf = xbt_realloc(*buf, *n += 1);
65 /** @brief Returns the directory component of a path (reimplementation of POSIX dirname)
67 * The argument is never modified, and the returned value must be freed after use.
69 char *xbt_dirname(const char *path) {
71 char drive[_MAX_DRIVE];
74 err = _splitpath_s(path, drive, _MAX_DRIVE, dir, _MAX_DIR, NULL,0, NULL,0);
75 return bprintf("%s%s",drive,dir);
77 return dirname(xbt_strdup(path));
80 /** @brief Returns the file component of a path (reimplementation of POSIX basename)
82 * The argument is never modified, and the returned value must be freed after use.
84 char *xbt_basename(const char *path) {
89 err = _splitpath_s(path, NULL,0, NULL,0, file,1024, ext,1024);
90 return bprintf("%s.%s",file,ext);
92 return basename(xbt_strdup(path));