Lab 2v -- Using UNIX and the vi Editor

Objectives: 

Learn how to manipulate files using UNIX commands.
Learn how to use UNIX directories.
Learn how to edit a C++ program.
Learn how to compile a C++ program.
Learn how to execute a C++ program.
Learn how to print files.

Click Here to CREATE ANSWER SHEET for LAB 2v

Sections:

Introduction
In the early days of computing, all programmers programmed the computer using machine language because that is the only language that the computer really understands. However with the advent of compilers, programmers today typically use high level languages, that is, languages very close to the written word. Examples of high level languages include C++, C, FORTRAN, Java, and Python. Today programmers may use C++, for example, to provide instructions to the computer instead of using machine language. Because the only language that a computer understands is machine language, we must have some type of translator that 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 executable code (the machine language version of the 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."

As you work through this lab, you will be asked to do several exercises (see sections in red). 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 in the top right-hand area to create an answer sheet window.

Logging on to ranger
The computer system you will use for CSCI 1170 & CSCI 2170 is named ranger. (Actually, ranger is an umbrella name for several actual machines, such as ranger0 or ranger2. Because it doesn't matter which particular ranger machine you are using, we'll just say ranger.) Ranger runs the UNIX operating system, an extremely powerful and popular system. There are different "dialects" of UNIX, such as Mac OS X or HP-UX. The UNIX dialect running on ranger is called Linux.


Exercise 1: LOG ON AND GET A TERMINAL WINDOW

Use your course account information to access ranger. For Login username enter your course account's C-number (that is, the 8 character login username you were assigned; for example, c0155913). For Password, enter your course account's password; for example 74ab2w45. Your password will not be displayed so be careful in your typing. If you have trouble logging in ask a lab assistant for help.



GETTING A "better" TERMINAL WINDOW: Once you have an active UNIX login, you will likely want to open up a "better" Terminal window. It is "better" in the sense it is clearer to read and easier to change the font size. (For reference: this "better" terminal window comes from running an application called sakura.) Enter the following command
          $ terminal &


The UNIX Operating System
The UNIX operating system was developed by Ken Thompson and Dennis Ritchie of AT&T Bell Labs in the early 1970's. UNIX (also often written "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:
(Type your answer on the answer sheet. If you have not already done so, click on the link in the top right-hand area to create an answer sheet window.) What is the name of the operating system we are using in this course? (Don't get confused and give the dialect name.)

TIP: To make the answer sheet window active, click on Exercise 2 link 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 a filing cabinet 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 /nfshome/cs2170/public_html/public. The actual name of the file (we call it the basename) goes at the right end separated from the directory name that contains it by a "/".


USING THE TERMINAL WINDOW: Much of UNIX is "command driven"; that's a fancy way of saying that to get most things done, you type out command instructions inside a Terminal window instead of clicking on icons. UNIX is case-sensitive, that is, it distinguishes between upper and lower case letters. It is important to type the commands exactly as indicated. Failing to put in a space where required is an error; however when a space is required, the amount of space (i.e., the number of blanks) is usually not critical.

The default Terminal window size is 32 rows long and 80 columns wide (historically the default was 24 x 80; we've upped it a bit); that is what we usually want it to be. You can resize a window by placing the mouse over the top or side window edge, then click the left mouse button, hold and drag. Although the Terminal 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
(Do NOT enter the $ 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.

Exercise 3:
Make the Terminal window active.

Check the current size of your window by entering the following UNIX command:
          $ stty size

Next copy the file cla2a.cpp from the CS department 2170 closed lab directory to your account area by typing the command below at the prompt in the Terminal window
          $ cp $CLA/cla2a.cpp cla2a.cpp

(Note: most UNIX commands, this is one of them, are silent when they work correctly. Thus you will not get any confirmation that you successfully copied the file---it will simply happen and you'll get another system prompt.)


In later sections you will learn how to create a file of high-level C++ source instructions with the "vi" editor and how to use the C++ compiler to create an executable file of machine instructions suitable for running on ranger. First, we explain a few simple commands. Read this section first, then do the exercises below.

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

$ cat cla2a.cpp
or
$ more cla2a.cpp
or
$ less cla2a.cpp

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.cpp on the screen. If it is longer than one screen (usually 32 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.cpp 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 Terminal window active and try out the three commands (cat, more, and less) above. Type each command in the Terminal 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 several laser printers. The default laser printer is cs360 and is located in KOM 360 towards the back of the room. The laser printer in KOM 350 is cs350 and the laser printer in KOM 351 (to the right of the entrance to KOM 360) is cs351.

To send a copy of the file cla2a.cpp to the cs351 laser printer, type

$ lph -Pcs351 cla2a.cpp

To send a copy of the file cla2a.cpp to the cs360 laser printer, type

$ lph -Pcs360 cla2a.cpp

or, because cs360 is the default printer, you can simply enter:

$ lph cla2a.cpp

and it will print to the same laser printer as the lengthier command above.

Usually each student is expected to obtain her/his own printout from the printer. xxxx

If you want the lines numbered, use
          $ pr -n -t -e4 cla2a.cpp > temp
          $ lph temp
          $ rm temp

"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 > symbol between "pr" and "temp" is the UNIX file redirection symbol. It makes the output from "pr" (which usually goes to the screen) go to the file "temp" instead. In turn, you use lph to print the file "temp" and then "rm" to remove/delete file "temp".


Exercise 5:
Make the Terminal window active; position it so you can see the UNIX command below and type the commands shown below. It causes the file, cla2a.cpp, 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.cpp > temp
          $ lph temp
          $ rm temp

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


Exercise 6:
We will not tell you to make the Terminal 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.cpp | pr -n -t -e4

$ pr -n -t -e4 cla2a.cpp

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:" link 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 that 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 that are 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 that 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.cpp, type in the following command in the Terminal window.

$ cp cla2a.cpp 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.cpp 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. Move the file cla2a.cpp into the CLA directory by typing

$ mv cla2a.cpp CLA

Change your working directory to CLA by typing

$ cd CLA

Type in a command to print (display) your current working directory (we did this in a previous exercise). Write the UNIX command that you used to display your current working directory on the answer sheet. (Hint: three letters long.)  Next, use ls to 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 Terminal window now.

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

$ mkdir mystuff

To make mystuff your current working directory, type

$ cd mystuff

in the Terminal 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 Terminal window now.)

Remove the mystuff directory by entering

$ rmdir mystuff

Finally change to the CLA directory.

Important Note:
Even if not stated explicitly in a closed lab writeup, all of our future CLosed Labs work must be placed in this CLA directory.





The "vi" Editor
There are no exercises due from this vi 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.cpp using vi (visual editor), you would type

$ vi lab.cpp

and press enter. Assuming lab.cpp does not already exist, you would see a clean screen with a line of '~' on the left.


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

$ vi cla2b.cpp

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

Exercise 14:
Type in this command in the Terminal window.   $ vi cla2b.cpp

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.

Exercise 15:
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 Terminal 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.


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". 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.


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

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

and edit with


        $ vi cla2c.cpp

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.cpp 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.



Compiling and Capturing a Terminal Session
Source code sitting in a file does nothing. Once it is converted into executable 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 a machine-like code called object code that is then linked with additional machine code from one or more libraries to produce a true executable file. In UNIX this process is accomplished with one command: the compiler command. The C++ compiler command we will use is c++. (Technically, the c++ command invokes the g++ compiler, but now we're getting into more detail than you need to know at this point.)


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

$ c++  cla2c.cpp

or

$ c++  cla2c.cpp   -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 scite again.

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

$ a.out

or

$ cla2c

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

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 "!s" at the UNIX prompt will reexecute the most recent command starting with an "s" like "scite". Entering "!c" would redo the most recent command starting with "c" -- probably c++, 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 "!c+" or "!c++" if you wanted to be sure to retrieve your most recently issued c++ 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.cpp as follows:

          $ script  lab2vex21.log
          $ pr  -n  -t  -e4  cla2c.cpp
          $ c++  cla2c.cpp  -o  cla2c
          $ cla2c
          $ exit

Submit the log file by typing

          $ handin lab2vlog lab2vex21.log
Exercise 22:

One last thing to do! From the PC you are working on, you must also submit the answer sheet (AnswerSheet2v.pdf) using the following directions:

  • Save your Lab2v Final Answer Sheet (click icon on very bottom of the answer sheet window)
  • Create the file AnswerSheet2v.pdf using your Browser's 'Save as PDF' feature
    (1. ctrl+p [Windows] or command+p [Mac]    2. Select 'Save as PDF')
  • Please use your C-number/password to log into the Gus Homework Repository System:
    https://www.cs.mtsu.edu/cgi-bin/gus/gus.py
  • Submit your AnswerSheet2v.pdf file to the Gus Homework Repository System
    1. Select the assignment from the dropdown menu: lab2vans
    2. Select the Submit radio button
    3. Click the button: Perform Action


    4. (On the next screen) Click the button: Choose File to locate your AnswerSheet2v.pdf
    5. Click the Upload button to upload the chosen file.

Congratulations! You have finished Lab 2v.



Once you are done, you will need to log off ranger. Enter   $ exit to exit the (sakura) terminal window. Depending on how you logged in to ranger you will need to enter $ exit one or more times to get completely logged off the system.