pre-fill stdin in C

2019-06-25 09:00发布

问题:

My program is supposed to let the user edit a line of a file. The user edits the line and sends it back by pressing enter. Therefore I would like to print the current line which is about to be edited, but kind of print it on stdin instead of stdout. The only problem I don't know how to solve is how I can prefill the stdin. I've already tried this:

char cprefill[] = {"You may edit this line"};
char cbuffer[100];
fprintf(stdin, cprefill);
fgets(cbuffer, 100, stdin);

This seems to be the simplest solution, but is probably too simple to work. The fprintf doesn't print anything to stdin. What is the correct way?

Edit:

This is how it is supposed to look like. Please mind the cursor which can be moved.

回答1:

First you need the libreadline developer package. (You might also need the libreadline if it's not already available on your system)

On Debian / Ubuntu that's apt install libreadline-dev (plus libreadline6 if you need the binaries also - 6 might be different on your platform)

Then you can add an history to readline, like this

#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>    

...

char cprefill[] = {"You may edit this line"};

add_history(cprefill);

char *buf = readline("Line: ");

printf("Edited line is %s\n", buf);

// free the line allocated by readline
free(buf);

User is prompted "Line: ", and has to do UP ARROW to get and edit the history, i.e. the cprefill line.

Note that you have to compile/link with -lreadline

readline prints the prompt given as argument, then waits for user interaction, allowing line edition, and arrows to load lines stored in the history.

The char * returned by readline has then to be freed (since that function allocates a buffer with malloc()).



回答2:

The C language has no notion of terminal nor of line edition, so it cannot be done in a portable way. You can either rely on a library like [n]curses to get an almost portable solution, or if you only need that on one single OS use low level OS primitives.

For exemple on Windows, you could feed the input buffer by simulating key strokes into the appropriate window (for example by sending WM_CHAR messages) just before reading, but that would be highly non portable - and in the end is no longer a C but a Windows solution...



标签: c printf stdin