Programming for Computing 07 - 08

Chapter: The Command Line

Module Admin   Contents, Index   Schedule  
1: Intro to VB    2: First Program and Projects    3: Variables, assignment, Strings    4: Type Conversion, InputBox, Constants    5:Built-in Functions    6: If - decisions    7: Loops - while, for    Example - find smallest    8: Scopes: local, global    9: Writing Procedures.Parameters, Functions   
10: Objects    11: Design    12: Testing    13: Graphics    14: Controls and events    15: Listboxes    16: Arrays    17: Files    18: The Command Line   

Appendices(links etc)   Additional Lectures    Tutorials (not in printed notes)     Selected solutions (not in printed notes)     Assignments    Additions and Errata   

new

The  schedule page has info on what we will do each week.

This chapter explains:

  • how to create a console application;
  • console input-output;
  • The processing of command-line arguments;
  • running programs from the command prompt;
  • scripting with batch files.

Introduction

The user interface has changed enormously in power (and complexity) since the early days of computers. In the 1960's, a common device for interaction was the teletype (or operator's console) which was basically an electrical typewriter with a roll of paper for displaying text. All you could do was to type a line of text, which the program could interpret as a command or as data.

It might seem strange that in this time of mice. high-resolution screens, and voice input, that a style of interaction involving lines of text can be useful, but this is the case! Some types of program do not have a major interactive element. Here are some examples:

  • a program which calculates the amount of free space on a disk drive. All the user needs to do is state the drive. Such a program might also be run automatically, perhaps when files are deleted.
  • a program which prints a list of company employees. This list does not change very often. All we need to do is run the program.
  • a program which is one part of a larger task, running without human intervention. Such an approach is called 'scripting' or 'batch' programming. For example, when you boot up an operating system, a script (a file containing instructions which execute programs) is run.

A first console program

We shall create a small program which asks you for your name, then displays it. The steps to create a project are almost identical to creating a GUI program, except that we select 'Console Application' for the project type. Name the project Hello. The IDE will then display the following code:
Module Module1

    Sub Main()

    End Sub

End Module

We then modify the program so that it looks like:

Module Module1

    Sub Main()
        Dim name As String
        Console.WriteLine("Please enter your name:")
        name = Console.ReadLine()
        Console.WriteLine("Hi there " & name)
        Dim wait As String = Console.ReadLine()
    End Sub

End Module

Finally, use Save As, choosing the name Hello.vb. Run the program, and enter your name. Note the result, then press the Enter key to end the program. Figure 1 shows a screenshot of the program.

[command1.jpg]
Fig 1 - running the Hello console application.

Here is an explanation of the program.

  • The program is contained within a module, which is similar in nature to a class, but without any inheritance possibilities.
  • When the program is executed, the method named Main is called automatically. It starts things off.
  • The Console class is imported automatically, and provides similar methods to those we used to access files. We have:
    • WriteLine, which writes a string to the screen, followed by an end-of-line. Write is similar, but does not add the end-of-line.
    • ReadLine inputs a complete line of text from the keyboard, as a string. The end-of-line marker is not stored in the string.
  • When console applications terminate, their window closes automatically. As you will see, this is what we require in many cases, but for our first program it is inconvenient, because we can't see the output. To prevent the window closing, we have inserted an extra line:
    Dim wait As String = Console.ReadLine()
    
    We placed this immediately above the End Sub. Its effect is to wait for the user to enter another line of text - we can simply enter a blank line by pressing the enter key. You might use this line in the early stages of creating and debugging a console application, then remove it in the finished version.
  • This particular project was named Hello, and we named the VB file after it. The project name need not match the VB file name, but it was suitable in this case. The IDE will create the executable version in the file:
    \Hello\bin\Debug\Hello.exe
    
    i.e. within the bin\Debug directory of our project. The name bin is short for 'binary'.

    The name of the executable file Hello.exe was derived from the name of the VB file.

The command prompt: cd and dir

