2022-03-29 23:47:22 +02:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <stddef.h>
|
|
|
|
#include <errno.h>
|
|
|
|
#include "fileutil.h"
|
|
|
|
|
2022-03-31 11:12:01 +02:00
|
|
|
ssize_t getdelim(char **restrict lineptr, size_t *restrict n, int delim,
|
|
|
|
FILE *restrict fp)
|
2022-03-29 23:47:22 +02:00
|
|
|
{
|
|
|
|
ssize_t cur = 0;
|
|
|
|
char *new_lineptr = NULL;
|
|
|
|
size_t new_n;
|
|
|
|
|
2022-03-31 11:12:01 +02:00
|
|
|
if(lineptr == NULL || n == NULL || fp == NULL) {
|
|
|
|
errno = EINVAL;
|
2022-03-29 23:47:22 +02:00
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
2022-03-31 11:12:01 +02:00
|
|
|
if(*lineptr == NULL) {
|
2022-03-29 23:47:22 +02:00
|
|
|
*n = 80;
|
|
|
|
*lineptr = (char *) malloc(*n);
|
|
|
|
if(*lineptr==NULL) return -1;
|
|
|
|
}
|
|
|
|
|
2022-03-31 11:12:01 +02:00
|
|
|
do {
|
|
|
|
ssize_t read_size = __fp_fread2(fp, *lineptr+cur, *n - cur - 1, delim);
|
2022-03-29 23:47:22 +02:00
|
|
|
if(read_size <= 0) return -1;
|
|
|
|
cur += read_size;
|
2022-03-31 11:12:01 +02:00
|
|
|
|
|
|
|
if((*lineptr)[cur - 1] != delim && !feof(fp)) {
|
2022-03-29 23:47:22 +02:00
|
|
|
new_n = *n * 2;
|
|
|
|
new_lineptr = (char *) realloc(*lineptr, new_n);
|
|
|
|
if(new_lineptr == NULL) return -1;
|
|
|
|
*lineptr = new_lineptr;
|
|
|
|
*n = new_n;
|
|
|
|
}
|
2022-03-31 11:12:01 +02:00
|
|
|
}
|
|
|
|
while((*lineptr)[cur-1] != delim && !feof(fp));
|
2022-03-29 23:47:22 +02:00
|
|
|
|
|
|
|
(*lineptr)[cur] = '\0';
|
|
|
|
|
|
|
|
if(feof(fp) && (*lineptr)[cur-1] != delim)
|
|
|
|
return -1;
|
2022-03-31 11:12:01 +02:00
|
|
|
return cur;
|
2022-03-29 23:47:22 +02:00
|
|
|
}
|