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

孤街浪徒 提交于 2021-02-05 20:15:31

问题


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.


回答1:


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 {



回答2:


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?



来源:https://stackoverflow.com/questions/12252103/how-to-read-a-line-from-stdin-blocking-until-the-newline-is-found

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!