Lab 2b -- Using UNIX And An Editor

Objectives: 

Learn how to manipulate files using UNIX commands.
Learn how to use UNIX directories.
Learn how to type in a C++ program.
Learn how to correct errors in typing.
Learn how to compile a C++ program.
Learn how to save a C++ program permanently.
Learn how to execute a C++ program.
Learn how to print a C++ program.

Click Here to CREATE ANSWER SHEET for LAB 2

Sections:

Introduction
In the early days of computing, all programmers programmed the computer using machine language since that is the only language that the computer really understands. However, today programmers use high level languages (languages very close to the written word) because of the invention of compilers. Examples of high level languages include C++, C, BASIC, FORTRAN, Pascal, and Ada. Today programmers may use C++, for example, to provide instructions to the computer instead of using machine language. Since the only language that a computer understands is machine language, we must have some type of translator which is able to take a C++ program (source code) and translate this code to machine language. This translator is called a compiler. A C++ compiler takes C++ source code and translates this code into object code (the machine language version of C++ source code). This lab is an introduction to the UNIX C++ compiler and its programming environment.

The language C++ was designed by Bjarne Stroustrup of AT&T Bell Labs in 1983. "Its main purpose is to make writing good programs easier and more pleasant for the individual programmer. C++ evolved, and continues to evolve, to cope with problems encountered by users, and through discussions between the author and his friends and colleagues." While C++ supports object-oriented programming, it will be used in a classical paradigm in CS 1.

As you work through this lab, you will be asked to do several exercises. Some exercises are provided for your learning experience. Some exercises will be used to determine your grade on this lab. Some exercises request that you generate a printout. Do all exercises to be successful on this lab. If you have not already done so, click on the link to the right above to generate an answer sheet.

Logging on to the Server
In Lab 1, you found that the computer system you will use for CSCI 1170 is an HP9000. Its name is frank. Frank runs the UNIX operating system, an extremely powerful and popular system.


Exercise 1:
LOG ON USING THE X WINDOW SYSTEM: We will be using the UNIX X Window system for the exercises below. Do NOT use a telnet program for the exercises below. (That means, for example, do not use PuTTY.)

To connect to frank via the X Window system, we again be using xterm program. Double-click the mouse on the XTerm frank.mtsu.edu desktop icon that looks something like this:


XTerm Icon

A box, similar to the one below, will pop-up.


XTerm Login
In this box, enter your username in the field labeled "User ID". After entering your username, use the tab key to skip to the field labeled "Password" and enter your password. Once both fields are filled in, click the "OK" button to log on. (If you have forgotten your username or password, ask the lab assistant for help.) If the log in is successful, an xterm window will pop up on the desktop. In this xterm window, you will find the UNIX  frank%   prompt at which you can enter UNIX commands. Once you are logged in, you need to arrange the windows for the browser and xterm so that one is not completely over the other. Click the left mouse button on the title bar of the xterm window, hold it down and drag the window until at least part of it is outside the browser window. It is OKAY to minimize an xterm window; for now, don't resize the xterm window. You can make either window active by clicking the mouse on it. Try that now and leave the browser window active.


The UNIX Operating System
The UNIX operating system was developed by Ken Thompson and Dennis Ritchie of AT&T Bell Labs in the late 1960's and early 1970's. UNIX is not an acronym. It is a pun on MULTICS, a failed system AT&T was experimenting with when Thompson began the UNIX development. Thompson, Ritchie, and their associates were programmers who chose short names for UNIX commands. Short names are great for poor typists but often cause confusion for a novice. UNIX commands are usually named with the first two consonants from a word that (sort of) describes the purpose of the command. They (and almost everything) are always in lower case letters. For example, cp is for copy, rm is for remove (delete), ls is for list (directory); vi is for visual editor (oops!), and lp is for line printer.


Exercise 2:
Enter the operating system we are using in CSCI 1170. Place your answer on the answer sheet created above. To make the answer sheet window active, click on Exercise 2 above. After you have placed your answer on the answer sheet, minimize the window containing the answer sheet (click on the '-' on the title bar) to continue the lab.  



Before we learn how to use a few UNIX commands, we will explain what we mean by a "file," the thing(s) most UNIX commands operate on. A file is an electronic repository for information. A file could hold the text of a letter to a friend, a set of high-level (text) instructions to the computer, or a collection of binary (non-text) machine instructions readable only by the computer. A directory is a collection of (related) files. If a manilla folder is an analogy for a file, then the file drawer would represent a directory. You will need a file for experimentation. It should be copied from a directory that will be used throughout the course. One directory can contain another can contain another, etc. In UNIX the directory names are separated by a "/" as in /users/depts2/csci117/public_html/1170. The actual name of the file goes at the right end separated from the directory name that contains it by a "/".