You are familiar with clicking on folder icons to navigate through folders, but when running console applications, it is sometimes necessary to use keyboard commands for the same tasks. Instructions are entered at the command prompt, which can beaccessed in several ways:
  • on Windows XP, use Windows Explorer to browse to the required folder. Right-click on the folder and select Open Command Window Here.
  • on other Windows systems, you might have to go via the Start menu, working through: Start | All Programs | Accessories | Command Prompt

    (though details vary slightly depending on your version of Windows. Sometimes you do not need to look as far as the Accessories menu. On earlier versions of Windows, it might be described as MS-DOS.)

When you run the command prompt, a black window appears where you can type commands. To navigate through directories, we use the dir (directory) and the cd (change directory) commands. They have lots of options, but we will present the minimum you need. Note that these commands use the older terminology of 'directory' rather than 'folder'. They mean the same thing.

The dir command

When you run the command prompt, a line is shown, of the form:
C:\TEMP>
This shows that you are on the C: drive, in the directory TEMP. Typing dir shows us the names of all the directories and files in the current directory, as in figure 2. Directories are indicated by DIR in angle brackets. To restrict the list to directories only, type:
dir /ad
The command is followed by a space, and capitals or lower-case letters can be used. This command is useful to remind you about directory names as you navigate.
[command2.jpg]
fig 2 - using the dir command

The cd command

This command is used to move between directories. Here are some examples. Note that .. is used to stand for the directory above the current one.
cd mydir                   change to the mydir sub-directory
cd ..                      move up  a level
cd ..\data                 move up, then into the data directory
Note that the prompt changes. Use this to check that your command worked properly. Finally, to move to another drive, we type its letter, in the form:
d:                        move to the d: drive

SELF-TEST QUESTION
Find out how to run the command prompt window on your computer. Experiment with the dir and cd commands. Navigate to a VB project directory, and find the exe file within the bin\Debug directory.
ANSWER:
A small amount of practice is needed. Remember to look at the prompt to see the current directory, and type dir to check on the exact spelling of directory names.

Ways of running programs

There are a number of ways to initiate the running of VB programs under Windows. Here are some of them:
  • you can run a program from the IDE. This is used when creating and debugging programs.
  • You can run a program by double-clicking on its name in Windows Explorer. For example, the above Hello program was saved as Hello.vb, and it can also be run by looking in the bin\Debug folder of its project folder and double-clicking on Hello.exe. Remember that its window will close automatically.
  • You can run a program by typing its name at the command prompt. For example, to run our Hello program, we open a command prompt window in the project's bin\Debug directory, and then enter the name of the exe file, as in:
    Hello.exe
    
    Figure 3 shows the command prompt window, after the program has been run. Note that the window does not close, and we could type another command.
    [command3.jpg]
    fig 3 - running Hello from the command prompt

    If you want to run the program whilst you are in another directory, you can enter the full path to the exe file. For example, if your project directory was stored at the top level of the C: drive, you would type:

    c:\Hello\bin\Debug\Hello.exe
    
  • You can also run a program in a 'batch' manner. Here is an example, which you can run by following these steps:
    1. use a text editor - such as NotePad in the Accessories folder - to create a file named hi.bat, and put these two lines of text in it:
      Hello.exe
      Hello.exe
      
      Save the file in the bin\Debug directory of your project.
    2. Run the bat file by double-clicking on hi.bat in Windows Explorer. Observe that your name is requested twice.
    As you have just seen, a batch file contains instructions to run a series of programs. Here we chose to run the same program twice. We shall discuss this approach in more detail later.

Classes in console applications

For small programs, you might choose to use a few methods, as in:
Module Module1

    Sub Main()
        MethodA()
    End Sub

    Private Sub MethodA()
        ... code for method
    End Sub

End Module
For larger programs, you might wish to incorporate library classes. This can be done by placing the appropriate Imports at the top of the file.

