Skip to content

Instantly share code, notes, and snippets.

@BolvarsDad
Created June 10, 2025 20:52
Show Gist options
  • Save BolvarsDad/0ba2658d102d05ce815ce2e64d94a471 to your computer and use it in GitHub Desktop.
Save BolvarsDad/0ba2658d102d05ce815ce2e64d94a471 to your computer and use it in GitHub Desktop.
Single-line input in C
#include <stdio.h>
size_t
get_line(char *buffer, size_t bufsz)
{
static char ch;
size_t nread;
size_t buflen = 0;
while (buflen < bufsz) {
if ((nread = fread(&ch, sizeof ch, 1, stdin)) == 0 || ch == '\n')
break;
buffer[buflen++] = ch;
}
return buflen;
}
int
main(int argc, char **argv)
{
char buf[10];
size_t nread;
nread = get_line(buf, 10);
printf("Result: {'%.*s', %lu}\n", (int)nread, buf, nread);
printf("Expected: {'Hello Worl', 10}\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment