Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Only declare getline portability cruft if it is needed (it's not used so far), it...
[simgrid.git] / src / xbt / getline.c
1 /* $Id$ */
2
3 /* getline -- reimplementation of the GNU's getline() for other platforms   */
4
5 /* Copyright (C) 2007 Martin Quinson. All rights reserved.                  */
6
7 /* This program is free software; you can redistribute it and/or modify it
8  * under the terms of the license (GNU LGPL) which comes with this package. */
9
10 /** @brief  Reads an entire line.
11  * 
12  * Reads a line from the file specified by the file pointer passed
13  * as parameter. This function is intead to replace the non-portable
14  * GNU getline() function.
15  * 
16  * @param buf address to a string buffer. If null, it will be allocated to receive the read data. If not and if too short, it will be reallocated. Must be freed by caller.
17  * @param n size of the buffer. Updated accordingly by the function.
18  * @param stream File pointer to the file to read from.
19  * @return The amount of chars read (or -1 on failure, ie on end of file condition)
20  */
21 #include "xbt/misc.h"
22 #include "xbt/sysdep.h" /* headers of this function */
23 #include "portable.h"
24
25 #ifndef HAVE_GETLINE
26 ssize_t getline(char **buf, size_t *n, FILE *stream) {
27    
28    int i, ch;
29    
30    if (!*buf) {
31      *buf = xbt_malloc(512);
32      *n = 512;
33    }
34    
35    if (feof(stream))
36      return (ssize_t)-1;
37    
38    for (i=0; (ch = fgetc(stream)) != EOF; i++)  {
39         
40       if (i >= (*n) + 1)
41         *buf = xbt_realloc(*buf, *n += 512);
42         
43       (*buf)[i] = ch;
44         
45       if ((*buf)[i] == '\n')  {
46          i++;
47          (*buf)[i] = '\0';
48          break;
49       }      
50    }
51       
52    if (i == *n) 
53      *buf = xbt_realloc(*buf, *n += 1);
54    
55    (*buf)[i] = '\0';
56
57    return (ssize_t)i;
58 }
59
60 #endif /* HAVE_GETLINE */