Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Document the new mkfile buildin command
[simgrid.git] / tools / tesh2 / src / readline.c
1 #include <readline.h>
2
3 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(tesh);
4
5 long
6 readline(FILE* stream, char **buf, size_t *n)
7 {
8         size_t i;
9         int ch;
10         int cr = 0;
11         fpos_t pos;
12
13         if (!*buf) {
14         *buf = calloc(512, sizeof(char));
15         *n = 512;
16         }
17
18         if (feof(stream))
19         return (ssize_t)-1;
20
21         for (i=0; (ch = fgetc(stream)) != EOF; i++)  
22         {
23                 if (i >= (*n) + 1)
24                         *buf = xbt_realloc(*buf, *n += 512);
25                         
26
27                         (*buf)[i] = ch;
28                         
29                         if(cr && (*buf)[i] != '\n')
30                         {
31                                 /* old Mac os uses CR */
32                                 i--;
33                                 (*buf)[i] = '\n';
34                                 
35                                 /* move to the previous pos (pos of the CR) */
36                                 fsetpos(stream, &pos);
37                                 
38                                 /* process as linux now */
39                                 cr --;
40                         }
41                         
42                         if((*buf)[i] == '\n')  
43                         {
44                                 if(cr)
45                                 {
46                                         /* Windows uses CRLF */
47                                         (*buf)[i - 1] = '\n';
48                                         (*buf)[i] = '\0';
49                                         break;
50                                 }
51                                 else
52                                 {
53                                         /* Unix use LF */
54                                         i++;
55                                         (*buf)[i] = '\0';
56                                         break;
57                                 }
58                         }  
59                         else if(ch == '\r')
60                         {
61                                 cr ++;
62                                 
63                                 /* register the CR position for mac */
64                                 fgetpos(stream, &pos);
65                         }
66         }
67         
68         
69         if (i == *n) 
70                 *buf = xbt_realloc(*buf, *n += 1);
71
72         /* Mac os file ended with a blank line */
73         if(ch == EOF && (*buf)[i - 1] == '\r')
74                 (*buf)[i - 1] = '\n';
75
76         (*buf)[i] = '\0';
77
78         return (ssize_t)i;
79 }
80