You might also wish to create new classes. As with GUI programs, you can put the classes in separate files, or in the same file.

Command-line arguments

When we run console applications, we often need to supply starting details for items such as file names to use. The program could use ReadLine to input such items - and this is a good approach in some cases. However, later we will see programs which operate without user interaction but which still need some form of initialization. This is where command-line arguments come into use.

Here is an example: we will write a program called Pick which searches through a specified file, picking out and displaying every line containing a specified string. Here is the code:

Imports System.IO
Module Module1

    Sub Main(ByVal args() As String)
        Dim line As String
        Dim fileName As String = args(0)
        Dim wanted As String = args(1)
        Dim inputStream As StreamReader = _
                           File.OpenText(fileName)

        line = inputStream.ReadLine()
        While line <> Nothing
            If line.IndexOf(wanted) >= 0 Then
                Console.WriteLine(line)
            End If
            line = inputStream.ReadLine()
        End While
        inputStream.Close()
    End Sub

End Module

The program reads each line in turn from a specified file (as we explained in chapter 18), and uses the IndexOf method from the String class to see if the required string exists anywhere within the line. If this is the case, we display the line on the screen.

Note that the program needs to get values for the strings fileName and wanted. Eventually we will use these in the conventional way via the command prompt window, but for debugging and testing, the IDE allows us to set up these values. Here is how:

  1. In the IDE, create a Console Application project named Pick, and enter the above VB code. Save the code in the file Pick.vb.
  2. Now we will set up the command-line arguments. From the menus, choose Project | Properties..., then click on Debug.
  3. In the Command line arguments area, enter the following:
    demo.txt "lines"
    
    then click OK. The strings for the arguments are separated by a space or spaces. You can use quotes around an argument if you wish, and this is essential if an argument itself contains spaces. Incidentally, if the file to be examined is stored elsewhere, you can use its full path when you specify the program arguments.
  4. create a file to work with, called demo.txt, containing these lines:
    These lines are
    a test of the Pick program.
    It finds and displays lines 
    containing a specified sub-string.
    

    To follow this example exactly, ensure that the file is stored in the bin\Debug directory within the Pick project directory.

When you run the program, its output will appear in a black window, and the window will close. To see the output, place the following line just above the End Sub, as we did in the Hello program:
Dim wait As String = Console.ReadLine()
Run the program again. You will see two lines shown below, each of which contains the string lines:
These lines are
It finds and displays lines
Press the 'enter' key to end the program.

When we run a console application, our Sub Main method is called by the run-time system. We do not call it ourselves. Any command-line arguments that we provide are passed into the method as an array of strings, which we chose to name as args. Before being placed in this array, some processing is done for us:

  • the arguments are split up. A space or spaces separates one from another.
  • Any spaces within quotes are not treated as a separator. For example, in our Pick program, we may have file paths containing spaces, or we may wish to find a string containing spaces. In these cases, we must set up the arguments with quotes surrounding them. The quotes are removed from the argument before it is passed to Sub Main.
  • The first argument is placed in position 0 of our array, not in position 1.
We can make use of the UBound function to find out how many arguments the user supplied, and reject any errors.


SELF-TEST QUESTION
Amend the Pick program so that it checks the number of supplied arguments. If there are not two arguments, the program should display an error message and terminate.
ANSWER:
We add an If to the code, and also ensure that we don't access any arguments before we have checked that they exist.
Dim line As String
Dim fileName As String
Dim wanted As String
If UBound(args) = 1 Then
    fileName = args(0)
    wanted = args(1)
    Dim inputStream As StreamReader = _
               File.OpenText(fileName)
    line = inputStream.ReadLine()
    While line <> Nothing
        If line.IndexOf(wanted) >= 0 Then
            Console.WriteLine(line)
        End If
        line = inputStream.ReadLine()
    End While
    inputStream.Close()
Else
    Console.WriteLine("Error: 2 arguments needed for Pick")
End If


