cis_config: /root/cis_interface/cis_interface/cis_interface/getline_win32.h Source File

cis_config

getline_win32.h
1 #ifndef GETLINE_WIN32_H_
2 #define GETLINE_WIN32_H_
3
4
5 #if defined(_WIN64)
6 #define SSIZE_MAX _I64_MAX
7 #else
8 #define SSIZE_MAX LONG_MAX
9 #endif
10
11
21 static inline
22 int getline(char** lineptr, size_t* n, FILE* stream) {
23
24 int nread = 0;
25
26 while (1) {
27 char* prev = *lineptr + nread;
28 if (fgets(prev, (int)(*n) - nread, stream) != prev)
29 return -1;
30 nread = (int)strlen(*lineptr);
31
32 // Break if new line reached or buffer not filled
33 if ((nread < (*n - 1)) || ((*lineptr)[nread - 1] == '\n'))
34 return nread;
35
36 // Stop if max size exceeded
37 if (*n == SSIZE_MAX)
38 return -1;
39
40 // Get size
41 size_t new_n;
42 if ((*n >> (sizeof(size_t) * 8 - 1)) == 1)
43 new_n = SSIZE_MAX;
44 else
45 new_n = 2 * (*n);
46
47 // Realloc
48 char* new_lineptr = (char*)realloc(*lineptr, new_n);
49 if (new_lineptr == NULL)
50 return -1;
51
52 // Assign
53 *n = new_n;
54 *lineptr = new_lineptr;
55
56 }
57
58 return nread;
59 };
60
61
62 #endif /*GETLINE_WIN32_H_*/