Using C Readline to read a line from file instead of stdin

谁说我不能喝 提交于 2019-12-11 07:08:52

问题


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;

回答1:


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




回答2:


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

cat file.txt > program


来源:https://stackoverflow.com/questions/5767707/using-c-readline-to-read-a-line-from-file-instead-of-stdin

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