Search code examples
cprintfstdin

pre-fill stdin in C


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: Result

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


Solution

  • 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()).