Re: [linux-audio-dev] Command parser?

New Message Reply About this list Date view Thread view Subject view Author view Other groups

Subject: Re: [linux-audio-dev] Command parser?
From: David Slomin (david.slomin_AT_av.com)
Date: Wed Aug 23 2000 - 00:44:33 EEST


Juhana Sadeharju wrote:
>
> Hello. I need to read simple commands from a file and execute the commands
> as they are read. What would be a good system for reading them?

The age of application-specific parsers is largely over.

If your config file is mostly data-oriented, use XML. If it can
benefit from an interpreted command language, use Guile or Tcl
(languages designed for this task), or Python or Perl (languages
which can perform this task although not designed for it).

There are free/Free, platform independent parsers/interpreters
available for all of the above. All can be embedded into programs
written in C or C++; some can also be embedded into other hosts.

That said, the following code should work just fine. The trick
is to treat lines separately from words, and to treat string
versions of words separately from their numerical equivalents.
If you try to do it all in one step, scanf and friends tend to
blow up in your face.

int read_config_file(FILE *config_file)
{
   char buffer[1024], command[256], arg1[256], arg2[256], arg3[256];

   while (fgets(buffer, 1024, stream) != NULL)
   {
      if (buffer[0] == '#')
      {
         continue; // ignore comment lines
      }

      command[0] = '\0';
      arg1[0] = '\0';
      arg2[0] = '\0';
      arg3[0] = '\0';

      sscanf(buffer, "%s %s %s %s", command, arg1, arg2, arg3);

      if (strcmp(command, "command1") == 0)
      {
         float f;

         if (sscanf(arg1, "%f", &f) == 1)
         {
            command1(f);
         }
         else
         {
            error("error in argument 1 of command1");
            return -1;
         }
      }
      else if (strcmp(command, "command2") == 0)
      {
         if (sscanf(arg1, "%i", &i1) == 1)
         {
            if (sscanf(arg2, "%i", &i2) == 1)
            {
               if (sscanf(arg3, "%f", &f) == 1)
               {
                  command2(i1, i2, f);
               }
               else
               {
                  error("error at argument 3 of command2");
                  return -1;
               }
            }
            else
            {
               error("error in argument 2 of command2");
               return -1;
            }
         }
         else
         {
            error("error in argument 1 of command3");
            return -1;
         }
      }
      else if (strcmp(command, "command3") == 0)
      {
         // you get the idea...
      }
      else
      {
         error("invalid command");
         return -1;
      }
   }

   return 0;
}

Div.


New Message Reply About this list Date view Thread view Subject view Author view Other groups

This archive was generated by hypermail 2b28 : Wed Aug 23 2000 - 01:48:41 EEST