Logo AND Algorithmique Numérique Distribuée

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