Skip to content

Instantly share code, notes, and snippets.

@harryhanYuhao
Last active January 9, 2024 22:03
Show Gist options
  • Save harryhanYuhao/8d1d4bd1b3fc0870d2c37e529cb0476f to your computer and use it in GitHub Desktop.
Save harryhanYuhao/8d1d4bd1b3fc0870d2c37e529cb0476f to your computer and use it in GitHub Desktop.
getline
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
ssize_t getline(char **restrict lineptr, size_t *restrict n,
FILE *restrict stream) {
register char c;
register char *cs = NULL;
register int length = 0;
while ((c = getc(stream)) != EOF) {
cs = (char *)realloc(cs, ++length + 1);
if ((*(cs + length - 1) = c) == '\n') {
*(cs + length) = '\0';
break;
}
}
// return the allocated memory if lineptr is null
if ((*lineptr) == NULL) {
*lineptr = cs;
}
else {
// check if enough memory is allocated
if ((length + 1) < *n) {
*lineptr = (char *)realloc(*lineptr, length + 1);
}
memcpy(*lineptr, cs, length);
free(cs);
}
return (ssize_t)(*n = strlen(*lineptr));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment