Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
remove a couple of MSC_VER stuff
[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
25  * buffer containing the text into *buf.  The buffer is null-terminated and
26  * includes the newline character, if one was found.
27  *
28  * If *buf is NULL, then xbt_getline() will allocate a buffer for storing the
29  * line, which should be freed by the user program.
30  *
31  * Alternatively, before calling xbt_getline(), *buf can contain a pointer to a
32  * malloc()-allocated buffer *n bytes in size.  If the buffer is not large
33  * enough to hold the line, xbt_getline() resizes it with realloc(), updating
34  * *buf and *n as necessary.
35  *
36  * In either case, on a successful call, *buf and *n will be updated to reflect
37  * the buffer address and allocated size respectively.
38  */
39 ssize_t xbt_getline(char **buf, size_t *n, FILE *stream)
40 {
41   ssize_t i;
42   int ch;
43
44   ch = getc(stream);
45   if (ferror(stream) || feof(stream))
46     return -1;
47
48   if (!*buf) {
49     *n = 512;
50     *buf = xbt_malloc(*n);
51   }
52
53   i = 0;
54   do {
55     if (i == *n)
56       *buf = xbt_realloc(*buf, *n += 512);
57     (*buf)[i++] = ch;
58   } while (ch != '\n' && (ch = getc(stream)) != EOF);
59
60   if (i == *n)
61     *buf = xbt_realloc(*buf, *n += 1);
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 }