Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a line from stdin, blocking until the newline is found?

Tags:

c

io

I'm trying to read one line at a time, of arbitrary length, from stdin at the command line. I'm not sure if I'll be able to include GNU readline and would prefer to use a library function.

The documentation I've read suggests that getline ought to work, but in my experiments it doesn't block. My sample program:

#include <stdio.h> int main() {     char *line = NULL;     if (getline(&line, NULL, stdin) == -1) {         printf("No line\n");     } else {         printf("%s\n", line);     }     return 0; } 

produces No line, which makes it unsuitable for accepting user input.

How do I do this? I know it should be trivial, but I haven't been able to figure it out.

like image 497
Taymon Avatar asked Sep 03 '12 17:09

Taymon


2 Answers

Try this patch

char *line = NULL; +size_t size; +if (getline(&line, &size, stdin) == -1) { -if (getline(&line, 0, stdin) == -1) {     printf("No line\n"); } else { 
like image 80
CyberDem0n Avatar answered Oct 04 '22 21:10

CyberDem0n


I have been able to reproduce a "nonblocking" behaviour on getline:

#include <stdio.h> #include <stdlib.h>  int main() {         char    *buffer;         size_t  n = 1024;         buffer = malloc(n);         return getline(&buffer, &n, stdin); } 

getline(&buffer... blocks. If I assign NULL to buffer, again it blocks (as advertised), and stores the line in a newly allocated buffer.

But if I write

getline(NULL, &n, stdin); 

then getline fails, and seems not to block. Probably also an invalid n or file pointer could cause the same behaviour. Might this be the problem?

like image 43
LSerni Avatar answered Oct 04 '22 21:10

LSerni