int main(int argc, char* argv[]) { char *input; char *str; char *tokv[5]; int tokc; char *expansion; int result; printf("Press Ctrl-D or enter \"exit\" to end session.\n" "Enter \"help\" to display a command list.\n"); using_history(); try { Shell shell; while (!shell.exitFlag()) { input = readline("bossa> "); if (!input) { printf("\n"); break; } for (str = input; *str && isspace(*str); str++); if (*str) { result = history_expand(input, &expansion); if (result >= 0 && result != 2) { add_history(expansion); tokc = split(expansion, tokv, ARRAY_SIZE(tokv)); shell.invoke(tokv, tokc); } free(expansion); } free(input); } } catch(...) { printf("\nUnhandled exception\n"); return 1; } return 0; }
//------------------------------------------------------------------------------ int expand_from_history(const char* text, char** expanded) { int result; expanded = NULL; result = history_expand((char*)text, expanded); if (result < 0) { free(expanded); } return result; }
int main(int argc, char *argv[]) { int count, i, tmp, j; int builtin_f; int hist_expand_status; cmd **cmds; char *hist_tmp; sh_init(); using_history(); while (buf = readline(getprompt())) { if (buf[0] == '!') { // history expand hist_expand_status = history_expand(buf, &hist_tmp); if (hist_expand_status == 1) { buf = realloc(buf, (strlen(hist_tmp)+1) * sizeof(char)); strcpy(buf, hist_tmp); } else { fprintf(stderr, "shell: %s: event not found\n", buf); free(buf); continue; } } if (*buf) add_history(buf); cmds = malloc(INIT_SIZE * sizeof(cmd *)); cmds_init(cmds, INIT_SIZE); tmp = strlen(buf); buf = realloc(buf, (tmp + 2) * sizeof(char)); buf[tmp] = '\n'; buf[tmp+1] = '\0'; count = parse(buf, cmds, INIT_SIZE); buf[tmp] = '\0'; //print(cmds, count); if (count != -1) for (i = 0; i < count; ++i) { builtin_f = 0; for (j = 0; j < BUILTIN_N; ++j) if (strcmp(cmds[i]->argv[0], builtin_list[j]) == 0) { (*builtins[j])(cmds[i]); builtin_f = 1; break; } if (!builtin_f) exec_cmd(cmds[i]); } jobctl_print_msgs(); for (i = 0; i < count; ++i) cmd_dealloc(cmds[i]); free(buf); } return 0; }
int main (int argc, char **argv) { char *line, *s; progname = argv[0]; initialize_readline(); /* Bind our completer. */ stifle_history(7); /* Loop reading and executing lines until the user quits. */ for ( ; done == 0; ) { line = readline ("FileMan: "); if (!line) break; /* Remove leading and trailing whitespace from the line. Then, if there is anything left, add it to the history list and execute it. */ s = stripwhite(line); if (*s) { char* expansion; int result; result = history_expand(s, &expansion); if (result < 0 || result == 2) { fprintf(stderr, "%s\n", expansion); } else { add_history(expansion); execute_line(expansion); } free(expansion); } free(line); } exit (0); return 0; }
/* NOTE: 1999-04-30 This is the asynchronous version of the command_line_input function; command_line_input will become obsolete once we use the event loop as the default mechanism in GDB. */ static void command_line_handler (char *rl) { static char *linebuffer = 0; static unsigned linelength = 0; char *p; char *p1; char *nline; int repeat = (instream == stdin); if (annotation_level > 1 && instream == stdin) { printf_unfiltered (("\n\032\032post-")); puts_unfiltered (async_annotation_suffix); printf_unfiltered (("\n")); } if (linebuffer == 0) { linelength = 80; linebuffer = (char *) xmalloc (linelength); } p = linebuffer; if (more_to_come) { strcpy (linebuffer, readline_input_state.linebuffer); p = readline_input_state.linebuffer_ptr; xfree (readline_input_state.linebuffer); more_to_come = 0; } #ifdef STOP_SIGNAL if (job_control) signal (STOP_SIGNAL, handle_stop_sig); #endif /* Make sure that all output has been output. Some machines may let you get away with leaving out some of the gdb_flush, but not all. */ wrap_here (""); gdb_flush (gdb_stdout); gdb_flush (gdb_stderr); if (source_file_name != NULL) ++source_line_number; /* If we are in this case, then command_handler will call quit and exit from gdb. */ if (!rl || rl == (char *) EOF) { command_handler (0); return; /* Lint. */ } if (strlen (rl) + 1 + (p - linebuffer) > linelength) { linelength = strlen (rl) + 1 + (p - linebuffer); nline = (char *) xrealloc (linebuffer, linelength); p += nline - linebuffer; linebuffer = nline; } p1 = rl; /* Copy line. Don't copy null at end. (Leaves line alone if this was just a newline). */ while (*p1) *p++ = *p1++; xfree (rl); /* Allocated in readline. */ if (p > linebuffer && *(p - 1) == '\\') { *p = '\0'; p--; /* Put on top of '\'. */ readline_input_state.linebuffer = xstrdup (linebuffer); readline_input_state.linebuffer_ptr = p; /* We will not invoke a execute_command if there is more input expected to complete the command. So, we need to print an empty prompt here. */ more_to_come = 1; display_gdb_prompt (""); return; } #ifdef STOP_SIGNAL if (job_control) signal (STOP_SIGNAL, SIG_DFL); #endif #define SERVER_COMMAND_LENGTH 7 server_command = (p - linebuffer > SERVER_COMMAND_LENGTH) && strncmp (linebuffer, "server ", SERVER_COMMAND_LENGTH) == 0; if (server_command) { /* Note that we don't set `line'. Between this and the check in dont_repeat, this insures that repeating will still do the right thing. */ *p = '\0'; command_handler (linebuffer + SERVER_COMMAND_LENGTH); display_gdb_prompt (0); return; } /* Do history expansion if that is wished. */ if (history_expansion_p && instream == stdin && ISATTY (instream)) { char *history_value; int expanded; *p = '\0'; /* Insert null now. */ expanded = history_expand (linebuffer, &history_value); if (expanded) { /* Print the changes. */ printf_unfiltered ("%s\n", history_value); /* If there was an error, call this function again. */ if (expanded < 0) { xfree (history_value); return; } if (strlen (history_value) > linelength) { linelength = strlen (history_value) + 1; linebuffer = (char *) xrealloc (linebuffer, linelength); } strcpy (linebuffer, history_value); p = linebuffer + strlen (linebuffer); } xfree (history_value); } /* If we just got an empty line, and that is supposed to repeat the previous command, return the value in the global buffer. */ if (repeat && p == linebuffer && *p != '\\') { command_handler (saved_command_line); display_gdb_prompt (0); return; } for (p1 = linebuffer; *p1 == ' ' || *p1 == '\t'; p1++); if (repeat && !*p1) { command_handler (saved_command_line); display_gdb_prompt (0); return; } *p = 0; /* Add line to history if appropriate. */ if (instream == stdin && ISATTY (stdin) && *linebuffer) add_history (linebuffer); /* Note: lines consisting solely of comments are added to the command history. This is useful when you type a command, and then realize you don't want to execute it quite yet. You can comment out the command and then later fetch it from the value history and remove the '#'. The kill ring is probably better, but some people are in the habit of commenting things out. */ if (*p1 == '#') *p1 = '\0'; /* Found a comment. */ /* Save into global buffer if appropriate. */ if (repeat) { if (linelength > saved_command_line_size) { saved_command_line = xrealloc (saved_command_line, linelength); saved_command_line_size = linelength; } strcpy (saved_command_line, linebuffer); if (!more_to_come) { command_handler (saved_command_line); display_gdb_prompt (0); } return; } command_handler (linebuffer); display_gdb_prompt (0); return; }
char * handle_line_of_input (struct buffer *cmd_line_buffer, char *rl, int repeat, const char *annotation_suffix) { struct ui *ui = current_ui; int from_tty = ui->instream == ui->stdin_stream; char *p1; char *cmd; if (rl == NULL) return (char *) EOF; cmd = command_line_append_input_line (cmd_line_buffer, rl); if (cmd == NULL) return NULL; /* We have a complete command line now. Prepare for the next command, but leave ownership of memory to the buffer . */ cmd_line_buffer->used_size = 0; if (from_tty && annotation_level > 1) { printf_unfiltered (("\n\032\032post-")); puts_unfiltered (annotation_suffix); printf_unfiltered (("\n")); } #define SERVER_COMMAND_PREFIX "server " server_command = startswith (cmd, SERVER_COMMAND_PREFIX); if (server_command) { /* Note that we don't set `saved_command_line'. Between this and the check in dont_repeat, this insures that repeating will still do the right thing. */ return cmd + strlen (SERVER_COMMAND_PREFIX); } /* Do history expansion if that is wished. */ if (history_expansion_p && from_tty && input_interactive_p (current_ui)) { char *history_value; int expanded; expanded = history_expand (cmd, &history_value); if (expanded) { size_t len; /* Print the changes. */ printf_unfiltered ("%s\n", history_value); /* If there was an error, call this function again. */ if (expanded < 0) { xfree (history_value); return cmd; } /* history_expand returns an allocated string. Just replace our buffer with it. */ len = strlen (history_value); xfree (buffer_finish (cmd_line_buffer)); cmd_line_buffer->buffer = history_value; cmd_line_buffer->buffer_size = len + 1; cmd = history_value; } } /* If we just got an empty line, and that is supposed to repeat the previous command, return the previously saved command. */ for (p1 = cmd; *p1 == ' ' || *p1 == '\t'; p1++) ; if (repeat && *p1 == '\0') return saved_command_line; /* Add command to history if appropriate. Note: lines consisting solely of comments are also added to the command history. This is useful when you type a command, and then realize you don't want to execute it quite yet. You can comment out the command and then later fetch it from the value history and remove the '#'. The kill ring is probably better, but some people are in the habit of commenting things out. */ if (*cmd != '\0' && from_tty && input_interactive_p (current_ui)) gdb_add_history (cmd); /* Save into global buffer if appropriate. */ if (repeat) { xfree (saved_command_line); saved_command_line = xstrdup (cmd); return saved_command_line; } else return cmd; }
int ridl_executeline(char *line, int flags) { int error = 0; // normal exit by hitting ^D if (line == NULL) { printf("\n"); return(IDL_Cleanup(IDL_FALSE)); }; // magic lines start with :, anything else is passed to IDL int firstcharIndex = ridl_firstchar(line); char firstchar = line[firstcharIndex]; if (firstchar == ':') { if ((firstcharIndex + 1 < strlen(line)) && (line[firstcharIndex + 1] == '!' || line[firstcharIndex + 1] == '^')) { // TODO: eventually this shouldn't be a magic command, but should be // activated when a space is entered char *expansion; int expansion_result; char *expansion_line = (char *)malloc(strlen(line) + 1); strcpy(expansion_line, line + firstcharIndex + 1); expansion_result = history_expand(expansion_line, &expansion); switch (expansion_result) { case -1: ridl_warning("error in expansion"); break; case 2: printf("%s\n", expansion); break; case 0: case 1: ridl_executestr(expansion, 1); break; } free(expansion_line); free(expansion); } else { int search_length; char *cmd = ridl_getnextword(line, firstcharIndex, &search_length); if (strcmp(cmd, ":colors") == 0) { use_colors = use_colors ? 0 : 1; if (use_colors) { printf("colors on\n"); } else { printf("colors off\n"); } } else if (strcmp(cmd, ":doc") == 0) { int search_length; char *routine = ridl_getnextword(line, firstcharIndex + 5, &search_length); char *man = (char *)malloc(8 + strlen(routine)); sprintf(man, "man, '%s'", routine); int error = IDL_ExecuteStr(man); free(man); free(routine); } else if (strcmp(cmd, ":notebook") == 0) { if (ridl_isnotebooking()) ridl_closenotebook(); int search_length; char *filename = ridl_getnextword(line, firstcharIndex + 9, &search_length); if (strlen(filename) == 0) { ridl_warning("must specify filename of notebook"); } else { ridl_setnotebooking(1); ridl_initnotebook(filename); } free(filename); } else if (strcmp(cmd, ":pref") == 0) { int search_length; char *has_args = ridl_getnextword(line, firstcharIndex + 5, &search_length); if (strlen(has_args) == 0) { ridl_printpreferences(); } else { char *pref_line = line + 6; ridl_process_pref_line(pref_line); } free(has_args); } else if (strcmp(cmd, ":log") == 0) { if (ridl_islogging()) ridl_closelog(); int search_length; char *filename = ridl_getnextword(line, firstcharIndex + 4, &search_length); if (strlen(filename) == 0) { ridl_warning("must specify filename of log"); } else { ridl_setlogging(1); ridl_initlog(filename); } free(filename); } else if (strcmp(cmd, ":unnotebook") == 0) { if (ridl_isnotebooking()) { ridl_closenotebook(); IDL_ToutPop(); ridl_setnotebooking(0); } else ridl_warning("not currently notebooking"); } else if (strcmp(cmd, ":unlog") == 0) { if (ridl_islogging()) { ridl_closelog(); IDL_ToutPop(); ridl_setlogging(0); } else ridl_warning("not currently logging"); } else if (strcmp(cmd, ":tee") == 0) { if (ridl_isteeing()) ridl_closelog(); int search_length; char *filename = ridl_getnextword(line, firstcharIndex + 4, &search_length); if (strlen(filename) == 0) { } else { ridl_setteeing(1); ridl_initlog(filename); } free(filename); } else if (strcmp(cmd, ":untee") == 0) { if (ridl_isteeing()) { ridl_closelog(); IDL_ToutPop(); ridl_setteeing(0); } else ridl_warning("not currently teeing"); } else if (strcmp(cmd, ":save_graphic") == 0) { if (ridl_isnotebooking()) { ridl_notebookgraphic(); } else { ridl_warning("turn on notebooking to save graphics"); } } else if (strcmp(cmd, ":time") == 0) { char *command = line + 6; ridl_magic_time(command); } else if (strcmp(cmd, ":help") == 0) { int f; int display_keybindings = ridl_magic_help(line, firstcharIndex); if (display_keybindings) { printf("\nrIDL keybindings:\n"); for(f = 0; f < N_FUNMAP_FUNCTIONS; f++) { ridl_printfunmap(funmap_function_names[f], funmap_functions[f]); } } } else if (strcmp(cmd, ":history") == 0) { ridl_magic_history(line, firstcharIndex); } else if (strcmp(cmd, ":histedit") == 0) { ridl_magic_histedit(line, firstcharIndex); } else if (strcmp(cmd, ":version") == 0) { ridl_printversion(); } else { ridl_warning("unknown magic command '%s'", cmd); error = 1; } } } else { if (line && *line) { // check for .edit if (firstchar == '.') { int search_length; char *cmd = ridl_getnextword(line, firstcharIndex, &search_length); if (strcmp(cmd, ".edit") == 0 || strcmp(cmd, ".edi") == 0 || strcmp(cmd, ".ed") == 0 || strcmp(cmd, ".e") == 0) { char *file = ridl_getnextword(line, firstcharIndex + strlen(cmd) + 1, &search_length); ridl_launcheditor(file); free(file); add_history(line); ridl_cmdnumber++; ridl_updateprompt(); } else { // execute standard executive commands error = ridl_executestr(line, 1); } free(cmd); } else { int lastcharIndex = ridl_lastchar(line); char lastchar = lastcharIndex == -1 ? ' ' : line[lastcharIndex]; if (lastchar == '?') { char cmd[1000]; char varname[1000]; strncpy(varname, line, lastcharIndex); varname[lastcharIndex] = '\0'; sprintf(cmd, "ridl_varhelp, %s", varname); int status = IDL_ExecuteStr(cmd); } else { // determine if line is continued char *line_continued = ridl_linecontinued(line); if (continued) { if (line_continued) { strcat(ridl_continuedline, line); } else { // execute IDL commands that were continued on several lines continued = 0; strcat(ridl_continuedline, line); error = ridl_executestr(ridl_continuedline, 1); } } else { if (line_continued) { continued = 1; strcpy(ridl_continuedline, line); } else { // execute normal IDL commands error = ridl_executestr(line, 1); } } } } } } return(error); }
char * getConsoleInput(Client c, const char *prompt, int linemode, int exit_on_error) { char *line = NULL; char *buf = NULL; size_t length; (void) exit_on_error; (void) linemode; do { #ifdef HAVE_LIBREADLINE if (prompt) { if (buf) free(buf); buf = readline(prompt); /* add a newline to the end since that makes further processing easier */ if (buf) { add_history(buf); length = strlen(buf); buf = realloc(buf, length + 2); if( buf == NULL){ GDKerror("getConsoleInput: " MAL_MALLOC_FAIL); return NULL; } buf[length++] = '\n'; buf[length] = 0; } line = buf; } else #endif { #ifndef HAVE_LIBREADLINE if (prompt) { fputs(prompt, stdout); fflush(stdout); } #endif if (buf == NULL) { buf= malloc(BUFSIZ); if( buf == NULL){ GDKerror("getConsoleInput: " MAL_MALLOC_FAIL); return NULL; } } line = fgets(buf, BUFSIZ, stdin); } if (line == NULL) { /* end of file */ if (buf) free(buf); return NULL; } else length = strlen(line); if (length > 0 ) { /* test for special commands */ while (length > 0 && (*line & ~0x7F) == 0 && isspace((int) *line)) { line++; length--; } /* in the switch, use continue if the line was processed, use break to send to parser */ switch (*line) { case '\0': /* empty line */ break; case '\\': switch (line[1]) { case 'q': free(buf); return NULL; default: break; } line= NULL; break; case '<': /* read commands from file */ if (line[length - 1] == '\n') line[--length] = 0; if (line[length - 1] == '\r') line[--length] = 0; /* doFile(mid, line + 1, 0);*/ line= NULL; continue; case '>': /* redirect output to file */ line++; length--; if (line[length - 1] == '\n') line[--length] = 0; if (line[length - 1] == '\r') line[--length] = 0; if (c->fdout && c->fdout != GDKout && c->fdout != GDKerr){ close_stream(c->fdout); c->fdout= 0; } if (length == 0 || strcmp(line, "stdout") == 0) c->fdout = GDKout; else if (strcmp(line, "stderr") == 0) c->fdout = GDKerr; else if ((c->fdout = open_wastream(line)) == NULL) { c->fdout = GDKout; mnstr_printf(GDKerr, "Cannot open %s\n", line); } line = NULL; continue; #ifdef HAVE_LIBREADLINE case '!': { char *nl; int i; if(line[1]=='\n') { for(i=0; i< history_length; i++){ nl= history_get(i)? history_get(i)->line:0; if( nl) mnstr_printf(c->fdout, "%d %s\n", i, nl); } line = NULL; } else if( history_expand(line,&nl) ==1 ) { mnstr_printf(c->fdout,"#%s",nl); line= nl; } else line= NULL; } continue; #endif case '?': if( line[1] && line[1]!='\n'){ showHelp( c->nspace,line+1, c->fdout); } else showCommands(); line= NULL; continue; } /* make sure we return a pointer that can (and should) be freed by the caller */ if (line) line = buf; } } while (line == NULL); return line; }
/* Warning: May be running setuid root! */ static void _interactive_dsh(opt_t * opt) { pid_t pid; char prompt[64]; char history_filename[MAXPATHLEN]; char *cmd = NULL; int got_history_file = 1; int len; snprintf(prompt, sizeof(prompt), "%s> ", opt->progname); using_history (); len = sizeof (history_filename); if (_history_file_create (history_filename, len) < 0) { got_history_file = 0; } while ((cmd = readline(prompt)) != NULL) { int errnum; char *expansion; if ((errnum = history_expand (cmd, &expansion))) { err ("%p: %s\n", expansion); } free (cmd); if ((errnum < 0) || (errnum == 2)) { free (expansion); continue; } cmd = expansion; if (!strcmp(cmd, "history")) { _history_list (); continue; } add_history (cmd); if (strlen(cmd) == 0) { /* empty line */ free(cmd); continue; } if (!strcmp(cmd, "quit") || !strcmp(cmd, "exit")) { free(cmd); /* quit or exit */ break; } if ((strlen(cmd) != 0) && (got_history_file)) append_history (1, history_filename); /* * fork dsh so we can ignore SIGINT in prompt loop */ switch (pid = fork()) { case -1: /* error */ errx("%p: fork: %m\n"); case 0: /* child - run cmd */ opt->cmd = Strdup(cmd); dsh(opt); Free((void **) &opt->cmd); exit(0); default: /* parent - wait */ while (waitpid(pid, NULL, 0) < 0) { if (errno != EINTR) break; } break; } free (cmd); } }
//------------------------------------------------------------------------------ static char* call_readline_impl(const char* prompt) { static int initialised = 0; int expand_result; char* text; char* expanded; char* prepared_prompt; char cwd_cache[MAX_PATH]; // Initialisation if (!initialised) { initialise_clink_settings(); initialise_lua(); load_history(); rl_catch_signals = 0; rl_startup_hook = initialise_hook; initialised = 1; } // If no prompt was provided assume the line is prompted already and // extract it. If a prompt was provided filter it through Lua. prepared_prompt = NULL; if (prompt == NULL) { prepared_prompt = extract_prompt(1); // Even though we're not going to display filtered result the extracted // prompt is run through Lua. This is a little bit of a hack, but helps // to keep behaviour consistent. if (prepared_prompt != NULL) { char buffer[1024]; str_cpy(buffer, prepared_prompt, sizeof(buffer)); lua_filter_prompt(buffer, sizeof_array(buffer)); } } else { prepared_prompt = filter_prompt(prompt); } GetCurrentDirectory(sizeof_array(cwd_cache), cwd_cache); // Call readline do { rl_already_prompted = (prompt == NULL); text = readline(prepared_prompt ? prepared_prompt : ""); if (!text) { goto call_readline_epilogue; } // Expand history designators in returned buffer. expanded = NULL; expand_result = history_expand(text, &expanded); if (expand_result < 0) { free(expanded); } else { free(text); text = expanded; // If there was some expansion then display the expanded result. if (expand_result > 0) { hooked_fprintf(NULL, "History expansion: %s\n", text); } } add_to_history(text); } while (!text || expand_result == 2); call_readline_epilogue: free_prompt(prepared_prompt); SetCurrentDirectory(cwd_cache); return text; }
void shell() { current_database = -1; char entrada[1000], nomeBD[TAM_NOME_BANCO]; int resultado = 0, codDB = -1; nomeBD[0]='\0'; char *current_db_name = strdup(">");//inicializa com nenhum banco conectado char *start; start = strdup("dbms-start");//este comando posteriormente como start do banco, no momento ele é automatico printf("\nWelcome to the DBMS Interface.\nType 'help' '\\h' for help.\n\n"); /** * **************************** * * Comandos do shell * * **************************** */ using_history ();//função para usar o histórico read_history (".history_file"); while(1) { int nTokens; strcpy(entrada, readline(current_db_name)); /** * Adiciona ao histórico */ if (entrada[0]) { char *expansion; int result; result = history_expand (entrada, &expansion); if (result) fprintf (stderr, "%s", expansion); if (result < 0 || result == 2) { free (expansion); continue; } add_history (expansion); strncpy (entrada, expansion, sizeof (entrada) - 1); free (expansion); write_history (".history_file");//adiciona no histórico } char **tokens = tokenize( trim_white_space(remove_newline(entrada)),' ',&nTokens); /** * Opção para criar tabela e banco de dados */ if (strcmp(strtolower(tokens[0]),"create")==0) { if(strcmp(strtolower(tokens[1]),"table")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } createTable(entrada,current_database); } else if(strcmp(strtolower(tokens[1]),"database")==0) { if (nTokens >= 5) { printf("Invalid command. Type help to show de interface usage.\n"); continue; } if (strlen(tokens[2]) > TAM_NOME_BANCO ) { printf("Database name too big.\n"); continue; } resultado = checkCreateDB( remove_semicolon(tokens[2]) );//verifica a existência do nome e grava-o no arquivo if(resultado==-1) { printf("Error creating database file.\n"); } if(resultado==-3) { printf("Database exists.\n"); } else { printf("Database created successfully.\n"); } } else { printf("Invalid command. Type help to show de interface usage.\n"); continue; } } /** * Conecta ao banco de dados passado como parâmetro */ else if(strcmp(strtolower(tokens[0]),"\\c") == 0){ if (nTokens != 2) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } char *name_db = remove_semicolon(tokens[1]); codDB = busca(name_db,1); //função chamada para conecção no banco, retorna o codigo do banco ao conectar if (codDB >= 0) { strcpy(nomeBD, name_db); //passa o nome do bd, para a variavel mostrar ao usuario qual o banco conectado free(current_db_name); current_db_name = (char*) malloc (sizeof(char)*(strlen(name_db)+3)); if (current_db_name == NULL) { printf("Out of memory.\nAborting...\n"); } strcpy(current_db_name,name_db); current_database = codDB; strcat(current_db_name,"=#"); current_db_name[strlen(current_db_name)] = '\0'; } else { printf("No such database '%s'.\n", name_db); continue; } } /** * Insere tuplas em uma tabela */ else if(strcmp(strtolower(tokens[0]),"insert")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } insert(entrada,current_database); } /** * Imprime as tabelas do banco de dados atual * ou o esquema de uma tabela */ else if(strcmp(strtolower(tokens[0]),"\\d")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } if (nTokens >= 3) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } else if (nTokens == 1) { //imprime tabelas do banco de dados listaTabelas(current_database); } else { //imprime o esquema de uma tabela char *t = table_name_real(remove_semicolon(tokens[1]),current_database); if(!verificaNomeTabela(t)){ printf("Invalid table name.\n"); free(t); continue; } struct fs_objects objeto = leObjeto(t);//para verificar se a tabela esta no banco show_schema(objeto,tokens[1]); free(t); } } /** * Comando temporário para imprimir tabela */ else if (strcmp(strtolower(tokens[0]),"select")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } selectTable(entrada,current_database); } /** * Imprime os registros da tabela passada */ else if (strcmp(strtolower(tokens[0]),"show")==0) { if (nTokens != 2) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } if (current_database == -1) { printf("Not connected to any database.\n"); continue; } if (verificaNomeTabela(table_name_real(remove_semicolon(tokens[1]),current_database) ) == 0 ) { printf("Table %s doesn't exist.\n",remove_semicolon(tokens[1])); continue; } char *t = table_name_real(remove_semicolon(tokens[1]),current_database); char *file = table_name_real(remove_semicolon(tokens[1]),current_database); strcat(file,".dat"); if (existeArquivo(file) == 0) { printf("Table is empty.\n" ); continue; } imprime(t); free(file); free(t); } /** * Lista os bancos existentes */ else if(strcmp(strtolower(tokens[0]),"\\l")==0) { if (nTokens != 1) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } //LISTA os bancos existentes listaBancos(); } /** * Opção para deletar o banco de dados e tabelas */ else if(strcmp(strtolower(tokens[0]),"drop")==0) { if (nTokens != 3) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } else if(strcmp(strtolower(tokens[1]),"table") == 0){ if (current_database == -1) { printf("Not connected to any database.\n"); continue; } if (verificaNomeTabela(table_name_real(remove_semicolon(tokens[2]),current_database) ) == 0 ) { printf("Table %s doesn't exist.\n",remove_semicolon(tokens[2])); continue; } char *t = table_name_real(remove_semicolon(tokens[2]),current_database); char *exist = table_name_real(remove_semicolon(tokens[2]),current_database); int ok = excluirTabela(t); if (ok == SUCCESS) { printf("Table deleted successfully.\n"); } free(exist); free(t); } else if(strcmp(strtolower(tokens[1]),"database") == 0){ char *exist = table_name_real(remove_semicolon(tokens[2]),current_database); strcat(exist,".dat"); if (existeArquivo(exist) != 0) { printf("The database is not empty for drop, there are existing tables.\n" ); continue; } exist = remove_semicolon(tokens[2]); codDB = busca(exist,1); if(codDB == current_database) { printf("Cannot drop the currently open database.\n"); continue; } int drop = dropDatabase(remove_semicolon(tokens[2])); if(drop == 1)printf("Database deleted successfully.\n"); free(exist); } } /** * Ajuda ao usuário com exemplos da sintaxe dos comandos */ else if (strcmp(strtolower(tokens[0]),"help")==0 || strcmp(strtolower(tokens[0]),"\\h")==0) { if (nTokens != 1) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); } help(); } /** * Imprime mensagem de copyright */ else if(strcmp(strtolower(remove_semicolon(tokens[0])),"\\copyright")==0) { printf("\nDatabase Management System\n"); printf("\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose, without fee, and without a written agreement\nis hereby granted, provided that the above copyright notice and this\nparagraph and the following two paragraphs appear in all copies.\n"); printf("\nTHIS SOFTWARE IS BEING DEVELOPED BY STUDENTS OF DATABASE II CLASS AT UNIVERSIDADE FEDERAL DA FRONTEIRA SUL.\n\n"); } /** * Comando de saída */ else if(strcmp(strtolower(remove_semicolon(tokens[0])),"exit")==0) { break; } else if(strcmp(strtolower(remove_semicolon(tokens[0])),"quit")==0) { break; } else if(strcmp(strtolower(remove_semicolon(tokens[0])),"bye")==0) { break; } else if(strcmp(strtolower(remove_semicolon(tokens[0])),"\\q")==0) { break; } else { printf("Invalid command. Type help to show the interface usage.\n"); continue; } } free(start); free(current_db_name); }
int main (int argc, char **argv) { char buf[256], *e, *t, *t0; int fd[2], i, j, n, n0, p, q; static char *signame[16] = { "", /*1*/ "Hangup on controlling terminal or death of controlling process", /*2*/ "Interrupt from keyboard", /*3*/ "Quit from keyboard", /*4*/ "Illegal Instruction", /*5*/ "Trace/breakpoint trap", /*6*/ "Abort signal", /*7*/ "Bus error", /*8*/ "Floating point exception", /*9*/ "Kill -9 signal", /*10*/ "Signal 10", /*11*/ "Segmentation fault (invalid memory reference)", /*12*/ "Signal 12", /*13*/ "Broken pipe", /*14*/ "Alarmm (SIGALRM)", /*15*/ "Termination signal (SIGTERM)" }; n = 0; progname = argv[0]; if (--argc <= 0) return usage(1); t = *++argv; if (*t == '-') { if (*++t == '?' && !t[1]) return usage(0); if (!strcmp(t, "-help")) return usage(0); if (*t >= '0' && *t <= '9') { n = (int)strtol(t,&t,0); if (*t) return usage(1); } else if (*t != '-' || t[1]) return usage(1); if (!(t = *++argv)) return usage(1); --argc; } if (pipe(fd)) { fprintf(stderr, "%s: pipe failure\n", progname); return 2; } if (!(q = fork())) { dup2(fd[0], 0); close(fd[0]); close(fd[1]); execvp(argv[0], argv); fprintf(stderr, "Cannot invoke %s\n", argv[0]); return 2; } signal(SIGINT, SIG_IGN); signal(SIGPIPE, catch_sigpipe); signal(SIGCHLD, catch_sigpipe); close(fd[0]); p = fd[1]; using_history(); if (n) stifle_history(n); rl_bind_key('\t', rl_insert); /* treat tab as tab */ /* history_expansion_char = 0x1b; */ /* escape: treat ! as ! */ t = t0 = 0; while(!pipegone) { if (t != t0) free(t); in_readline = 1; if (!(t = readline(0))) { pipegone = 1; write(p, buf, 0); /* try to send EOF */ write(1, "\n", 1); break; } in_readline = 0; if (pipegone) break; n0 = strlen(t); if (t[n = n0 - 1] == '\n') { if (!n) { write(p, t, n0); continue; } t[n] = 0; } else n = -1; i = history_expand(t, &e); if (i > 0) { if (i == 2) { n = strlen(e); if (n < sizeof(buf)) { memcpy(buf, e, n); buf[n++] = '\n'; write(2, buf, n); } else { write(2, e, n); if (pipegone) break; write(2, "\n", 1); } free(e); continue; } free(t); t = e; } else free(e); if (!t0 || strcmp(t,t0)) { add_history(t); if (t0) free(t0); t0 = t; } if (i >= 0) { n = strlen(t); if (n < sizeof(buf)) { memcpy(buf, t, n); buf[n++] = '\n'; write(p, buf, n); } else { write(p, t, n); if (pipegone) break; write(p, "\n", 1); } } else { if (n >= 0) t[n] = '\n'; write(p, t, n0); } } close(p); i = 0; do n = wait(&i); while(n != -1 && n != q); if (j = i & 0xff) { if (j < 16) fprintf(stderr, "%s\n", signame[j]); else fprintf(stderr, "Signal %d\n", j); return 1; } return i >> 8; }
main () { char line[1024], *t; int len, done = 0; line[0] = 0; using_history (); while (!done) { printf ("history$ "); fflush (stdout); t = fgets (line, sizeof (line) - 1, stdin); if (t && *t) { len = strlen (t); if (t[len - 1] == '\n') t[len - 1] = '\0'; } if (!t) strcpy (line, "quit"); if (line[0]) { char *expansion; int result; using_history (); result = history_expand (line, &expansion); if (result) fprintf (stderr, "%s\n", expansion); if (result < 0 || result == 2) { free (expansion); continue; } add_history (expansion); strncpy (line, expansion, sizeof (line) - 1); free (expansion); } if (strcmp (line, "quit") == 0) done = 1; else if (strcmp (line, "save") == 0) write_history ("history_file"); else if (strcmp (line, "read") == 0) read_history ("history_file"); else if (strcmp (line, "list") == 0) { register HIST_ENTRY **the_list; register int i; the_list = history_list (); if (the_list) for (i = 0; the_list[i]; i++) printf ("%d: %s\n", i + history_base, the_list[i]->line); } else if (strncmp (line, "delete", 6) == 0) { int which; if ((sscanf (line + 6, "%d", &which)) == 1) { HIST_ENTRY *entry = remove_history (which); if (!entry) fprintf (stderr, "No such entry %d\n", which); else { free (entry->line); free (entry); } } else { fprintf (stderr, "non-numeric arg given to `delete'\n"); } } } }