Readline programming


 
Thread Tools Search this Thread
Top Forums Programming Readline programming
# 8  
Old 05-12-2011
Readline Programming

Yeah exactly iam trying to develop for an application same like GDB. So if you can say how the gdb works with source code then that could may help me out. Here for my application i want to develop similar as what GDB does but doing using GNU Readline line(Linux). I am not understanding whether I can do it using GNU readline or not.

---------- Post updated at 05:56 AM ---------- Previous update was at 05:53 AM ----------

Yeah exactly iam trying to develop for an application same like GDB. So if you can say how the gdb works with source code then that could may help me out. Here for my application i want to develop similar as what GDB does but doing using GNU Readline line(Linux). I am not understanding whether I can do it using GNU readline or not.
# 9  
Old 05-12-2011
So you want to develop a debugger? Or just add readline capability to GDB? For the later, take a look at how rlwrap does things, and try to build on top of that.
This User Gave Thanks to pludi For This Post:
# 10  
Old 05-13-2011
Readline Programming

Actually here I post my code till where I have achieved command line completion,history.


Code:
/* fileman.c -- A tiny application which demonstrates how to use the
   GNU Readline library.  This application interactively allows users
   to manipulate files and their modes. */

#include <stdio.h>
#include <sys/types.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/errno.h>

#include <readline/readline.h>
#include <readline/history.h>
#define ARRAY_SIZE 4
extern char *xmalloc ();

/* The names of functions that actually do the manipulation. */
int com_list __P((char *));
int com_view __P((char *));
int com_rename __P((char *));
int com_stat __P((char *));
int com_pwd __P((char *));
int com_delete __P((char *));
int com_help __P((char *));
int com_cd __P((char *));
int com_quit __P((char *));

/* A structure which contains information on the commands this program
   can understand. */

typedef struct {
  char *name;            /* User printable name of the function. */
  rl_icpfunc_t *func;        /* Function to call to do the job. */
  char *doc;            /* Documentation for this function.  */
} COMMAND;

COMMAND commands[] = {
  { "cd", com_cd, "Change to directory DIR" },
  { "delete", com_delete, "Delete FILE" },
  { "help", com_help, "Display this text" },
  { "?", com_help, "Synonym for `help'" },
  { "list", com_list, "List files in DIR" },
  { "ls", com_list, "Synonym for `list'" },
  { "pwd", com_pwd, "Print the current working directory" },
  { "quit", com_quit, "Quit using Fileman" },
  { "rename", com_rename, "Rename FILE to NEWNAME" },
  { "stat", com_stat, "Print out statistics on FILE" },
  { "view", com_view, "View the contents of FILE" },
  { (char *)NULL, (rl_icpfunc_t *)NULL, (char *)NULL }
    };

/* Forward declarations. */
char *stripwhite ();
COMMAND *find_command ();

/* The name of this program, as taken from argv[0]. */
char *progname;

/* When non-zero, this means the user is done using this program. */
int done;

char *
dupstr (s)
     int s;
{
  char *r;

  r = xmalloc (strlen (s) + 1);
  strcpy (r, s);
  return (r);
}

