Auto-completion visual not good (readline.h) - c

I would like to add the auto completion on the shell I created. I could not put the entire code but I can tell you my shell is working!
So I tried to implement auto-completion by using the readline function but the result is not that great (see the code in commentary I tried): the auto-completion works but the problems are:
1. I need to press twice enter to get the command executed now. 2. I need to type twice the command (like "ls") to get it executed! Can you help me to fix this? thank you :)
#include <readline/readline.h>
#include <readline/history.h>
#include <stdlib.h>
#include <stdio.h>
#include "includes/ft_sh1.h"
int main(int ac, char **av, char **envp)
{
char *line;
t_env *e = NULL;
char *add;
if (!(e = (t_env *)malloc(sizeof(t_env))))
return (0);
e->envp = env_cpy(envp, 0, 0);
init_env(e);
while (1)
{
--> My question is only about this part below <--
ft_printf("shell$> ");
// add = readline( "shell ");
// add_history(add);
// printf("%s", add);
--> My question is only about this part above <--
get_next_line(0, &line);
get_pwd_env(e);
e->cmd = get_cmd(e, line);
if (ft_strcmp(line, "exit") == 0)
exit(0);
else if (ft_strncmp(e->cmd[0], "cd", 2) == 0)
cd_cmd(e);
else
ft_execute(av, line, e);
}
}

When you just uncomment the part of code in question, you still have the call
get_next_line(0, &line);
in your program, so no wonder that you need to type two command lines.

Related

Suppress printing a new prompt when pressing tab with Readline

