Last active
January 9, 2024 22:03
-
-
Save harryhanYuhao/8d1d4bd1b3fc0870d2c37e529cb0476f to your computer and use it in GitHub Desktop.
getline
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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