1 /* 2 * Copyright 2006, Haiku, Inc. All Rights Reserved. 3 * Distributed under the terms of the MIT License. 4 * 5 * Authors: 6 * Axel Dörfler, axeld@pinc-software.de 7 */ 8 9 10 #include <stdio.h> 11 #include <stdlib.h> 12 13 14 #define LINE_LENGTH 4096 15 16 17 char * 18 fgetln(FILE *stream, size_t *_length) 19 { 20 // TODO: this function is not thread-safe 21 static size_t sBufferSize; 22 static char *sBuffer; 23 24 size_t length, left; 25 char *line; 26 27 if (sBuffer == NULL) { 28 sBuffer = (char *)malloc(LINE_LENGTH); 29 if (sBuffer == NULL) 30 return NULL; 31 32 sBufferSize = LINE_LENGTH; 33 } 34 35 line = sBuffer; 36 left = sBufferSize; 37 38 for (;;) { 39 line = fgets(line, left, stream); 40 if (line == NULL) { 41 free(sBuffer); 42 sBuffer = NULL; 43 return NULL; 44 } 45 46 length = strlen(line); 47 if (line[length - 1] != '\n' && length == sBufferSize - 1) { 48 // more data is following, enlarge buffer 49 char *newBuffer = realloc(sBuffer, sBufferSize + LINE_LENGTH); 50 if (newBuffer == NULL) { 51 free(sBuffer); 52 sBuffer = NULL; 53 return NULL; 54 } 55 56 sBuffer = newBuffer; 57 sBufferSize += LINE_LENGTH; 58 line = sBuffer + length; 59 left += 1; 60 } else 61 break; 62 } 63 64 return sBuffer; 65 } 66 67