Exercise 3:
Make the xterm window active and drag it so you can see the example below.

Although the xterm window can be resized, it MUST be at least 24 rows long and 80 columns wide. Any smaller than these minimum dimensions and certain commands get messed up. You can check the current size of your window by entering the following UNIX command:
          % stty  size
(Remember, do NOT enter the percent sign as part of your command. It is meant to represent the prompt provided by the system.) This will display the number of rows followed by the column width. If the window is too small, resize it larger.

Copy the file cla2a.cc from the departmental 1170 directory to your account by typing the command below at the prompt in the xterm window

% cp $CLA/cla2a.cc cla2a.cc

(Note: Do not try to cut and paste this command from the browser to the xterm window. There is no straightforward way to do this.)


In later sections you will learn how to create a file of high-level C++ instructions with the "NEdit" editor and how to use the aCC compiler to create a executable file of machine instructions for frank. First, we explain a few simple commands. Read this section, then do the exercises below.

To display a (text) file named cla2a.cc on the screen, type

% cat cla2a.cc
or
% more cla2a.cc
or
% less cla2a.cc

The command cat (short for "catenate", an old version of the word "concatenate") displays (catenates it to what is already on the screen) the contents of the file cla2a.cc on the screen. If it is longer than one screen (usually 24 lines), the first part of the screen scrolls off the top of the screen as other lines are displayed. You will have to be a speed reader to keep up. To see one screen at a time, use the "more" command instead of "cat" More displays the first screen of text from cla2a.cc and waits for you to press a key. Pressing a carriage return advances one line; the space bar advances one screen of text; typing "q" will quit (exit); typing "/" followed by a word or phrase (and return) searches for the first occurrence of the given word or phrase. The "less" command is similar to "more", but more advanced. (The pun here is that "less is more".)


Exercise 4:
Make the xterm window active and try out the three commands (cat, more, and less) above. Type each command in the xterm window and observe the difference. There is nothing to turn in as a result of this exercise.

Read the following but don't type any of these commands until you reach Exercise 5.

The Computer Science Computer Lab has a line printer, csp1, that produces a hardcopy printout on greenbar paper; it is located in KOM 351 to the left of the entrance to KOM 360.

To send a copy of the file cla2a.cc to the csp1 line printer, type

% lph cla2a.cc

Usually each student is expected to obtain her/his own printout from the line printer. To make sure you know how to obtain your printout, please read the instructions affixed to the printer or ask a Lab Worker to show you.

If you want the lines numbered, use

% pr -n -t -e4 cla2a.cc | lph

"pr" is a UNIX formatting command -- it does things like number the lines as they are being displayed or change the output appearance of tabs (using -"e4"). The vertical line (or stroke) between "pr" and "lph" is the UNIX pipe symbol. It makes the output from "pr" (which usually goes to the screen) go through the "pipeline" to become the input for "lph" which sends it to the printer. Since lph's input comes from the pipeline, you don't need to specify a file to print.


Exercise 5:
Make the xterm window active; position it so you can see the UNIX command below and type the command shown below. It causes the file, cla2a.cc, to be printed (with line numbers and tabs expanded to four spaces) and places (at least part of) your name on the banner page:

% pr  -n  -t  -e4  cla2a.cc  |  lph

Your printout can be found in the printer in KOM 351 (to the left of the entrance to room 360).
This hardcopy printout will be turned in with your answer sheet at the end of the lab.


Exercise 6:
We will not tell you to make the xterm window active anymore when we ask you to enter a command. YOU SHOULD REMEMBER TO DO IT ON YOUR OWN.

By trying them, convince yourself that these two command lines accomplish the same end result (there is nothing to turn in as a result of this exercise):

% cat cla2a.cc | pr -n

% pr -n cla2a.cc

Exercise 7:
Type the command

% pwd

to print (display) your working directory name. Enter your working directory name on the answer sheet. Remember, to open the window containing the answer sheet, click on "Exercise 7:" above.


The "ls" command displays a list of file names in the current working directory. A directory is like a drawer in a file cabinet which holds the files (the manilla folders). You can see (display) the list of files in your directory by typing

% ls

or

% ls -l (Note: use letter 'l' not the number '1')

