Skip to content

Instantly share code, notes, and snippets.

@drmalex07
Created March 12, 2021 23:31
Show Gist options
  • Save drmalex07/b63c1f77afc2532c6bd27d7ec1334f61 to your computer and use it in GitHub Desktop.
Save drmalex07/b63c1f77afc2532c6bd27d7ec1334f61 to your computer and use it in GitHub Desktop.
Real lines in C without overflowing buffer. #C #fgets #read-line
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int MAX_LINE_SIZE = 10;
int main(int argc, char **argv){
char line[MAX_LINE_SIZE + 2];
const char* PROMPT = ">> ";
do {
fputs(PROMPT, stdout);
if (fgets(line, sizeof(line), stdin) == NULL) {
fputs("\n", stdout);
break;
}
size_t len = strlen(line);
if (line[len - 1] != '\n') {
// input exceeds max size: consume remaining line
while (getchar() != '\n')
;
line[MAX_LINE_SIZE] = '\0';
len = MAX_LINE_SIZE;
} else {
// input is within limits: erase trailing newline
line[--len] = '\0';
}
printf("Line=<%s> Len=%lu=%lu\n", line, len, strlen(line));
} while (1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment