使用C Readline从文件中读取一行,而不是stdin



我使用gcc -lreadline中的readline从stdin中读取。后来,我想从文件中读取,所以我尝试了以下操作,但它仍然暂停并接受来自命令提示符的输入,而不是从文件中接受输入。这种方法有什么解决办法吗?


FILE* savedStdin = stdin;
stdin = fopen("someFile.txt", "r");
char* input = readline(NULL);
stdin = savedStdin;

The readline library is actually pretty flexible and can almost certainly be tortured to do what you want. But it doesn't seem to make any sense to bother with that, when your stated reason for trying to use readline to read from a file (in a program which elsewhere uses readline to read from the console) is that you don't want to manage your input buffers yourself. Just use readline to read console input (like a command prompt), and when you need to read from a file, do it the way you normally would without readline, such as by using fgets().

If you really don't like all that, there's a global variable called rl_instream which you can modify to make readline read from a stream other than stdin. Its type is FILE* and it is documented here: https://tiswww.case.edu/php/chet/readline/readline.html

maybe just try to use stdin, and run it using:

cat file.txt > program

相关内容

  • 没有找到相关文章

最新更新