The "-l" option ('l' for long) gives information about the file, as well as its name, such as its size and its protection (privilege or mode) bits: rwxr--r--. These bits describe what you (the owner) and others can do to the file: r = read; w = write; x = execute. If the first character on a line is a 'd' then the file is a directory (and not a regular file). If you were successful customizing your account, you should have directories. Find them.


Exercise 8:
Obtain a list of files in your directory by typing in both of the commands above. Count the number of regular (i.e., non-directory) files in the directory and place your answer on the answer sheet. Also on the answer sheet, l
ist the files which were directories.

To learn more about the "ls" command (or any UNIX command) use the "man" (short for "manual") command, as in

% man ls

Notice that "man" uses more to display the file to the screen. Use 'q' to quit! Man is the UNIX on-line help command. If you don't know what command to use for a task, like printing, you can use

% man -k print

('k' for keyword search) to get a list of UNIX commands that relate to the word "print."


Exercise 9:
Type in both of the commands above to explore the manual pages on "ls" and to obtain UNIX commands related to the word "print." Type in a command which would give you manual pages concerning cat. What command did you type in? Place your answer on the answer sheet.

Exercise 10:
To make a backup copy of the file cla2a.cc, type in the following command in the xterm window.

% cp cla2a.cc cla2a.bak
Now type in a command to list the files in your directory. What command did you type in to list the files in your directory? Place your answer on the answer sheet.

Now there are two files (named cla2a.cc and cla2a.bak) that contain exactly the same information.

 


Exercise 11:
Remove (delete) the cla2a.bak file using

% rm cla2a.bak

If you want to keep it, you can copy it again. Be careful when you delete files. Once they are deleted, you can not get them back. There is nothing to turn in as a result of this exercise.


Exercise 12:
To organize your account, we created directories OLA (stands for Open Lab Assignments) and CLA (for Closed Lab Assignments) during customization to hold your C++ open lab files and closed lab files. Copy a file into the CLA directory by typing

% cp cla2a.cc CLA

Change your working directory to CLA by typing

% cd CLA

Type in a command to display your current working directory (we did this in a previous exercise). Write the UNIX command which you used to display your current working directory on the answer sheet.  List the files that are in your current directory on the answer sheet.

To change back to your original (parent, home) directory type
% cd ..       or       % cd

Dot-dot ("..") is a special name for the parent directory while "cd" by itself always returns you to your login (home) directory from wherever you are. Type one of the "cd" commands shown above in the xterm window now.

Exercise 13:
You can create your own directories. To make a directory, say mystuff, type the following command in the xterm window.

% mkdir mystuff

To make mystuff your current working directory, type

% cd mystuff

in the xterm window NOW. List the files in the mystuff directory. On the answer sheet tell how many (regular) files were in the mystuff directory.

Now change back to the parent directory. (Type the "cd" command in the xterm window now.) Finally change to the CLA directory.

Important Note:
All of our future work in the Closed Labs should be placed in this directory.



The next required section is The "NEdit" Editor.


Optional Section: The "vi" Editor

Note: this section is optional reading. Read it only if you are interested in another editor besides "NEdit". If you are pressed for time, you should certainly skip to the next section, The "NEdit" Editor.

There are no exercises due from this optional section.


Read the following. Do not type in any commands until you start the next exercise!

In the computer world, an editor is a program that facilitates the creation and modification (editing) of a text file. For us the text file will usually be a C++ source file (i.e. a file of instructions to the computer written in the syntax of the C++ language). To create a new file, say lab.cc using vi (visual editor), you would type

% vi lab.cc

and press enter. Assuming lab.cc does not already exist, you would see a clean screen with a line of '~' on the left. If you typed this and your screen didn't look like this, you would type Shift-ZZ (hold down the Shift key and press 'z' twice) to exit vi and set the terminal type to an appropriate value using

% set term = vt100

or another appropriate type in place of the "vt100". Then you would restart vi using

% vi lab.cc


Suppose we wish to create a file, cla2b, with the vi editor. We would enter

% vi cla2b.cc

Before you type this command in the xterm window, drag the top or bottom border of the xterm window so it is as large as it will extend vertically.

Optional Exercise:
Type in this command in the xterm window.

You should see a clear screen except for a column of tilde (~) characters, a cursor, and perhaps a brief message on the last line. If you do not, ask for help from your lab assistant.


Do not start typing until you read this entire section.

The vi editor has three modes: the command mode, the insert mode and the last line mode. The vi editor always begins in the command mode. The command mode is used for moving the cursor, deleting text, moving text, and other functions; the insert mode is used for entering and changing text; the last line mode is used to type in vi commands to allow one to go to a particular line, to cause indentation, etc.

