简体   繁体   English

如何从stdin读取一行,阻塞直到找到换行符?

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

I'm trying to read one line at a time, of arbitrary length, from stdin at the command line. 我试图从命令行的stdin一次读取任意长度的一行。 I'm not sure if I'll be able to include GNU readline and would prefer to use a library function. 我不确定我是否能够包含GNU readline并且更喜欢使用库函数。

The documentation I've read suggests that getline ought to work, but in my experiments it doesn't block. 我读过的文档表明getline应该可行,但在我的实验中它并没有阻止。 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. 生成No line ,这使得它不适合接受用户输入。

How do I do this? 我该怎么做呢? I know it should be trivial, but I haven't been able to figure it out. 我知道这应该是微不足道的,但我无法弄明白。

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 {

I have been able to reproduce a "nonblocking" behaviour on getline : 我已经能够在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. getline(&buffer... blocks。如果我将NULL分配给buffer ,它再次阻塞(如公布的那样),并将该行存储在新分配的缓冲区中。

But if I write 但如果我写

getline(NULL, &n, stdin);

then getline fails, and seems not to block. 然后getline失败了, 似乎没有阻止。 Probably also an invalid n or file pointer could cause the same behaviour. 也可能是无效的n或文件指针可能导致相同的行为。 Might this be the problem? 这可能是问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM