开发者

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

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


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

cat file.txt > program
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