As mentioned above, vi always begins in command mode. When in command mode, vi is controlled by one or two letter commands. You can not use the arrow keys to move around the screen nor can you just start typing and have what you type appear in the document.

How do you get into insert mode? In vi, when you want to insert (add) something, you type one of the following one letter commands

Once in insert mode (you have typed in one of the commands above), what you type can and will be held against you (i.e. it is inserted into the file). While typing you can use the backspace key to erase previously typed characters. Obviously, once you are in insert mode the one letter commands to vi like 'i' or 'a', do not work. To change back to command mode, you must press the ESC key to exit insert mode.

Optional Exercise:
Enter insert mode by pressing the i key (you do not need to press ENTER) and then input the following three lines of text:

It is time for all
good men to come to
the aid of their planet.

We are done inserting text, so exit insert mode by pressing the ESC key. Do these steps NOW in the xterm window before proceeding.

Because beginners tend to forget to leave the insert mode before they type another vi command, commands often end up being inserted into their text.

Read the following before attempting the next exercise.

How do you delete selected text? When in command mode, the character on which the cursor is sitting can be deleted by pressing 'x' while 'X' deletes the character to the left of the cursor, if there is one. To delete a whole line press 'd' twice, i.e. "dd". If you press a number before the "dd", say 5, it will delete 5 lines starting from the cursor. You can use this technique to move a block of lines from one place in the file to another. Suppose you want to move 15 lines. Put the cursor on the first line, press "15dd", then move the cursor to where you want the deleted lines placed. Press 'p' (for paste) to put them below the cursor or 'P' to paste them above the cursor. Of course if you delete something else in the interim you will lose the 15 lines from the buffer and can not restore them.

How do you move the cursor? Make sure you are in command mode (press ESC if in doubt). There are two simple ways to move down one line: Press the ENTER key or a 'j'. There are two simple ways to move up one line: press the minus key '-' or 'k'. There are two simple ways to move right one character (position): press the space bar key or 'l'. The letter 'h' moves you left one position. You can move any number of lines or characters by typing a number followed by the key for the direction: "20j" moves down 20 lines; "60<space bar>" moves across 60 characters on the current line.


Optional Exercise:
We will continue to work on the three lines of text that we typed in above. We notice that we have made a mistake and we want the text to read "Now is the time" instead of "It is the time". We wish to move our cursor to the I of It. If necessary, read the above paragraph again to determine how to move the cursor to the I. Now delete the word It by pressing the x key twice. Next, press i to return to insert mode. Type the word Now, add a space, and then press ESC to return to the command mode. We also want to insert the word the before the word time, so position the cursor at the t in time. Now, press i (for insert mode) and type the, add a space, and press ESC. The corrections are done.

When in command mode, to move a screen at a time use CTRL-f (for forward) and CTRL-b (for backward). To see what line you are on use CTRL-g (look at bottom left of screen). To search forward for a string press '/' followed by the string and a return. To search backward press '?' followed by the string. To go to a specific line press ':' (this command always gets you into last line mode). Now follow by typing in the line number (and return), e.g. ":0" takes you to the top of the file while :50 places the cursor on line 50 of the file.

If you want to save changes you have made without exiting, to be prepared in case of a power failure use ":w" ('w' for write). To use any UNIX command without leaving vi type ":!<command>" for example ":!ls" to see a list of files on the current directory. To exit vi without saving changes made to the file press ":q!". Usually you will exit and save the changes with ":wq". If it appears on the screen you are in insert mode. Press ESC first.


Optional Exercise:
Exit vi now by typing :wq. There is nothing to turn in as a result of these exercises.

Optional Exercise:
A sample C++ source file cla2c.cc (that contains errors) has been prepared for you to copy and edit. Copy it to your account with
        % cp  $CLA/cla2c.cc  .       (Note: the dot (.) is required)

and edit with


        % vi cla2c.cc