main (argc, argv)
     int argc;
     char **argv;
{
  char *line, *s;

  progname = argv[0];

  initialize_readline ();    /* Bind our completer. */

  /* 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)
        {
          add_history (s);
          execute_line (s);
        }

      free (line);
    }
  exit (0);
}

/* Execute a command line. */
int
execute_line (line)
     char *line;
{
  register int i;
  COMMAND *command;
  char *word;

  /* Isolate the command word. */
  i = 0;
  while (line[i] && whitespace (line[i]))
    i++;
  word = line + i;

  while (line[i] && !whitespace (line[i]))
    i++;

  if (line[i])
    line[i++] = '\0';

  command = find_command (word);

  if (!command)
    {
      fprintf (stderr, "%s: No such command for FileMan.\n", word);
      return (-1);
    }

  /* Get argument to command, if any. */
  while (whitespace (line[i]))
    i++;

  word = line + i;

  /* Call the function. */
  return ((*(command->func)) (word));
}

/* Look up NAME as the name of a command, and return a pointer to that
   command.  Return a NULL pointer if NAME isn't a command name. */
COMMAND *
find_command (name)
     char *name;
{
  register int i;

  for (i = 0; commands[i].name; i++)
    if (strcmp (name, commands[i].name) == 0)
      return (&commands[i]);

  return ((COMMAND *)NULL);
}



/* Strip whitespace from the start and end of STRING.  Return a pointer
   into STRING. */
char *
stripwhite (string)
     char *string;
{
  register char *s, *t;

  for (s = string; whitespace (*s); s++)
    ;
    
  if (*s == 0)
    return (s);

  t = s + strlen (s) - 1;
  while (t > s && whitespace (*t))
    t--;
  *++t = '\0';

  return s;
}


/* **************************************************************** */
/*                                                                  */
/*                  Interface to Readline Completion                */
/*                                                                  */
/* **************************************************************** */

char *command_generator __P((const char *, int));
char **fileman_completion __P((const char *, int, int));

/* Tell the GNU Readline library how to complete.  We want to try to
   complete on command names if this is the first word in the line, or
   on filenames if not. */
initialize_readline ()
{
  /* Allow conditional parsing of the ~/.inputrc file. */
  rl_readline_name = "FileMan";
   rl_attempted_completion_function = fileman_completion;
    
}

/* Attempt to complete on the contents of TEXT.  START and END
   bound the region of rl_line_buffer that contains the word to
   complete.  TEXT is the word to complete.  We can use the entire
   contents of rl_line_buffer in case we want to do some simple
   parsing.  Returnthe array of matches, or NULL if there aren't any. */
char **
fileman_completion (text, start, end)
     const char *text;
     int start, end;
{
  char **matches;
  matches = (char **)NULL;

  /* If this word is at the start of the line, then it is a command
     to complete.  Otherwise it is the name of a file in the current
     directory. */
  if (start == 0) {
    matches = rl_completion_matches (text, command_generator);
}
  return (matches);
}
/* Generator function for command completion.  STATE lets us
   know whether to start from scratch; without any state
   (i.e. STATE == 0), then we start at the top of the list. */
char *
command_generator (text, state)
     const char *text;
     int state;
{
  static int list_index, len;
  char *name;

  /* If this is a new word to complete, initialize now.  This
     includes saving the length of TEXT for efficiency, and
     initializing the index variable to 0. */
  if (!state)
    {
      list_index = 0;
      len = strlen (text);
    }

  /* Return the next name which partially matches from the
     command list. */
  while (name = commands[list_index].name)
    {
      list_index++;

      if (strncmp (name, text, len) == 0)
        return (dupstr(name));
    }

  /* If no names matched, then return NULL. */
  return ((char *)NULL);
}


/* **************************************************************** */
/*                                                                  */
/*                       FileMan Commands                           */
/*                                                                  */
/* **************************************************************** */

/* String to pass to system ().  This is for the LIST, VIEW and RENAME
   commands. */
static char syscom[1024];

/* List the file(s) named in arg. */
com_list (arg)
     char *arg;
{
  if (!arg)
    arg = "";

  sprintf (syscom, "ls -FClg %s", arg);
  return (system (syscom));
}

com_view (arg)
char *arg;
{
  if (!valid_argument ("view", arg))
    return 1;

  sprintf (syscom, "more %s", arg);
  return (system (syscom));
}

com_rename (arg)
     char *arg;
{
  too_dangerous ("rename");
  return (1);
}

com_stat (arg)
     char *arg;
{
  struct stat finfo;

  if (!valid_argument ("stat", arg))
    return (1);

  if (stat (arg, &finfo) == -1)
    {
      perror (arg);
      return (1);
    }

  printf ("Statistics for `%s':\n", arg);

  printf ("%s has %d link%s, and is %d byte%s in length.\n", arg,
          finfo.st_nlink,
          (finfo.st_nlink == 1) ? "" : "s",
          finfo.st_size,
          (finfo.st_size == 1) ? "" : "s");
  printf ("Inode Last Change at: %s", ctime (&finfo.st_ctime));
  printf ("      Last access at: %s", ctime (&finfo.st_atime));
  printf ("    Last modified at: %s", ctime (&finfo.st_mtime));
  return (0);
}

com_delete (arg)
     char *arg;
{
  too_dangerous ("delete");
  return (1);
}

/* Print out help for ARG, or for all of the commands if ARG is
   not present. */
com_help (arg)
     char *arg;
{
  register int i;
  int printed = 0;

  for (i = 0; commands[i].name; i++)
    {
      if (!*arg || (strcmp (arg, commands[i].name) == 0))
        {
          printf ("%s\t\t%s.\n", commands[i].name, commands[i].doc);
          printed++;
        }
    }

  if (!printed)
    {
      printf ("No commands match `%s'.  Possibilties are:\n", arg);

      for (i = 0; commands[i].name; i++)
        {
          /* Print in six columns. */
          if (printed == 6)
            {
              printed = 0;
              printf ("\n");
            }

          printf ("%s\t", commands[i].name);
          printed++;
        }

      if (printed)
        printf ("\n");
    }
  return (0);
}

/* Change to the directory ARG. */
com_cd (arg)
     char *arg;
{
  if (chdir (arg) == -1)
    {
      perror (arg);
      return 1;
    }

  com_pwd ("");
  return (0);
}

/* Print out the current working directory. */
com_pwd (ignore)
     char *ignore;
{
  char dir[1024], *s;

  s = getcwd (dir, sizeof(dir) - 1);
  if (s == 0)
    {
      printf ("Error getting pwd: %s\n", dir);
      return 1;
    }

  printf ("Current directory is %s\n", dir);
  return 0;
}

/* The user wishes to quit using this program.  Just set DONE
   non-zero. */
com_quit (arg)
     char *arg;
{
  done = 1;
  return (0);
}

/* Function which tells you that you can't do this. */
too_dangerous (caller)
     char *caller;
{
  fprintf (stderr, "%s: Too dangerous for me to distribute.\n", caller);
  fprintf (stderr, "Write it yourself.\n");
}

/* Return non-zero if ARG is a valid argument for CALLER,
   else print an error message and return zero. */
int
valid_argument (caller, arg)
     char *caller, *arg;
{
  if (!arg || !*arg)
    {
      fprintf (stderr, "%s: Argument required.\n", caller);
      return (0);
    }

  return (1);
}

To which i need to add above said command line option completion:

Last edited by pludi; 05-13-2011 at 07:41 AM..
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Programming

Trouble compiling program using the readline library.

Hi: in the info page for readline library I read -- Function: void rl_variable_dumper (int readable) Print the readline variable names and their current values to `rl_outstream'. If READABLE is non-zero, the list is formatted in such a way that it can be made part of an... (1 Reply)
Discussion started by: stf92
1 Replies

2. UNIX for Dummies Questions & Answers

From iOS programming to Linux system programming

Hello. I like Linux and C programming language. Allways wanted to understand kernel and become a Linux system programmer. And I also like Objective-C and iOS. These two programming areas have relations: 1. Linux and iOS are UNIX-like systems, POSIX compliant. 2. It is useful to know C language... (2 Replies)
Discussion started by: Rockatansky
2 Replies

3. Shell Programming and Scripting

How do I get my shell back to normal readline?

I just ran an application that crashed... but before it did, it managed to set readline echo off, and probably a bunch of other settings. Is there any way I can just tell my shell to re-initialize? To get back to whatever state existed before my shell got messed up by this evil program? (2 Replies)
Discussion started by: jjinno
2 Replies

4. Shell Programming and Scripting

using readline with parameter

dear all, i have code shell like this but i want to using parameter for this shell how i can do that :ex ./sample.sh 100 500sample.sh START=${1} LAST=${2} for (( a=${START}; a<=${LAST}; a++ )) do { echo $a } donethx for your advice (5 Replies)
Discussion started by: zvtral
5 Replies

5. Programming

Error:readline() on closed filehandle Perl

Hi, i have run the below perl code and i am getting an error Error:readline() on closed filehandle OR at run.pl line 31. CODE: =========================================== open OR,$ARGV; while (<OR>) { # find the batch date next if length $_ < 3; # BLANK LINE # last if $. > 120; #... (3 Replies)
Discussion started by: pspriyanka
3 Replies

6. Shell Programming and Scripting

Readline Formatting

Hi All, I have a function that loops through an XML file line by line and spits it the content out to a new file (sometimes certain lines need changing). This all works fine, however the formatting of the original XML is not kept. for example:- <?xml version="1.0"?> <mysqldump>... (3 Replies)
Discussion started by: robfwauk
3 Replies

7. Programming

C Programming - Hardware Programming

Can someone help me on suggesting some ways to access the memory content in RAM directly from C/C++ source code. Please provide me any book name or any URL so that I can get an exhaustive knowledge over it. If possible please give me some tips on interacting with hardwares directly through... (3 Replies)
Discussion started by: nandumishra
3 Replies

8. Programming

Readline problems

I'm having problems with libreadline. When I write text longer than the current line, the text wraps back to the beginning of the line rather than to the next line. Also, when I use the arrow keys to edit something in that beginning part, it won't display at all (so I can edit only if I remember... (5 Replies)
Discussion started by: CRGreathouse
5 Replies

9. Shell Programming and Scripting

cat vs head vs readline get variable from txt file

I have a file with a single filename in it, which I want to assign to a BASH variable, so I've been trying: c=$(head -1 somefile) echo $c which outputs correctly, but them when I do ... somecommand $c it says it can't find the file, is that because it's grabbing the whole line, and... (5 Replies)
Discussion started by: unclecameron
5 Replies

10. UNIX for Dummies Questions & Answers

Carreer:Networking Programming in Unix (C programming Language)

Hello, I am trying to learn Networking Programming in C in unix enviorment. I want to know how good it is to become a network programmer. i am crazy about Network programming but i also want to opt for the best carreer options. Anybody experienced Network Programmer, please tell me is my... (5 Replies)
Discussion started by: vibhory2j
5 Replies
Login or Register to Ask a Question