I wonder how to implement a program in C that can automatically complete the command or text that you are entering in command line.For example, say your program is prompting user for a file name. Mostly one would use scanf() or else to do this. And then in the command line user would be prompt likeplease input the file name:_.
Let's say there is a shakespeare.txt in the same directory. And now I have entered shakes, and then I want the computer to auto-complete the shakespeare.txt for me, as it does for most programs when user hitting Tab. How to implement that?
Edit:to make it more clear, another example:
if you use grep in your command line, like grep -i "shakespeare" shakespeare.txt, before you complete shakespeare.txt yourself, if you simply use Tab, there would be some candidates show up.
How can I implement my program to make it possess this utilities when I try to prompt the user for input when using function like scanf()?
If you consider using an existing utility,
take a look at the GNU readline library which provides a pretty neat implementation of what you're looking for.
There some other helpful features like moving the cursor in your input, providing an input history and an input shell-like prompt.
This library's functionality works identical on different platforms.
As this example from Wikipedia shows, the key to indicate the completion can be set easily:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <readline/readline.h>
#include <readline/history.h>
int main()
{
char* input, shell_prompt[100];
// Configure readline to auto-complete paths when the tab key is hit.
rl_bind_key('\t', rl_complete);
for(;;) {
// Create prompt string from user name and current working directory.
snprintf(shell_prompt, sizeof(shell_prompt), "%s:%s $ ", getenv("USER"), getcwd(NULL, 1024));
// Display prompt and read input (NB: input must be freed after use)...
input = readline(shell_prompt);
// Check for EOF.
if (!input)
break;
// Add input to history.
add_history(input);
// Do stuff...
// Free input.
free(input);
}
return 0;
}
Because in C there is no portable solution for knowing what you have typed in a promt without pressing enter you need to read character by character.
Note: you may want to use getche() in order to echo the character back.
You will need to define a buffer where you will store character by character everything the user press, until the user hit enter or it press enter. When you find \t you will analyze the content from buffer and take a decision based on that.
The following code is a oversimplified example:
char c;
int i = 0;
do {
c = _getche();
if (c == '\t') {
// Autocomplete
// Print the rest of the word here
}
else {
buff[i++] = c;
}
} while (c != '\n' && c!='\r');
buff[i] = '\0'; // Let's keep the standard
It's not clear whether your asking for completion performed by
Your grep example suggests your asking about shell completion. Here is one example.