Skip Navigation
InitialsDiceBearhttps://github.com/dicebear/dicebearhttps://creativecommons.org/publicdomain/zero/1.0/„Initials” (https://github.com/dicebear/dicebear) by „DiceBear”, licensed under „CC0 1.0” (https://creativecommons.org/publicdomain/zero/1.0/)KA
Posts
1
Comments
0
Joined
4 yr. ago
The C Programming Language @lemmy.ml
kawaiiamber @lemmy.ml

Readline from stdin

If one has POSIX extensions available, then it seems that defining _POSIX_C_SOURCE and just using getline or detdelim is the way to go. However, for source that is just C, here is a solution I've found from various sources, mainly here. I've also tried to make it more safe.

 undefined
    
// Read line from stdin

#include <stdio.h>
#include <stdlib.h>

#define CHUNK_SIZE 16 // Allocate memory in chunks of this size

// Safe self-realloc
void *xrealloc(void *ptr, size_t size)
{
    void *tmp = realloc(ptr, size);
    if (!tmp) free(ptr);
    return tmp;
}

// Dynamically allocate memory for char pointer from stdin
char *readline(void)
{
    size_t len = 0, chunk = CHUNK_SIZE;
    char *str = (char *)malloc(CHUNK_SIZE);
    if (!str) return NULL;
    int ch;
    while((ch = getchar()) != EOF && ch != '\n' && ch != '\r') {
        str[len++] = ch;
        if (len == chunk) {
            str = (char *)xre