Files
haiku-beta6/src/libs/bsd/fgetln.c
T
Axel Dörfler 275d9d80a9 Some more functions for our BSD compatibility library.
git-svn-id: file:///srv/svn/repos/haiku/haiku/trunk@18436 a95241bf-73f2-0310-859d-f6bbb57e9c96
2006-08-07 16:46:24 +00:00

67 lines
1.1 KiB
C

/*
* Copyright 2006, Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Axel Dörfler, [email protected]
*/
#include <stdio.h>
#include <stdlib.h>
#define LINE_LENGTH 4096
char *
fgetln(FILE *stream, size_t *_length)
{
// TODO: this function is not thread-safe
static size_t sBufferSize;
static char *sBuffer;
size_t length, left;
char *line;
if (sBuffer == NULL) {
sBuffer = (char *)malloc(LINE_LENGTH);
if (sBuffer == NULL)
return NULL;
sBufferSize = LINE_LENGTH;
}
line = sBuffer;
left = sBufferSize;
for (;;) {
line = fgets(line, left, stream);
if (line == NULL) {
free(sBuffer);
sBuffer = NULL;
return NULL;
}
length = strlen(line);
if (line[length - 1] != '\n' && length == sBufferSize - 1) {
// more data is following, enlarge buffer
char *newBuffer = realloc(sBuffer, sBufferSize + LINE_LENGTH);
if (newBuffer == NULL) {
free(sBuffer);
sBuffer = NULL;
return NULL;
}
sBuffer = newBuffer;
sBufferSize += LINE_LENGTH;
line = sBuffer + length;
left += 1;
} else
break;
}
return sBuffer;
}