SELF-TEST QUESTION
Modify the Pick program so that lower-case and upper-case versions of the required string are found.
ANSWER:
We convert both strings to upper-case before comparing, as in:
If line.ToUpper().IndexOf(wanted.ToUpper()) >= 0 Then

Scripting and output re-direction

Here we will examine some of the facilities that Windows systems offer for scripting, and actually do some scripting with our Pick program. Scripting covers a variety of techniques. Here we will regard a script as a file containing instructions for running a series of programs. They are known as batch files, and have the .bat extension. Their use promotes a 'building brick' approach, where we create new software by connecting existing software together, rather than coding from scratch.

Output re-direction lets us control the destination of output text from a program. Recall out previous programs. We used Console.WriteLine to send text to the screen. However, sometimes we wish to place the results in a file. Here is an example: we need to place the output from Pick into a file, so we can use it elsewhere. This can be done by opening a command prompt window, then using the cd command to move into the bin\Debug directory of the Pick project. Type the following:

Pick.exe demo.txt "lines" > results.txt
The use of > causes the text that would have appeared on the screen to be re-directed to the file results.txt in the bin\Debug directory. If this file existed already, it is over-written. If it did not exist, it is created.

We chose to put spaces around the > for ease of reading, though this is not essential.

Another matter of preference is the use of capitals. The command-line software is based on MS-DOS, an early Microsoft operating system. When you type file names and paths, these get converted to upper-case internally, so the same effect is obtained from either of these lines:

PICK.EXE DEMO.TXT "lines"
Pick.exe demo.txt "lines"
pick.exe demo.txt "lines"

Here is another example: we wish to find every line containing the word Dim in a VB program. Moreover, we wish to add these lines to the existing results.txt file from above. We type:

Pick.exe SomeProg.vb "Dim" >> results.txt
The >> symbol means 'append', and its action is very much like >, except that text is placed at the end of an existing file, rather than replacing the file.

Input re-direction is also possible, using <, but this requires a different technique for reading the data into the program. In our examples, we will always read from files rather than use input re-direction.

The benefit of output re-direction is that changing the destination of the data is simple: we don't need to re-write the program, or click through a file dialog. The program becomes more flexible.


SELF-TEST QUESTION
If we opened a command prompt window, moved into the bin\Debug directory of the Hello project, and typed:
Hello.exe > temp.txt
what would we expect to see on the screen and in the file temp.txt?


ANSWER:
The text from Write and WriteLine does not appear on the screen, so we have to guess that we must enter our name. In the file, we see:

Please enter your name: Hi there Bill


SELF-TEST QUESTION
Here are two cases where we use Pick. The first use is with >:
Pick.exe testfile.txt "Visual Basic" > out.txt
Pick.exe testfile.txt "Visual Basic" > out.txt
The second is with >>:
Pick.exe testfile.txt "Visual Basic" >> out.txt
Pick.exe testfile.txt "Visual Basic" >> out.txt
How does the use of > or >> affect the contents of the file out.txt?
ANSWER:
In the > case, the file will contain only the lines with the required string in them. The second use of > overwrites any previous contents.

In the >> case, the file contains the same lines duplicated. In addition, if the output file is not empty to start with, its original contents will still be there.


Scripting and batch files

Before the days of personal computers, punched cards were used. The programmer had to prepare a 'batch' of cards containing the program, and instructions on how to run the program. This concept of a sequence of instructions has its modern equivalent in the bat file. We can prepare a file containing instructions to run a number of programs; each program runs without user interaction.

Here is an example: as part of the documentation for a large VB program (here named Big.vb), we wish to create a file containing the header of every Sub and Function method. This requires Pick to be used twice. We can do this by:

  1. creating a file named (for example) getsubs.bat within the bin\Debug directory of the Pick project, containing:
    Pick.exe Big.vb "Sub" > subs.txt
    Pick.exe Big.vb "Function" >> subs.txt
    

  2. Executing the file getsubs.bat. This can be done in several ways, as we saw earlier. We could double-click on its name in Windows Explorer, or type its name at the command prompt. In either case, this would initiate the execution of the instructions within the file.