Comments in a C++ program appear after two slashes (//) or between a slash-asterisk and asterisk-slash pair (/*   */). The comments in this program describe what should be corrected to make this program work. Read the comments in cla2c.cc and correct each line with an error on it. After you are finished with the corrections, save it. Use the vi commands described above to accomplish this.



The "NEdit" Editor


Read the following. Do not type in any commands until you start the next exercise!

In the computer world, an editor is a program that facilitates the creation and modification (editing) of a text file. For us the text file will usually be a C++ source file (i.e. a file of instructions to the computer written in the syntax of the C++ language). To create a new file, say lab.cc using NEdit, you would type

% nedit lab.cc &

and press enter. (Note that the UNIX command to invoke the NEdit editor is all lower-case letters.)


Exercise 14:
Suppose we wish to create a file, cla2b, with the NEdit editor. What should we type? Place your answer on the answer sheet (don't actually enter this on frank yet)

Before you type this command in the xterm window, drag the top or bottom border of the xterm window so it is as large as it will extend vertically.

Now type in the command in the xterm window.

A new window, resembling a Microsoft WordPad window, should now open. If it does not, ask for help from your lab assistant.


Take a brief look at this page on using NEdit. If you are familiar with Microsoft's WordPad or Word software, you probably can skip the page entirely and press on to the exercises below.

Exercise 15:
Insert the following three lines of text:

It is time for all
good men to come to
the aid of their planet.


Exercise 16:
We will continue to work on the three lines of text that we typed in above. We notice that we have made a mistake and we want the text to read "Now is the time" instead of "It is the time". Using the mouse, highlight the two letters of the word "It". Next type, "Now". We also want to insert the word the before the word time, so position the cursor at the t in time. Type the and a space. The corrections are done.

Exercise 17:
Exit NEdit. There is nothing to turn in for Exercise 17.

If you are interested in learning more about using NEdit, look over the NEdit Help menu. The tutorial at http://unix.cms.gre.ac.uk/software/editors/nedit.html might also be useful.



Exercise 18:
A sample C++ source file cla2c.cc (that contains errors) has been prepared for you to copy and edit. Copy it to your account with
        % cp  $CLA/cla2c.cc  .       (Note: the dot (.) is required)

and edit with


        % nedit cla2c.cc &

Comments in a C++ program appear after two slashes (//) or between a slash-asterisk and asterisk-slash pair ( /*  */). The comments in this program describe what should be corrected to make this program work. Read the comments in cla2c.cc and correct each line with an error on it. After you are finished with the corrections, save it. Use what you discovered about using NEdit to accomplish this.



Compiling and Capturing a Terminal Session
Source code sitting in a file does nothing. Once it is converted into machine code, it can be executed and results can be generated. The conversion is a multi-step process. First, the high-level language (C++) source code is converted into assembly language code that is then converted into machine code that is then linked with additional machine code from one or more libraries to produce an executable file. In UNIX this process is accomplished with one command, the compiler command. The compiler used on frank is the C++ compiler called aCC.


Exercise 19:
Compile the cla2c.cc program you edited above by typing:

% aCC  cla2c.cc

or

% aCC  cla2c.cc   -o  cla2c

In the first version, the executable file is called, by default, a.out while in the second version it is called cla2c (because of the -o cla2c; o for output). Hopefully, you will not receive any errors at this point if you were careful on the last exercise. However, if you do receive errors, you must edit the source program to remove the errors before you can go on the next exercise. To edit the source program, you must use NEdit again.

Exercise 20:
"Run" or "execute" the program by typing the name of the executable:

% a.out

or (only one of these will work depending on the compile command from Exercise 19)

% cla2c

The program should cause the statement "Enter the first test score: " to appear on the screen. The program now "waits" for you to enter the first test score. Type in the following three test scores after each score is requested:

            90
            80
            65
	
and the program will then display the average of the test scores.

If you must edit, compile, and run repeatedly, you can avoid some typing by taking advantage of a shorthand notation. Typing "!n" at the UNIX prompt will reexecute the most recent command starting with an "n" like "nedit". Entering "!a" would redo the most recent command starting with "a" -- probably aCC, but beware, maybe a.out, depending on which was most recent. You can enter additional characters after the exclamation mark to retrieve the most recent command you entered that started with those letters; for example, you could enter "!aC" or "!aCC" if you wanted to be sure to retrieve your most recently issued aCC command. Two exclamations (!!) reexecutes the last command.

Once our program works, we will need to get a printout of the changes, the compilation, and the results. That is, we need to capture a terminal session in a file so we can print it. In UNIX this is done with a program called "script". You start script by typing "script" followed by a file name for saving the session. Warning: Do not use the name of your source file! Once everything is in the log (script) file you want, type exit to close it.

Usually when we turn in a program we will want a source listing, perhaps with line numbers, a compilation (without errors), and a run showing inputs and outputs.


Exercise 21:
Create a log file for the program cla2c.cc as follows:

% script  ex21.log

% pr  -n4  -t  -e4  cla2c.cc

% aCC  cla2c.cc  -o  cla2c

% cla2c

% exit

Print the log file by typing

% lph  ex21.log

Turn it into your lab instructor with the answer sheet and the first printout.




Congratulations! You have finished Lab 2b.