使用C Readline从文件而不是stdin中读取一行 [英] Using C Readline to read a line from file instead of stdin

查看:71
本文介绍了使用C Readline从文件而不是stdin中读取一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用gcc -lreadline的readline从stdin读取.后来,我想从文件中读取内容,因此尝试了以下操作,但是它仍然暂停并接受了命令提示符下的输入,而不是从文件中接受它.此方法是否有解决方法?

 FILE * savedStdin = stdin;stdin = fopen("someFile.txt","r");char *输入= readline(NULL);标准输入=已保存标准输入;

解决方案

readline库实际上非常灵活,几乎可以肯定会遭受折磨以实现您想要的功能.但是,当您声明尝试使用readline读取文件的原因(在其他地方使用readline从控制台读取的程序中)时,您似乎并不想这样做.自己管理输入缓冲区.只需使用readline读取控制台输入(如命令提示符),当您需要从文件中读取内容时,可以使用通常不使用readline的方式进行读取,例如使用 fgets()./p>

如果您真的不喜欢所有这些,则有一个名为 rl_instream 的全局变量,您可以对其进行修改以使readline从stdin以外的流中读取.其类型为 FILE * ,并在此处进行记录: https://tiswww.case.edu/php/chet/readline/readline.html

I'm using the readline from gcc -lreadline for reading from stdin. Later, I want to read from a file, so I tried the following, but it still paused for and accepted input from command prompt instead of accepting it from the file. Is there a fix for this approach?


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

这篇关于使用C Readline从文件而不是stdin中读取一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