The first use of Pick puts all the lines containing Sub into the file subs.txt, and the second use appends any lines containing the string Function to the end of the same file. The instructions to run Pick are obeyed in top-to-bottom order, working down the batch file.


SELF-TEST QUESTION
Assume that we are given a large VB program, and we wish to find every line which contains an If referring to a variable sum. For example, we want lines such as:
If sum = 0 Then
If a = sum Then
Prepare a batch file, which uses Pick to perform the task. Hint: use a temporary file named (for example) temp.txt
ANSWER:
The first execution of Pick should pick out every If line. These lines should then be used as input to another run of Pick, which picks out the lines containing sum. Here is the code, which you might place in a file named ifsum.bat:
Pick.exe Big.vb "If" > temp.txt
Pick.exe temp.txt "sum" > out.txt

The selected lines have been re-directed to a file named out.txt.

Programming principles

  • Not all programs warrant a GUI.
  • I/O re-direction can make programs more flexible.
  • A batch file solution can prevent the need to write new software.

Programming pitfalls

  • Forgetting to put a call to ReadLine when you wish to observe output on the screen.
  • Accessing command-line arguments from position 1 in the string array. In fact, the items begin at position 0.

Grammar spot

There is no new VB grammar in this chapter.

New language elements

  • The Console class, and the methods ReadLine, WriteLine, Write.
  • The Module for console applications.

New IDE elements

  • There is an option to create a console application
  • Command-line arguments can be set within the IDE, for debugging and testing.

Summary

  • Console applications can display lines of text on the screen, and can read lines of text that the user types.
  • They can access command-line arguments.
  • They can be run in a variety of ways.
  • Their output can be re-directed to a file with > and >>.
  • Batch files can contain instructions to execute programs.

Exercises

1. Write a console application which asks the user to enter an integer. The doubled value should be calculated and displayed. (Assume the user will not make any input errors.)

2. Write a console application which inputs a series of exam marks (one at a time) from the user. The program should display the sum of all the marks. The marks are all zero or above, and a negative number is used end the sequence of marks. (Use a While loop.)

3. Write a console application which displays the first line of a file. The file name should be specified as a command-line argument. Check that the correct result appears on the screen, then run it with output re-direction to place the output in a file.

4. Write a console application which counts the number of lines in a file, and displays the result.

5. It has been suggested that the complexity of a program can be measured by counting the number of decisions and loops it has. Ideally, we wish to avoid creating programs that are unduly complex. With the aid of our Pick program and your solution from Q4, create a batch file which adds up the number of If, While, For, and Select statements in a VB file, and displays this single number. (Do not write any new VB code.)

6. Write a console application which reads a file line-by-line and displays it on the screen. However, lines containing a particular sub-string are not to be displayed. The program has two command-line arguments: the file name, and the sub-string. The latter can be enclosed in quotes if it contains spaces. Use this program to provide a 'collapsed' version of a VB program, by omitting every line containing eight spaces. (This will cause the inner nested code to be ignored, but the outer lines (such as Imports, Class, and Private to be displayed.)

7. Write a console application which replaces one string by another throughout a file. The program has three arguments: the file name, the string to be replaced, and the string to replace it with. Read the whole file at once into a string, and make use of the Change method used in chapter 16. Redirect the output to a new file.

8. Write a program named Multirep, which does multiple string replacements in a file. The arguments for the program are the input file name and the name of a file containing pairs of lines specifying from/to replacements. Here is an example. We wish to replace every Mr by Mrs and every him by her in the file data.txt. We run the program by typing:

Multirep data.txt changes.txt > out.txt
The file changes.txt contains:
Mr
Mrs
him
her
If you know another programming language, investigate the use of Multirep in converting a VB program into that language.

Module Admin   Contents, Index