C Function to read instructions from the file and obey them

How to write a C Program Function to read instructions from the file and obey them in C Programming Language ?


This C Program function to read instructions from the file and obey them.

Solution:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. #include "display.h"
  5.  
  6. typedef unsigned char byte;
  7.  
  8. int getopcode(byte b){
  9.         return ((>> 6) & 0x3);
  10. }
  11. int getoperand(byte b, bool s){
  12.   if(&& (>> 5) & 1){
  13.     return (-32) + (& 0x1F);
  14.   } else {
  15.     return (& 0x3F);
  16.   }
  17. }
  18. struct state {
  19.         int x;
  20.         int y;
  21.         int pen;
  22. };
  23.  
  24. struct state DX(struct state s, int dx, display *d){
  25.   if (s.pen == 1) line(d, s.x, s.y, s.x + dx, s.y);
  26.   s.x = s.x + dx;
  27.   return s;
  28. }
  29. struct state DY(struct state s, int dy, display *d){
  30.   if (s.pen == 1) line(d, s.x, s.y, s.x, s.y + dy);
  31.   s.y = s.y + dy;
  32.   return s;
  33. }
  34. struct state DT(struct state s, int t, display *d){
  35.   pause(d, t);
  36.   return s;
  37. }
  38. struct state PEN(struct state s){
  39.   if(s.pen == 1){
  40.     s.pen = 0;
  41.   } else {
  42.     s.pen = 1;
  43.   }
  44.   return s;
  45. }
  46.  
  47. void interpet(FILE *in, display *d) {
  48.         struct state s = { 0, 0, 0 };
  49.         byte b;
  50.         bool sign = true;
  51.         b = fgetc(in);
  52.         while(! feof(in)) {
  53.                 int opcode = getopcode(b);
  54.                 printf("%d %d\n",opcode, operand);
  55.                 if (opcode == 0) s = DX(s, getoperand(b, sign), d);
  56.                 if (opcode == 1) s = DY(s, getoperand(b, sign), d);
  57.                 if (opcode == 2){
  58.                         sign = false;
  59.                         s = DT(s, getoperand(b, sign), d);
  60.                 }
  61.                 if (opcode == 3) s = PEN(s);
  62.                 b = fgetc(in);
  63.         }
  64. }
  65.  
  66.  
  67. // TODO: upgrade this function to read instructions from the file and obey them
  68. void run(char *filename, bool testing) {
  69.     FILE *in = fopen(filename, "rb");
  70.     if (in == NULL) {
  71.         printf("Can't open %s\n", filename);
  72.         exit(1);
  73.     }
  74.  
  75.     display *= newDisplay(filename, 200, 200, testing);
  76.     interpet(in, d);
  77.     end(d);
  78.     fclose(in);
  79.     if (testing) printf("Sketch %s OK\n", filename);
  80. }


Learn More :