Tuesday, March 17, 2020

DOS programming - ECHO and TYPE

If you're new to programming, this how-to video is for you. Let's explore how to write some simple FreeDOS utilities, using C.

I think the easiest programs to demonstrate are ECHO and TYPE.


In the video, I walk through how to write a simple ECHO command, which is a great first example when you're learning to write C prorgams. The ECHO command just prints the command line arguments it was given (it echoes them back to the user). In FreeDOS, ECHO is an internal command, so it's part of the COMMAND.COM shell. But for this programming example, we'll write our own version of ECHO as an external command (a standalone EXE or COM program).

Every C program starts with a few lines to include parts of the C library:
#include <stdio.h>
#include <stdlib.h>

The stdio.h file contains definitions for functions that do input or output (called "I/O"). The stdlib.h file contains definitions for other parts of the C standard library of functions (hence "lib" is short for "library").

Now let's write a program to perform the ECHO command. In C, the main part of the program is the main function.
#include <stdio.h>
#include <stdlib.h>

int
main (int argc, char **argv)
{
  int i;
  
  for (i = 1; i < argc; i++)
  {

    printf ("%s ", argv[i]);
  }
  
  putchar ('\n');
  
  exit (0);
}

A few things in that example:

The command line is represented as argc and argv. The argc value is the argument count. This tells the program how many arguments came to the program. And argv is the argument vector that contains a list of strings on the command line. A string would be defined as char *, because char * defines a pointer to a string value. But since this is a list of strings, you need another * to indicate the pointer to the list. That's why you get char ** instead of just char *. Some older programs might instead use char *argv[].

The for loop runs through all arguments starting at position 1. That's because the "0th" entry in argv is actually the program's name. We want to print all arguments after the program's name, so we start at position 1.

The i++ is shorthand to increment by 1. You could have instead written i=i+1 and that would have been fine here. But I learned it as i++, so that's how I write it. On a similar note, i-- is similar to i=i-1. If you use the ++ and -- notation, note that ++i and i++ are subtly different.

The printf() function is a formatted print statement. The quoted string as its first argument is the format that printf() uses. Here, %s means to print a string. You can also use %d to print an integer (decimal, as opposed to some other number format like binary).

End the program with exit() or return(). You can use return() to exit the main() function, but I learned C in an earlier standard, so I prefer to exit the program using exit(). In the main() function, both do the same thing.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.