Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
cosmetics
[simgrid.git] / src / xbt / xbt_os_file.c
1 /* xbt_os_file.c -- portable interface to file-related functions            */
2
3 /* Copyright (c) 2007-2010, 2012-2015. The SimGrid Team.
4  * All rights reserved.                                                     */
5
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. */
8
9 #include "xbt/sysdep.h"
10 #include "xbt/file.h"    /* this module */
11 #include "xbt/log.h"
12 #include "src/internal_config.h"
13
14 #ifdef _WIN32
15 #include <windows.h>
16 #endif
17
18 #include "libgen.h" /* POSIX dirname */
19
20 /** @brief Get a single line from the stream (reimplementation of the GNU getline)
21  *
22  * This is a reimplementation of the GNU getline function, so that our code don't depends on the GNU libc.
23  *
24  * xbt_getline() reads an entire line from stream, storing the address of the buffer containing the text into *buf.
25  * The buffer is null-terminated and includes the newline character, if one was found.
26  *
27  * If *buf is NULL, then xbt_getline() will allocate a buffer for storing the  line, which should be freed by the user
28  * program.
29  *
30  * Alternatively, before calling xbt_getline(), *buf can contain a pointer to a malloc()-allocated buffer *n bytes in
31  * size. If the buffer is not large enough to hold the line, xbt_getline() resizes it with realloc(), updating
32  * *buf and *n as necessary.
33  *
34  * In either case, on a successful call, *buf and *n will be updated to reflect the buffer address and allocated size
35  * respectively.
36  */
37 ssize_t xbt_getline(char **buf, size_t *n, FILE *stream)
38 {
39   int ch = getc(stream);
40   if (ferror(stream) || feof(stream))
41     return -1;
42
43   if (!*buf) {
44     *n = 512;
45     *buf = xbt_malloc(*n);
46   }
47
48   ssize_t i = 0;
49   do {
50     if (i == *n) {
51       *n += 512;
52       *buf = xbt_realloc(*buf, *n);
53     }
54     (*buf)[i] = ch;
55     i++;
56   } while (ch != '\n' && (ch = getc(stream)) != EOF);
57
58   if (i == *n) {
59     *n += 1;
60     *buf = xbt_realloc(*buf, *n);
61   }
62   (*buf)[i] = '\0';
63
64   return i;
65 }
66
67 /** @brief Returns the directory component of a path (reimplementation of POSIX dirname)
68  *
69  * The argument is never modified, and the returned value must be freed after use.
70  */
71 char *xbt_dirname(const char *path) {
72   char *tmp = xbt_strdup(path);
73   char *res = xbt_strdup(dirname(tmp));
74   free(tmp);
75   return res;
76 }
77
78 /** @brief Returns the file component of a path (reimplementation of POSIX basename)
79  *
80  * The argument is never modified, and the returned value must be freed after use.
81  */
82 char *xbt_basename(const char *path) {
83   char *tmp = xbt_strdup(path);
84   char *res = xbt_strdup(basename(tmp));
85   free(tmp);
86   return res;
87 }