Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
dfda65059b8c52f2ceb3b0145e32b430920fd378
[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 ssize_t getline(char **buf, size_t *n, FILE *stream) {
26    
27    int i, ch;
28    
29    if (!*buf) {
30      *buf = xbt_malloc(512);
31      *n = 512;
32    }
33    
34    if (feof(stream))
35      return (ssize_t)-1;
36    
37    for (i=0; (ch = fgetc(stream)) != EOF; i++)  {
38         
39       if (i >= (*n) + 1)
40         *buf = xbt_realloc(*buf, *n += 512);
41         
42       (*buf)[i] = ch;
43         
44       if ((*buf)[i] == '\n')  {
45          i++;
46          (*buf)[i] = '\0';
47          break;
48       }      
49    }
50       
51    if (i == *n) 
52      *buf = xbt_realloc(*buf, *n += 1);
53    
54    (*buf)[i] = '\0';
55
56    return (ssize_t)i;
57 }
58
59