When using the auto completion with the Readline library in C, the prompt is reprinted when typing the tab key twice:
(prompt) view NAME_OF_F (user presses tab twice)
NAME_OF_FILE1 NAME_OF_FILE2 (suggestions by Readline)
(prompt) view NAME_OF_F
I'd like to suppress the reprinting of the prompt on the 3rd line by keeping the first line printed with the suggestions below it like such:
(prompt) view NAME_OF_F (user presses tab twice)
NAME_OF_FILE1 NAME_OF_FILE2 (suggestions by Readline)
I'd like the cursor back at the end of the first line that has the prompt.
Compiled with gcc -Wall -O0 -ggdb -fno-builtin rline.c -o rline -lreadline -ltermcap.
Here's a code sample:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <readline/readline.h>
int execute_line(char *line);
void initialize_readline();
static char **fileman_completion(char *text, int start, int end);
static char *command_generator(char *text, int state);
char *command[] = { "view", "quit", (char *)NULL };
int done; /* When non-zero, this global means the user is done using this program. */
int main(int argc, char **argv)
{
char *line;
initialize_readline(); /* Bind our completer. */
for ( ; done == 0; ) {
line = readline("> ");
if (!line)
break;
if (*line)
execute_line(line);
free(line);
}
return 0;
}
/* String to pass to system(). This is for the VIEW command. */
static char syscom[1024];
int execute_line(char *line)
{
int i = 0;
char *word;
/* Isolate the command word. */
while (line[i] && whitespace(line[i]))
i++;
word = line + i;
while (line[i] && !whitespace(line[i])) i++;
if (line[i]) line[i++] = '\0';
if (strcmp(word, "quit") == 0) {
done = 1;
return 0;
} else if (strcmp(word, "view")) {
fprintf(stderr, "%s: Choose only \"view FILE\" or \"quit\" as your command.\n", word);
return -1;
}
/* Get argument to command, if any. */
while (whitespace(line[i])) i++;
word = line + i;
if(!word || !*word) {
fprintf(stderr, "view: Argument required.\n");
return -1;
}
sprintf(syscom, "more %s", word);
return system(syscom);
}
void initialize_readline()
{
rl_readline_name = "rline";
rl_attempted_completion_function = (rl_completion_func_t *)fileman_completion;
}
static char **fileman_completion(char *text, int start, int end)
{
if (start == 0)
return rl_completion_matches(text, (rl_compentry_func_t *)*command_generator);
return NULL;
}
static char *command_generator(char *text, int state)
{
static int list_index, len;
char *name;
if (!state) {
list_index = 0;
len = strlen(text);
}
while ((name = command[list_index++]))
if (strncmp(name, text, len) == 0)
return strdup(name);
return NULL;
}
The program only accepts the commands view FILE_NAME to view the contents of a file and quit to exit the program.
The example is a shortened version of a sample program found here.
I don't think that readline has anything like that built in, but it does provide a lot of customisation possibilities if you want to try to write the logic yourself.
You could try writing a custom rl_completion_display_matches_hook to display the completion list. But it's not entirely clear to me how you would restore the cursor position afterwards. I don't think readline has a public interface for either finding or resetting the cursor position. (And, of course, it's possible that the completion list was so big that the original command scrolled off the screen.)
As an alternative, I was able use the hook to print the completion list over top of the current line and then redisplay the prompt after the completion list (although I cheated by assuming that the current input is always just one line). That's not quite what you asked for, but it may be useful for demonstration purposes. I used the following custom match printer:
static void display_matches(char** matches, int len, int max) {
putp(carriage_return);
putp(clr_eol);
putp(cursor_up);
rl_display_match_list(matches, len, max);
rl_forced_update_display();
}
I also added the following to the initialisation function:
rl_completion_display_matches_hook = display_matches;
setupterm(NULL, 1, (int*)0);
Thanks #rici for the inspiration. I got it working with his function with some modifications.
In order for this to work properly you need to download the readline library. In the rlprivate.h file from readline, I removed the lines char **lines;, and the line #include "realdine.h" from display.c. Then in your own .c you must have an #include </PATH/TO/display.c>. In that display.c, an #include points to the modified rlprivate.h. All of this so that I can have access to _rl_move_vert(1).
static void display_matches(char** matches, int len, int max)
{
int saved_point = rl_point;
char *saved_line = rl_copy_text(0, rl_end);
rl_save_prompt();
rl_replace_line("", 0); // Clear the previous text
putp(cursor_up);
_rl_move_vert(1);
rl_display_match_list(matches, len, max);
putp(cursor_up);
rl_restore_prompt();
rl_replace_line(saved_line, 0);
rl_point = saved_point;
rl_redisplay();
putp(cursor_down);
free(saved_line);
}

c does not follow the program operation procedure

summary : system("clear"); isn't working well.
I'm using gcc, ubuntu 18.04 LTS version for c programming.
what I intended was "read each words and print from two text files. After finish read file, delay 3 seconds and erase terminal"
so I was make two text files, and using system("clear"); to erase terminal.
here is whole code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void printFiles(char *file1,char *file2,char *change1, char *change2){
FILE *f;
char *text = malloc(sizeof(char)*100);
f=fopen(file1,"r");
system("clear");
//while(!feof(f)){
while(EOF!=fscanf(f,"%s",text)){
//fscanf(f,"%s", text);
printf("%s ",text);
//usleep(20000);
}
//sleep(3);
fclose(f);
printf("\n");
//all comment problems are appear here. and if I give delay, such as usleep() or sleep, delay also appear here. Not appear each wrote part.
f=fopen(file2,"r");
//while(!feof(f)){
while(EOF!=fscanf(f,"%s",text)){
if(strcmp(text,"**,")==0){
strcpy(text,change1);
strcat(text,",");
}
else if(strcmp(text,"**")==0){
strcpy(text,change1);
}
else if(strcmp(text,"##.")==0){
strcpy(text,change2);
strcat(text,".");
}
else if(strcmp(text,"##,")==0){
strcpy(text,change2);
strcat(text,",");
}
printf("%s ",text);
//usleep(200000);
}
fclose(f);
free(text);
sleep(3); //here is problem. This part works in the above commented part "//all comment problems are appear here."
system("clear"); //here is problem. This part works in the above commented part "//all comment problems are appear here."
}
int main(){
char file1[100] = "./file1.txt";
char file2[100] = "./file2.txt";
char change1[100]="text1";
char change2[100]="text2";
printFiles(file1,file2,change1,change2);
return 0;
}
I'm very sorry, files and variables names are changed because of policy. Also, file contents also can not upload.
I can't find which part makes break Procedure-oriented programming. I think that was compiler error, because using one file read and system(clear); works well.
I also make two point variables, such as 'FILE *f1; FILE *f2; f1=fopen(file1); f2=fopen(file2)...`, but same result occur.
Is it compiler error? If it is, what should I do for fix these problem? Thanks.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void printFiles(char *file1,char *file2,char *change1, char *change2){
FILE *f;
char *text = malloc(sizeof(char)*100);
f=fopen(file1,"r");
system("clear");
//while(!feof(f)){
while(EOF!=fscanf(f,"%s",text)){
//fscanf(f,"%s", text);
printf("%s ",text);
fflush(stdout);
//usleep(20000);
}
//sleep(3);
fclose(f);
printf("\n");
//all comment problems are appear here. and if I give delay, such as usleep() or sleep, delay also appear here. Not appear each wrote part.
f=fopen(file2,"r");
//while(!feof(f)){
while(EOF!=fscanf(f,"%s",text)){
if(strcmp(text,"**,")==0){
strcpy(text,change1);
strcat(text,",");
}
else if(strcmp(text,"**")==0){
strcpy(text,change1);
}
else if(strcmp(text,"##.")==0){
strcpy(text,change2);
strcat(text,".");
}
else if(strcmp(text,"##,")==0){
strcpy(text,change2);
strcat(text,",");
}
printf("%s ",text);
fflush(stdout);// The answer.
//usleep(200000);
}
fclose(f);
free(text);
sleep(3); //here is problem. This part works in the above commented part "//all comment problems are appear here."
system("clear"); //here is problem. This part works in the above commented part "//all comment problems are appear here."
}
int main(){
char file1[100] = "./file1.txt";
char file2[100] = "./file2.txt";
char change1[100]="text1";
char change2[100]="text2";
printFiles(file1,file2,change1,change2);
return 0;
}
Hint for
That's probably just buffering. Do fflush(stdout); before you sleep. – melpomene
Thanks.
You can try this solution for delay.
#include <time.h>
#include <stdio.h>
void delay(double seconds)
{
const time_t start = time(NULL);
time_t current;
do
{
time(&current);
} while(difftime(current, start) < seconds);
}
int main(void)
{
printf("Just waiting...\n");
delay(3);
printf("...oh man, waiting for so long...\n");
return 0;
}
Following solution is pretty quite the same of previous one but with a clear terminal solution.
#include <time.h>
#include <stdio.h>
#ifdef _WIN32
#define CLEAR_SCREEN system ("cls");
#else
#define CLEAR_SCREEN puts("\x1b[H\x1b[2J");
#endif
void delay(double seconds)
{
const time_t start = time(NULL);
time_t current;
do
{
time(&current);
} while(difftime(current, start) < seconds);
}
int main(void)
{
printf("Just waiting...\n");
delay(2); //seconds
printf("...oh man, waiting for so long...\n");
delay(1);
CLEAR_SCREEN
return 0;
}

creating multiple recursive directories in c

I am completing cs50x (the edX (free) version of the Harvard cs50) course and am trying to be a bit tricky/lazy/test myself.
I am trying to use a C program to create all the directories I will need for my psets.
I have looked online and found that <sys/stat.h> includes the mkdir() function and therefore tried creating some nested loops to create all the necessary folders by doing something similar to mkdir {pset1,pset1/{standard,hacker},pset2,pset2{standard... to give me a directory structure like this:
pset1/Standard
pset1/Hacker
pset2/Standard
etc...
I came up with this:
#include <cs50.h>
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, string argv[])
{
for(int i = 1; i <=8; i++)
{
string dir = argv[1];
sprintf(dir,"%s%i", argv[1], i);
mkdir(dir, 0777);
for(int j = 0; j<2; j++)
{
string subDir[] = {"Standard","Hacker"};
sprintf(dir,"%s%i/%s", argv[1], i, subDir[j]);
mkdir(dir, 0777);
}
}
}
However, the program only creates pset1 and completes, there are no subfolders, no pset2 etc.
Yes, you're being lazy since you seem to have very little knowledge of C, yet try to program in it. :)
C is not Python, there is no string interpolation/formatting operator. You have to call a function, specificially snprintf(). Read that manual page.
Also, you can't create a bunch of nested directories with a single call to mkdir(). Read the manual page.
To create nested directories, you're either going to have to build each's absolute path (i.e. each successive time you call mkdir() the path will be longer than the previous time), or actually enter each directory as you create it, and go from there.
To create a full path you can call mkdir() recursivly like this:
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
int mkdirr(const char * path, const mode_t mode, const int fail_on_exist)
{
int result = 0;
char * dir = NULL;
do
{
if (NULL == path)
{
errno = EINVAL;
result = -1;
break;
}
if ((dir = strrchr(path, '/')))
{
*dir = '\0';
result = mkdirr(path, mode, fail_on_exist);
*dir = '/';
if (result)
{
break;
}
}
if (strlen(path))
{
if ((result = mkdir(path, mode)))
{
char s[PATH_MAX];
sprintf(s, "mkdir() failed for '%s'", path);
perror(s);
if ((EEXIST == result) && (0 == fail_on_exist))
{
result = 0;
}
else
{
break;
}
}
}
} while (0);
return result;
}
And then call mkdirr() like this;
int main(void)
{
char p[] = "test/1/2/3";
if (-1 == mkdirr(p, 0777, 0))
{
perror("mkdirr() failed()");
}
return 0;
}

Getting the error "undefined reference to". Can you explain what it means and where I have made the mistake?

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <stdio_ext.h>
#include <string.h>
#include <signal.h>
#include <pwd.h>
#include <sys/types.h>
#include <crypt.h>
#include "pwent.h"
#define TRUE 1
#define FALSE 0
#define LENGTH 16
void sighandler() {
signal(SIGINT,SIG_IGN);
}
int main(int argc, char *argv[]) {
mypwent *passwddata;
/* see pwent.h */
char important[LENGTH] = "***IMPORTANT***";
char user[LENGTH];
char prompt[] = "password: ";
char swap_prompt[]="New password: ";
char again_prompt[]="Again: ";
char *user_pass;
char *new_pass;
char *again_pass;
int f_login;
char *en_pass;
char *envp[] = { NULL };
char *argvv[] = { "/bin/sh",NULL};
sighandler();
while (TRUE) {
/* check what important variable contains - do not remove, part of buffer overflow test */
printf("Value of variable 'important' before input of login name: %s\n",
important);
printf("login: ");
fflush(NULL); /* Flush all output buffers */
__fpurge(stdin); /* Purge any data in stdin buffer */
if (fgets(user,16,stdin) == NULL) /* gets() is vulnerable to buffer */
{
exit(0); /* overflow attacks. */
}
*/* check to see if important variable is intact after input of login name - do not remove */*
printf("Value of variable 'important' after input of login name: %*.*s\n",
LENGTH - 1, LENGTH - 1, important);
user_pass = getpass(prompt);
passwddata = mygetpwnam(user);
if (passwddata != NULL) {
en_pass=crypt(user_pass,passwddata->passwd_salt);
if (!strcmp(en_pass, passwddata->passwd)) {
if(passwddata->pwage==10){
printf("You need to swap your password!!! \n");
do{
new_pass=getpass(swap_prompt);
again_pass=getpass(again_prompt);
}while(strcmp(new_pass,again_pass));
printf("Password changed!!! \n");
passwddata->passwd=new_pass;
passwddata->pwage=0;
}else{
printf(" You're in !\n");
printf("Number of failed login is %d\n", passwddata->pwfailed);
passwddata->pwfailed=0;
passwddata->pwage++;
}
mysetpwent(user,passwddata);
setuid(passwddata->uid);
execve("/bin/sh",argvv,envp);
}else{
if(passwddata->pwfailed==3){
printf("You attempted too many times \n");
passwddata->pwfailed=0;
mysetpwent(user,passwddata);
return 0;
}
printf("Wrong password, please try again!!! \n");
f_login++;
passwddata->pwfailed=f_login;
mysetpwent(user,passwddata);
}
}else{
printf("Login Incorrect \n");
}
}
return 0;
}
So I get the error "undefined reference to mygetpwnam" and "undefined reference to mysetpwent". I am not sure what this exactly means and how to go about correcting it. This is a part of an assignment I am working on with regards to unix and their password systems.
You attempt to call the function mygetpwnam once in your code, and mysetpwent three times, yet those functions are not defined anywhere. Hence, you reference something undefined, an error.
"mygetpwnam" and "mysetpwent" are defined in pwd.h. Open and check if pwd.h has definition for "mygetpwnam" and "mysetpwent".
Check pwent.h to see if your functions are declared there (definition should be in pwent.c). Also make sure you haven't misspelled the function names. You should show us how you compile the program.

"Unknown Command" error when passing "uname" to execv()

So I have to build a program in C that practically takes a command from keyboard , split it into tokens that are stored in an array and use those tokens as input to "execv" (a command in ubuntu) , I chose the command "uname" with the parameter "-a", but for some reason it keeps saying "Comanda necunoscuta!" (Unknown Command!) Heres my code:
#include <stdio.h>
#include<stdlib.h>
#include <string.h> /*strtok strcpy*/
#include<malloc.h> /*malloc*/
#include <sys/types.h> /* pid_t */
#include <sys/wait.h> /* waitpid */
#include <unistd.h> /* _exit, fork */
int main()
{
int i=0;
char *cuvinte[256]; //words
char comanda[256]; //command
printf("Introduceti comanda: "); // command input
fgets(comanda,sizeof(comanda),stdin); // read command
char *c = strtok(comanda," "); // break command into tokens
while(c!=0)
{
cuvinte[i] = malloc( strlen( c ) + 1 ); //alocate memory
strcpy(cuvinte[i++],c); // copy them
printf("%s\n",c); // print them
c=strtok(NULL, " ,.!?");
}
printf("Sunt %d elemente stocate in array! \n\n",i); // no of elements stored
printf("Primul cuvant este: %s \n\n",cuvinte[0]); // shows the first token
if((cuvinte[0]=='uname')&&(cuvinte[1]=='-a')){ // here lays the problem i guess
/*face un proces copil*/
pid_t pid=fork();
if (pid==0) { /* procesul copil*/
static char *argv[]={"/bin/uname","-a",NULL};
execv(argv[0],argv);
exit(127); /*in caz ca execv da fail*/
}
else { /* pid!=0; proces parinte */
waitpid(pid,0,0); /* asteapta dupa copil */
}
}
else printf("Comanda necunoscuta !\n"); // problem
//getch();
return 0;
}
Firstly add
cuvinte[1][strlen(cuvinte[1])-1]='\0';
after the while loop and just before "printf("Sunt %d elemente stocate in array! \n\n",i);"
second thing
use
if((strcmp(cuvinte[0],"uname")==0) && (strcmp(cuvinte[1],"-a")==0))
instead of "=="
program will work !!
First of all, I don't have enough reputation to post a comment sorry for that.
I'm not sure you can compare two strings with the '==' operator in C. Try using the strcmp function.

Resources