Search code examples
cimplementationfsm

How to implement a fsm


I want to parse output from a commandline tool using the fsm programming model. What is the simplest implementation of a fsm that is possible for this task?


Solution

  • Basically, the core idea of a finite state machine is that the machine is in a "state" and, for every state, the behaviour of the machine is different from other states.

    A simple way to do this is to have an integer variable (or an enum) which stores the status, and a switch() statement which implements, for every case, the required logic.

    Suppose you have a file of the followin kind:

    something
    begin
      something
      something2
    end
    something
    

    and you duty is to print the part between begin/end. You read the file line by line, and switch state basing on the content of the line:

    // pseudo-C code
    enum state {nothing, inblock};
    enum state status;
    string line;
    
    status = nothing;
    
    while (!eof(file)) {
      readline(line);
      switch(status) {
        case nothing:
          if (line == "begin") status=inblock;
          break;
        case inblock:
          if (line == "end")
            status=nothing;
            else print(line);
          break;
      }
    }
    

    In this example, only the core idea is shown: a "status" of the machine and a mean to change status (the "line" read from file). In real life examples probably there are more variables to keep more informations for every state and, perhaps, the "status" of the machine can be stored in a function pointer, to avoid the burden and rigidity of the switch() statement but, even so, the programming paradigm is clean and powerful.