Table of Contents

Saad Malik's Opus

Spring 2012

Unix/Linux Fundamentals

C/C++ Programming

Introduction

My name is Saad Malik. I am currently 18 years old, and am enrolled in CCC for my second semester.
Last semester I was chemical engineering, and I have switched majors to compsci due to it being challenging and interesting.
I currently tutor at the MLC, and am usually glad to help out anybody who has a problem that I can solve.

Part 1

Entries

Entry 1: January 26, 2012 - C/C++ Programming

Today, for C/C++ in-class we learned a good deal about pointers. Beforehand, from learncpp.com I had read about pointers and even messed around with them in visual studio express but they always manage to confuse me or trip me up somehow. We also did a little on binary, and if knowing binary well becomes a necessity I will have to google and read up on it.

Regarding pointers and whatnot, we made a .c file in class with two variables, with b pointing towards a. We would assign pointer b a value, and that value would then be assigned to a. It's almost like the point is a soft shortcut to whatever address it's pointing to. What threw me off was that we would then fstream the b value, and de-reference it, and then b would suddenly be equal to 12. I'm guessing repetition, and messing with the code, will help me understand it. For the most part, it all did make sense. Along with the binary, and signed and unsigned variables.

Overall, pointers and referencing addresses of variables makes sense to me. When it comes to a bunch of things with pointers and address references going on at once, I find it a little challenging to try to follow what exactly is happening. As for binary, I can understand enough to understand how signed and unsigned works.

Entry 2: February 1, 2012 - Unix/Linux Fundamentals

I am supposed to make a tree of the UNIX file system, with my home directory in it along with a couple other things.

                        root
                          |
                        home
                          |
                      smalik2
                      /  |   \
              archives  bin  src
                             /  \
                           unix  cprog
                             

Entry 3: February 9, 2012 - Unix/Linux Fundamentals

All of the things that we learned in the first two weeks for Linux has actually helped me understand more other things outside of class. Going through directories, moving files, copying files, and other commands we've learned so far I've been using.

Over the past couple weeks I've been modding and messing around with my phone, and since I try to primarily use Ubuntu, I end up using terminal a lot. When I run into a guide on a website and they just have lists of commands to type in terminal to make something happen, I actually know what they're talking about as opposed to just following directions. This level of understanding really helps when it comes to troubleshooting problems, and with not blindly following instructions just hoping that it will magically work.

Since Android phones are based on a Linux kernel, when it comes to navigating my phones contents through the terminal on the computer, I actually know how to do it. I can really appreciate how nicely my need to know this material has coincided with this class. I also appreciate how widely used Linux appears to be, although many people probably do not realize it.

Entry 4: February 12, 2012 - C/C++ Programming

This past Friday in Object Oriented Problem Solving, we were creating an algorithm to read a user entered number. The ultimate goal will be to read the number and convert it to base ten, but right now the objective is to simply read in the number, each digit separately (without the user actually entering each digit separately).

I attempted to do this using C, but kept on hitting various errors. Segmentation faults, syntax, logical errors, etc. The end result was that there was SOMETHING wrong with the line containing the modulus function, where it would take a mod of the number entered by powers of ten (basically knocking off and storing the last digit in the number), and the digit would not be stored in the Array.

I am not sure if this is a problem with the array (I am still not comfortable with C, I'm much more used to C++) or the mathematical functions being performed. I briefly talked to Professor Oppenheim about it after class, but unfortunately I was in a rush so could not check the code with him. We will look over it next time we have class hopefully.

We figured it out, the problem was that one of the variables that was being changed had not been passed by reference. Adding an & fixed this, and the program started running.

Entry 5: February 27, 2012 - UNIX/Linux Fundamentals

This is somewhat random, but I since I have been running Ubuntu 99% exclusively on my laptop now and it is Linux based, it is part of my everyday life pretty much. So much so that I recommend it over Windows to my friends. I was helping somebody (who is not taking UNIX) install it on their laptop, and then when they were trying to use it they had to ask me how to create just a text file - thanks to the UNIX class I could immediately just tell them 'just use terminal, and then nano [filename].txt'. I would have recommended vim, but they had tried it before and it didn't end well.

Additionally, I am contemplating attempting the Linux from Scratch project which is basically building a linux based OS from scratch – teaching you a ton about the whole thing and how it works in the process. Perhaps I will attempt this when I have more free time on my hands.

Keywords

cprog Keywords

LIST FOR C/C++ KEYWORDS

The following is a list of the major topics being covered in this course:

DONE: Standard I/O (STDIO, STDOUT, STDERR)
DONE: Header Files (Local and System), C Standard Library (Libc), Libraries
DONE: arithmetic (equations, operators)
DONE: logic and operators (and, or, not, xor)
DONE: Variables (types, ranges, sizes)
DONE: Scope (Block, Local, Global, File)
DONE: Pointers (address of, assignment, dereferencing)
DONE: Type Casting
DONE: Selection Structures (if, case/switch)
DONE: Repetition/Iteration Structures (for, while, do while)
DONE: Arrays (standard notation, pointer arithmetic, single-dimensional, multi-dimensional)
DONE: File Access (Read, Write, Append)
Structures (Declaration, Accessing Elements, Pointers to)
typedef, enum, union
DONE: Functions, Parameters (Pass by: Value, Address, Reference), Return Types, Recursion, Command-line arguments
DONE: Compiler, Preprocessor, Flags, Assembler, Linker, Multi-file programs (how to structure, how to compile)
DONE: I/O Streams (cin, cout, cerr, stream operators) [C++]
DONE: Namespaces [C++]
DONE: Type Casting Operators, Const-Volatility Specifiers (const, volatile) [C++]
DONE: Classes (Objects, Constructor, Destructor, Access Control, Public, Protected, Private, Friend, “this” pointer) [C++]
DONE: Inheritance (single, multiple Inheritance), Polymorphism/Virtual Functions, Abstract Base Class [C++]
DONE: Overloading (Functions, Operators) [C++]
Exception Handing (throw, try, catch) [C++]
DONE: Templates, STL (Standard Template Library) [C++]

1: Repetition/Iteration Structures

Definition

Repetition/Iteration Structures are basically the coding that is necessary if you want to repeat a process many times, or to count. If you wanted to input 500 values into an array, you'd have to use a repetitive structure (the alternative being typing 500 lines of code). Or let's say you want to run a process multiple times, but each time something is slightly different, you'd use a repetitive structure.

Demonstration

Demonstration of the chosen keyword.

If you wish to aid your definition with a code sample, you can do so by using a wiki code block, an example follows:

Using a for loop

 
//THIS PROGRAM WILL COUNT FROM 0-20
 
#include <stdio.h>
#include <stdlib.h>
 
 
int main()
{//START MAIN
 
        int count = 0;          //DECLARING AND INITIALIZING A VARIABLE FOR COUNTING
 
 
        for(count; count<=20; ++count)          //FOR LOOP TO COUNT FROM 0-20
        {
                printf("%u sheep.\n", count);   //FSTREAM # AND SHEEP
        }       //END FOR LOOP
 
        return (0);     //RETURN 0
}//END MAIN

Using a do while loop

#include <stdio.h>
 
int main()
{
 
        int count=0;
        do
        {
                printf("%u sheep.\n", count);
                ++count;
        }
        while(count<=20);
 
        return (0);
}

Using a while loop

#include <stdio.h>
 
int main()
{
        int count = 0;
 
        while(count<=20)
        {
                printf("%u sheep.\n", count);
                ++count;
        }
 
        return 0;
}

The outputs of all of these programs lead to the SAME THING, so I'm only putting it once.

lab46:~/src/cprog/MessingAround$ nano RepetitiveDoWhile.c
lab46:~/src/cprog/MessingAround$ gcc -o RepetitiveDoWhile RepetitiveDoWhile.c
lab46:~/src/cprog/MessingAround$ ./RepetitiveDoWhile
0 sheep.
1 sheep.
2 sheep.
3 sheep.
4 sheep.
5 sheep.
6 sheep.
7 sheep.
8 sheep.
9 sheep.
10 sheep.
11 sheep.
12 sheep.
13 sheep.
14 sheep.
15 sheep.
16 sheep.
17 sheep.
18 sheep.
19 sheep.
20 sheep.

2: Variables (types, ranges, sizes)

Definition

Variables are structures that can hold types of data that can be manipulated.

Demonstration

To define a variable you have to make a statement in the code.

[type][identifier] = [value];

The type is the type of variable - Char short int int long int long long int float double long double

All of these variables can also be signed or unsigned (whether or not half of the memory allocated to each variable will be used for negative values, or further positive values.)

The sizes and ranges of these variables can differ, as shown by the output of a program (Project 0) that prints it all.

An unsigned char is 1 bytes
The range of an unsigned char is 0 to 255
An unsigned char can store 255 unique values

An unsigned short int is 2 bytes
The range of an unsigned short int is 0 to 65535
An unsigned short int can store 65535 unique values

An unsigned int is 4 bytes
The range of an unsigned int is 0 to 4294967295
An unsigned int can store 4294967295 unique values

An unsigned long int is 8 bytes
The range of an unsigned long int is 0 to 18446744073709551615
An unsigned long int can store 18446744073709551615 unique values

An unsigned long long int is 8 bytes
The range of an unsigned long long int is 0 to 18446744073709551615
An unsigned long long int can store 18446744073709551615 unique values

A signed char is 1 bytes
The range of a signed char is -128 to 127
A signed char can store 256 unique values

A signed short int is 2 bytes
The range of a signed short int is -32768 to 32767
A signed short int can store 65536 unique values

A signed int is 4 bytes
The range of a signed int is -2147483648 to 2147483647
A signed int can store 4294967296 unique values

A signed long int is 8 bytes
The range of a signed long int is -9223372036854775807 to 9223372036854775806
A signed long can store 18446744073709551615 unique values

A signed long long int is 8 bytes
The range of a signed long long int is -9223372036854775807 to 9223372036854775806
A signed long long can store 18446744073709551615 unique values

3: Pointers (address of, assignment, dereferencing)

Definition

A pointer is basically a variable, that contains the address/location of another variable.

Demonstration

To assign a pointer, you denote it with;

*[variable declaration];

The asterisk denotes pointer. And you can have two, or even three to designate a double or triple pointer.

To dereference a pointer, you use an asterisk again.

I think of a pointer as 'going higher' and then dereferencing as 'going back down'.

So if you have a variable called pointer, which is a single pointer, that variable is one level up. To put something in it, you have to bring it down a level.

The plain variable is just the address of where the actual value is being stored.

So, given the following code and output, you can see that the normal variable you can just printf it normally. But when it comes to storing and printing to the pointer, you need to dereference it to take the pointer back down to the storage unit that it specifies.

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
        int *pointer, variable;
 
        *pointer = 9001;        //need  to dereference to store it
 
        variable = 1111;        //not a pointer so it's fine
 
        printf("\nVariable is %d\n", variable);
 
        printf("\nPointer is %d\n", pointer);   
//Since it is not dereferenced, it will print an address (garbage).
 
 
        printf("\n*Pointer (dereferenced) is %d\n", *pointer);
//Since it has been dereferenced, it will properly display the value.
 
        return (0);
 
}
lab46:~/src/cprog/MessingAround$ ./pointers

Variable is 1111

Pointer is -1584842064

*Pointer (dereferenced) is 9001

4: File Access (Read, Write, Append)

Definition

File Access is basically the term for when you read from, write to, or append a file. Basically the program can open a .txt file or a .data file or whatever, and then either read information from it (such as a list of numbers or something) or write information to it (such as results of some calculation), or append (just add onto what is already in the file).

Demonstration

The following program will take an input file, and then add 1 to every number in the input file, and write those results into a different file.

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
 
        int number;
 
        FILE *in, *out;
//Defines two file variable pointers called in and out.
 
        in = fopen("numbers.txt", "r");
//Opening the input file (known as numbers.txt). The r denotes reading.
 
        out = fopen("output.txt", "w");
//Opening the output file (naming it output.txt). The w denotes writing.
 
        if(in == NULL)
        {
                printf("Error, need an input file numbers.txt");
                exit(1);
        }
//This block checks to make sure that a file gets thrown into the in variable
 
        fscanf(in, "%hhd", &number);
//That in at the beginning of the statement indicates that input file
 
        while(number != 17)
        {
                int newnumber=0;
 
                newnumber = number+1;
 
                fprintf(out, "%hhd\n", newnumber);
 
                fscanf(in, "%hhd", &number);
        }
 
        return (0);
}

5: Standard I/O (STDIO, STDOUT, STDERR)

Definition

Standard I/O is the Default Input, Output, and Error Output. Normally these are the keyboard, and the monitor.

Demonstration

When we use scanf(“%d”, &number); it inputs an integer value from the standard input, which is the keyboard.

If we use fscanf(in, “%d”, &number); it inputs an integer value from whatever is defined as 'in' (like a text file), so we changed the input.

When we use printf(“Hello”); it prints Hello to the standard output, which is the monitor.

If we use fprintf(out, “Hello”); it prints Hello to whatever output is defined by 'out' (for instance, a text file). So we changed the output.

The errors are outputted to the STDOUT typically, and we haven't covered redirecting them in C yet.

6. Arrays (standard notation, pointer arithmetic, single-dimensional, multi-dimensional)

Definition

An array is basically a bunch of different data values (of the same type) that fall under the same identifier. The identifier is basically a gigantic data block, that has been sliced into smaller blocks, each of which holds the different data values.

Demonstration

This program will use two 1-d arrays, and 1 2-d array. It will store 0-4 in the 1-d arrays, and in the 2-d array it shows examples of counting by increasing numbers in sets of 5. So, in the first one it counts forward by zeros. In the second set it counts forward by 1s. Third by 2s. Etc.

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
        int Array[5];
 //This defines an array that can hold 5 values
 
 
        int D_Array[5][5];
//This defines a 2-d array, so it holds 5 values, each of which have five values underneath (like a table of sorts).
 
        int *P_Array;
        P_Array = (int*)malloc(sizeof(int)*5);
//This defines a 5 slot array, but using pointer style arithmetic.
 
        int count = 0;
        int count2 = 0;
        int number = 0;
 
        for(count = 0; count < 5; ++count)
        {
                int number2 = 0;
 
                Array[count] = number;
 
                *(P_Array + count) = number;
 
                for(count2 = 0; count2 < 5; ++count2)
                {
 
                        D_Array[count][count2] = number*number2;
                        ++number2;
                }
                ++number;
        }
 
 
        printf("\nThe values in Array\n");
 
        for(count = 0; count < 5; ++count)
        {
                printf("%d ", Array[count]);
        }
 
        printf("\nThe values in P_Array\n");
 
        for(count = 0; count < 5; ++count)
        {
                printf("%d ", *(P_Array + count));
        }
 
        printf("\nThe values in D_Array\n");
 
        for(count = 0; count <5; ++count)
        {
                for(count2 = 0; count2 < 5; ++count2)
                {
                        printf("%d ", D_Array[count][count2]);
                }
 
                printf("\n");
        }
 
        printf("\n");
 
        return (0);
}
lab46:~/src/cprog/MessingAround$ vim arrays.c
lab46:~/src/cprog/MessingAround$ gcc -o arrays arrays.c
lab46:~/src/cprog/MessingAround$ ./arrays

The values in Array
0 1 2 3 4
The values in P_Array
0 1 2 3 4
The values in D_Array
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 4 8 12 16

lab46:~/src/cprog/MessingAround$

7: Selection Structures (if, case/switch)

Definition

Selection structures are basically ways of checking. They allow you to check things within the program, and decide what to do based on the check. With more complex logic operating behind the checks, the more interactive and 'intelligent' the program becomes.

Demonstration
IF statements

The following program will take a number, and using if blocks determine IF the number is even or odd.

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
        int number = 0;
        int x;
 
        printf("Enter a number: ");
 
        scanf("%d", &number);
 
        x = number%2;
 
        if(x == 0)
        {
                printf("\n%d is even\n", number);
        }
        else
        {
                printf("\n%d is odd\n", number);
        }
        return (0);
}
lab46:~/src/cprog/MessingAround$ vim Selection.c
lab46:~/src/cprog/MessingAround$ gcc -o Selection Selection.c
lab46:~/src/cprog/MessingAround$ ./Selection
Enter a number: 2

2 is even
lab46:~/src/cprog/MessingAround$ ./Selection
Enter a number: 3

3 is odd
Switch Case
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
        int number;
 
        printf("Enter a number: ");
        scanf("%d", &number);
 
        int x;
        x = number%2;
 
        switch (x)
        {
        case 0:
                printf("The number is even");
                break;
        case 1:
                printf("The number is odd");
                break;
        default:
                printf("The number is neither even nor odd");
                break;
        }
 
        printf("\n");
 
        return (0);
}
lab46:~/src/cprog/MessingAround$ gcc -o SwitchCase SwitchCase.c
lab46:~/src/cprog/MessingAround$ ./SwitchCase
Enter a number: 6
The number is even
lab46:~/src/cprog/MessingAround$ ./SwitchCase
Enter a number: 9
The number is odd
lab46:~/src/cprog/MessingAround$ 

8: Logic and Operators

Definition

Logic and operators allow you to make a program much more interactive and capable.

Demonstration

And can be used to ensure two values are both true.

Or can be used to ensure at least one value is true.

Not returns the opposite of a value , from true to false and vice versa.

XOR will return true if JUST ONE value is true.

cprog Objective

cprog Objective

Use pointers and variables to discover the indirect properties of data storage

Definition

Basically this means that we will figure out, and be able to utilize, pointers and variables for the sake of different methods and 'tricks' behind data storage.

Method

Probably paying attention when Matt Haas is talking about those things would be a great start. Defining these as keywords would help as well.

Measurement

I defined them both as keywords, and it did help me understand a lot more. I already knew variables for the most part, but all the stuff to do with pointers I was sketchy on and now I feel much more confident about it.

Analysis

Reflect upon your results of the measurement to ascertain your achievement of the particular course objective.

I think I did great. Of course there is room for improvement, but I am no longer clueless. Not really, being forced to define them and give working examples of them (for me) works very well. Perhaps the course objective would make a little more sense if it went into a little bit more detail in what it means by 'indirect properties data storage'.

unix Keywords

THIS IS THE LIST –

The following is a list of the major topics being covered in this course:

DONE: Local host
DONE: Remote host
DONE: Home directory
DONE: Current working directory
DONE: Types of files (regular, directory, special)
DONE: File manipulation
DONE: Text Processing
DONE: The VI editor
DONE: The UNIX Shell
DONE: Environment variable
DONE: $PATH
DONE: wildcards
DONE: tab completion
DONE: Job Control
DONE: The UNIX Programming Environment
DONE: Compiler, Assembler, Linker, Loader
DONE: Source Code, Object Code, Binary Code, Library
DONE: Pattern Matching
DONE: Regular Expressions
DONE: Filtering
DONE: Shell Scripting
DONE: networking, UNIX Networking Tools
DONE: Security
DONE: X Window System

1: File manipulation

Definition

The ability to control files, such as moving them, removing them, copying them, organizing them.

Demonstration

In this command line sample, you can see me moving files between directories, or for the sake of renaming, copying files, making directories, and removing a file. All of this is file manipulation.

lab46:~$ cd src/cprog
lab46:~/src/cprog$ ls
Feb14    Feb2.c    JAN26_printf_examples.c  JAN31_pointers3.c
Feb14.c  Feb7.c    JAN26_printf_pointers.c  MessingAround
Feb16    Feb7x0.c  JAN31_pointers.c         Projects
Feb16.c  Feb9.c    JAN31_pointers2.c        out.txt
lab46:~/src/cprog$ cd MessingAround
lab46:~/src/cprog/MessingAround$ ls
Algorithm.c   RepetitiveDoWhile.c  files    numbers.txt  pointers
Repetitive.c  RepetitiveWhile.c    files.c  output.txt   pointers.c
lab46:~/src/cprog/MessingAround$ rm files
rm: remove regular file `files'? y
lab46:~/src/cprog/MessingAround$ mv pointers lookitrenamed
lab46:~/src/cprog/MessingAround$ cp lookitrenamed lookanothercopy!!
cp lookitrenamed lookanothercopymv pointers lookitrenamed
cp: target `lookitrenamed' is not a directory
lab46:~/src/cprog/MessingAround$ cp lookitrenamed lookanothercopy
lab46:~/src/cprog/MessingAround$ mkdir lookanewdirectory
lab46:~/src/cprog/MessingAround$ mv lookitrenamed lookanewdirectory
lab46:~/src/cprog/MessingAround$ ls
Algorithm.c          RepetitiveWhile.c  lookanothercopy  pointers.c
Repetitive.c         files.c            numbers.txt
RepetitiveDoWhile.c  lookanewdirectory  output.txt
lab46:~/src/cprog/MessingAround$ cd lookanewdirectory
lab46:~/src/cprog/MessingAround/lookanewdirectory$ ls
lookitrenamed
lab46:~/src/cprog/MessingAround/lookanewdirectory$ 

2: Home directory

Definition

The home directory is your default directory. Whenever you open up a cmd prompt this is the file location that you start at.

Demonstration

So here, you can see that right when I log into lab46 my home directory is denoted by ~$. Using the pwd command (to show the full file structure) reveals that my home directory is at /home/smalik2

saad@saad-Satellite-P775:~$ ssh smalik2@lab46.corning-cc.edu
smalik2@lab46.corning-cc.edu's password: 
 __         _     _ _   __   . . . . . . . . . . . . . . . . . . . . . . . . .
|  |   __ _| |__ / | |_/ /   . Basic System Usage:  Type 'usage' at prompt   .
|  |__/ _` | '_ \\_  _/ _ \  . Events and News:     Type 'news' at prompt    .
|_____\__,_|_.__/  |_|\___/  . Broken E-mail?       Type 'fixmail' at prompt .
---------------------------  . Check Lab46 Mail:    Type 'alpine' at prompt  .
c o r n i n g - c c . e d u  . . . . . . . . . . . . . . . . . . . . . . . . .

 Lab46 is the Computer & Information Science Department's Student Development
 Server for Computer-related coursework, projects, and exploration.  For more
 information, please check out:
  .. .  .    .        .                .                .        .    .  . ..
 .  Lab46 Web Page:       http://lab46.corning-cc.edu/                       .
 .  Lab46 Help Form:      http://lab46.corning-cc.edu/help_request           .
 .  Help E-mail:          haas@corning-cc.edu or wedge@lab46.corning-cc.edu  .
  .. .  .    .        .                .                .        .    .  . ..
      _        
  .-./*)       
_/___/   `.    
  U U      'You can delete files with the 'rm' command.'
No mail.
Last login: Fri Feb 17 19:09:50 2012 from cpe-69-205-204-88.stny.res.rr.com
lab46:~$ pwd
/home/smalik2
lab46:~$ 

In this example, you can see me moving to a different directory using the cd command. The cd command with no argument takes you back to your home directory.

lab46:~$ pwd
/home/smalik2
lab46:~$ cd src/cprog/Projects
lab46:~/src/cprog/Projects$ pwd
/home/smalik2/src/cprog/Projects
lab46:~/src/cprog/Projects$ cd
lab46:~$ pwd
/home/smalik2
lab46:~$ 

3: Current working directory

Definition

The current working directory is the directory that you're in.

Demonstration

The current working directory is basically the directory that you are in. The cd command with no arguments will change your current working directory to your home directory.

The pwd command reveals the current working directory.

lab46:~$ pwd
/home/smalik2
lab46:~$ 

4: Types of files (regular, directory, special)

Definition

There are three types of files, regular files (such as .txt), directories (technically a file with other file locations in it), and special files (a directory is a type of special file, or C programs).

Demonstration

In the example we see that there are regular files, which are the .c files, directories, and then the special files (the compile C code).

lab46:~$ cd src/cprog
lab46:~/src/cprog$ ls
Feb14    Feb2.c    JAN26_printf_examples.c  JAN31_pointers3.c
Feb14.c  Feb7.c    JAN26_printf_pointers.c  MessingAround
Feb16    Feb7x0.c  JAN31_pointers.c         Projects
Feb16.c  Feb9.c    JAN31_pointers2.c        out.txt
lab46:~/src/cprog$ 

5: Local Host

Definition

The device that is running the session.

Demonstration

My laptop is running Ubuntu. The terminal on my laptop screen is an example of a local host, because my device (the laptop) is what the services are being ran on.

6: Remote Host

Definition

A remote host is a device that is running services remotely.

Demonstration

My laptop is connected to lab46.corning-cc.edu via ssh, which is an example of a remote host.

7. The VI editor

Definition

The VI editor is a text editor where in one mode you can always insert, and in another mode you enter commands. To toggle command mode you hit escape, and to enter insert mode you push i when in command mode.

Demonstration
lab46:~/src/cprog$ vim Hello.txt
lab46:~/src/cprog$ cat Hello.txt
I couldn't type until I hit I to enter insert mode.

Now, to exit VI editor (and save the work) I will hit the ESCAPE key to enter command mode, from there I will type :wq to quit and save my work.  If I didn't want to save, I would use :q!
lab46:~/src/cprog$ 

After typing vim Hello.txt, this appeared on my screen.

I couldn't type until I hit I to enter insert mode.

Now, to exit VI editor (and save the work) I will hit the ESCAPE key to enter command mode, from there I will type :wq to quit and save my work.  If I didn't want to save, I would use :q!
~                                                                               
~     

8: Text Processing

Definition

Manipulating text

Demonstration of the chosen keyword.

You can print the contents of a file using the cat command. You can manipulate text using many things. The nano and vim text editors are really good for editing text based files.

Just nano filename.txt or vim to open the editor.

unix Objective

unix Objective

Familiarity with the structure of UNIX systems.

Definition

Basically this means that I will become much more familiar with how UNIX systems look like, like the file structure and whatnot.

Method

If I can tell if a system is based off the UNIX system based on the file structure.

Measurement

I think I can do this pretty well, as I can recognize that mobile phones (such as my android powered phone and my previous iPhone) are based off of UNIX because of their file structure. They have the files named var, usr, bin, and others.

Analysis

I think I did pretty well. Not particularly, unless if there is some other discrepancy that I am unaware of. I don't think so. If there was a quick description associated with the objective.

Experiments

Change base 8 to base 10

Question

My experiment is to create a program that will convert any 3 digit base 8 number to base 10, and vice versa.

Resources

http://www.unitconversion.org/numbers/base-10-to-base-8-conversion.html – To double check program once I begin testing it.

http://science.widener.edu/~schultz/mathhelp2.html – This will help me develop the logic to run behind the program.

Hypothesis

I'm guessing that by the time I finish, I will have a program that can accomplish the goal.

Experiment

See if the program will output correct data given an input (checked against the converter I found online).

Data

Program so far:

  GNU nano 2.2.4                                                                                                                        File: Algorithm.c                                                                                                                                                                                                                                            Modified  
 
=#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
int main()
{
 
        int number = 0;
        int array[3];
        int count = 0;
        int random = 0;
        int result = 0;
        int choice;
 
        printf("This program will convert any three digit number to a different base\n");
 
        printf("For base 8 to base 10, press 1\n");
        printf("For base 10 to base 8, press 2\n");
 
        scanf("%d", &choice);
 
        if(choice == 1)
        {
 
                printf("\nEnter a base 8, three digit number :");
                scanf("%d", &number);
                printf("\nThat number will now be converted to base 10\n");
                printf("\nThe number you input was: %d\n", number);
 
                for(count = 0; count <=2; ++count)
                {
                        random = number%10;
 
                        array[count] = random;
 
                        number = (number-random)/10;
                }
 
                for(count = 2; count >=0; --count)
                {
                        result = result + array[count]*(pow(8, count));
                }
 
                printf("\nThat number in base 10 is %d\n", result);
        }
 
        if(choice == 2)
        {
 
                printf("Enter a base 10 number: ");
                scanf("%d", &number);
                printf("\nThat number will not be converted to base 8\n");
                printf("\nThe number you input was: %d\n", number);
 
                for(count = 0; count <=2; ++count)
                {
 
 
                        random = number%8;
 
                        array[count] = random;
 
                        number = (number-random)/8;
                }
 
                printf("\nThat number in base 8 is: ");
 
                for(count = 2; count >=0; --count)
                {
                        printf("%d", array[count]);
                }
 
                printf("\n");
        }
 
        return (0);
}

This code can successfully convert from base 8 to base 10.

When it comes to converting from base 10 to base 8 however, there is no check to take into account that the numbers 8 and 9 don't exist in base 8, (they have to carry over). This is something that will have to be incorporated. Perhaps as a second experiment it would be good to do that, with some more menu options and invalid input coding added in.

Analysis

My hypothesis was mostly correct. The program mostly works. It still needs some safety nets built into it, however.

Conclusions

I know the language better.

One major thing that I didn't realize was that when you input a number, you have to input it by reference (denoted by an &) if you wish to make changes to that number as the program progresses.

Directory navigation

Question

I know that I can change directory from one end of the file system tree to the other by stating my destination as the entire file tree starting from the root. Can I do it if I only do part of the entire file tree that I wish to get to?

Resources

No resources consulted.

Hypothesis

I don't think it will work, but if UNIX has some sort of measure in place then I wouldn't be surprised by that.

I don't think it will work because if you don't specify the entire file tree starting from the root, then UNIX wouldn't know for sure what you're talking about.

Experiment

I'm going to try to change from two different directories, first by using the file tree from the root, and then by using only part of it.

Data

lab46:/$ cd home/smalik2/src/cprog/Projects
lab46:~/src/cprog/Projects$ cd /
lab46:/$ cd src/cprog/Projects
-bash: cd: src/cprog/Projects: No such file or directory
lab46:/$ 

Analysis

My hypothesis was correct, and applicable.

Conclusions

If you want to change directories more then one level at a time, you have to start by specifying the file system from the root (or starting from your current location).

Change base 10 to base 8

Question

I am trying to figure out what is wrong with the code for experiment 1, where it will randomly return an incorrect value for a base 10 to base 8 conversion.

Resources

No other resources were consulted, other than the ones from Experiment 1.

Hypothesis

I think it's a problem with carrying over a digit, because going from base ten to base 8, base 8 requires more symbols to represent the same number as in base 10, so I may need an additional placeholder.

Experiment

Try to see if I can incorporate some logic to carry over a 1.

Data

New and improved code for Algorithm program
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
int main()
{
 
        int number = 0;
        int array[4];
        int count = 0;
        int random = 0;
        int result = 0;
        int choice;
 
        printf("This program will convert any three digit number to a different base\n");
 
        printf("For base 8 to base 10, press 1\n");
        printf("For base 10 to base 8, press 2\n");
 
        scanf("%d", &choice);
 
        if(choice == 1)
        {
 
                printf("\nEnter a base 8, three digit number :");
                scanf("%d", &number);
                printf("\nThat number will now be converted to base 10\n");
                printf("\nThe number you input was: %d\n", number);
 
                for(count = 0; count <=2; ++count)
                {
                        random = number%10;
 
                        array[count] = random;
 
                        number = (number-random)/10;
                }
 
                for(count = 2; count >=0; --count)
                {
                        result = result + array[count]*(pow(8, count));
                }
 
                printf("\nThat number in base 10 is %d\n", result);
        }
 
        if(choice == 2)
        {
 
                printf("Enter a base 10 number: ");
                scanf("%d", &number);
                printf("\nThat number will not be converted to base 8\n");
                printf("\nThe number you input was: %d\n", number);
 
                for(count = 0; count <=2; ++count)
                {
 
 
                        random = number%8;
 
                        array[count] = random;
 
                        number = (number-random)/8;
                }
 
                array[3] = number;
 
                printf("\nThat number in base 8 is: ");
 
                for(count = 3; count >=0; --count)
                {
                        printf("%d", array[count]);
                }
 
                printf("\n");
        }
 
        return (0);
}
Program running

The problem from experiment one was that with larger numbers, the program wouldn't work. It could convert 511 to 777, but fail to convert 777 to 1411. Now it does.

lab46:~/src/cprog/MessingAround$ ./Algorithm
This program will convert any three digit number to a different base
For base 8 to base 10, press 1
For base 10 to base 8, press 2
2
Enter a base 10 number: 777

That number will not be converted to base 8

The number you input was: 777

That number in base 8 is: 1411

Analysis

My hypothesis was correct.

It wasn't necessarily a need to carry over a one, as the number%8 always returned a value between 0 and 7 (inclusive). However, if the final number that I end with is a 1, then that means I need a 1 in the thousands place. Which was a very easy fix.

Conclusions

This experiment was very good at developing troubleshooting, and forcing me to think on a very logical level.

Part 2

Entries

Entry 5: March 11, 2012

For the UNIX course I am playing around with the IRC bot phenny.

It's pretty cool, but since I had a ton of trouble with scripting, the scripting for this case study is taking me awhile to take care of.

The idea behind bots is really cool though, just whenever you need something done based on some condition, you can get a bot to do it for you. Quite neat.

Entry 6: March 18, 2012

In C++ this past week we worked on Project 2 and more stuff on classes and whatnot in C++. This C++ material is something I've never been exposed to before, but it makes sense if you have a very very large program and want it to be even more organized. We also dealt with header files, which are useful as they make the code less cluttered.

Regarding Project 2, it's the first thing that I had to resort to using pencil and paper to get it all organized before coding it, which I know is a good habit. Hopefully I will stay on that same track.

Entry 7: March 30, 2012

This past week in C++ we did a lot of playing around with inheritance and all that good stuff.

We basically build classes and functions within the classes that would run logical operations and returning the boolean values.

At first it was like hitting a brick wall, I would bet because the syntax was unlike anything I have ever seen before. It does make sense why one would want to do this however… for a large scale team effort on something, it would provide a good means for organization. But when it comes to my own programming, I can't really see myself using it unless I was working on something very big and very segmented where it would be a good advantage.

It took awhile to understand it, but once I did the actual coding was fairly smooth sailing, I've managed to create classes and functions to perform and, or, not, nor, and nand operations.

Entry 8: April 17, 2012

In unix I did a bunch of pattern matching and regexp stuff.

At first it was kind of hard, but once I got the syntax down it was fairly easy.

I can see how it's useful, especially in word processing and stuff. It helps you manipulate information much more quickly. Which is never a bad thing.

Keywords

cprog Keywords

9. Type Casting

Definition

Type casting is basically telling the program to treat a certain entity (an int, char, whatever) using the rules of a different one.

Demonstration

So if we use…

int a = 3; int b = 5;

int c = a/b;

c is actually zero, because of integer division. But if we use this line instead….

int c; (float)c = a/b;

The (float) is a type cast to c, telling the program to treat c as a float, which would ensure that it stores a 0.6 instead of a 0.

10. I/O Streams (cin, cout, cerr, stream operators) [C++]

Definition

Needs #include <iostream>

cout produces output ~ printf cin provides input ~ scanf cerr is just the error output stream operators are things such as setf() and setw() which held you do different things with the stream.

Demonstration

int a=1 int b=2

printf(“a is %d, b is %d\n”, a, b); cout « “a is ” « a « “,b is ” « b « endl;

scanf(“%d”, %a); cin » a;

cerr « “Error, yo” « endl;

Stream operator in use: cout « setw(5) « a « “ sheep are sleeping.” « endl;

11. Header Files (Local and System), C Standard Library (Libc), Libraries

Definition

Header files are basically files that contain class and function 'prototypes'. It basically will let the program know that there is a class or function which is named something, and the types of parameters and return type it has. Local Header files are the ones that tend to be user made, or could get pulled in from another source I suppose. System header files are the ones that are in the system.

The C Standard Library has a bunch of the most common and useful C header files I would guess, such as stdio for input and output capabilities.

Libraries in C contain all of these functions and whatnot in them.

Demonstration

To call a system header

#include <stdio>

To call a local header

#include “nor.h”

12. Arithmetic (equations, operators)

Definition

Arithmetic is the way that we can manipulate data. Equations would set some value equal to something else, while operators can compare values.

Demonstration

To assign a value to a variable using an equation:

Density = 50*8/13;

To compare using an operator:

if (Density < 100)
{
    printf("Wow")
}

13. Scope (Block, Local, Global, File)

Definition

Scope is basically the region of the program in which a declared variable will exist. Block would mean the scope is in regards to the set of brackets you're in. Local would mean within a function. Global would mean within an entire file of code. File would (I assume) mean between files. Although how to do this I do not know.

Demonstration
if( x>3)
{
    int Q = 5;   // Q only exists within this if statement
}
 
int Sum1(int num1, int num2)   //these two integers are only defined within this function!
{
    return (num1 + num2)
}
 
int x;     //this variable will be defined throughout the entire file, regardless of functions and whatnot.
int main()
{
    x = 4
}

14. Functions, Parameters (Pass by: Value, Address, Reference), Return Types, Recursion, Command-line arguments

Definition

Functions are basically isolate segments of code that can do certain things based on Parameters that you pass them. It saves a lot of coding, for example, to have a function that you just send different values of length and width to calculate the area of 50 squares is much easier than actually writing the code to do 50 different areas.
Return Types are the variable type that the function will be returning- in the case of the area function, we would probably want to return a float value.
Recursion is basically when a function calls itself within itself, with some end terminating condition. We haven't covered it in class yet though.
Command-line arguments are when you pass parameters to the main function of the program.

Demonstration

There are some great examples of functions in Project 1 and Project 2. Everything is used except Recursion.

15. Overloading (Functions, Operators) [C++]

Definition

Overloading a function is to use the same function name for multiple functions, with the difference being the parameters passed to the function.

Demonstration

Let's say we want to write a program that will calculate areas. Rectangles, Squares, and Circles. We'll overload a function to do this.

int Area(int);    //for the square
float Area(float, float);   //for the rectangle
float Area(float);    //for the circle

These functions will actually work, and depending on the parameters that we send, it will either call the one meant for squares, rectangles, or circles!

16. Inheritance (single, multiple Inheritance), Polymorphism/Virtual Functions, Abstract Base Class [C++]

Definition

Inheritance is how classes can inherit the stuff from the public and protected part of their 'parent' class. Multiple Inheritance is when there are multiple layers going on.

Demonstration

To see an excellent example of inheritance, over multiple files, in my directory… /home/smalik2/src/cprog/c++

There is a multifile program using classes and inheritance and multiple inheritance.

cprog Objective

cprog Objective

break down and separate code into functions and illustrate the use of parameter passing

Definition

If you need to write a huge long program that does multiple things, that are similar to one another, this will be the capability to recognize the need for and be able to split the program apart into functions, so that code repetition is minimized and the code is more efficient.

Method

If I start doing what I said in the definition. Which I believe I already do fairly solidly. In Project2 we continuously printed arrays, so I actually just made a function that would print an array given the array name and the length of the array.

Measurement

I did a lot of this in Project 2.

Analysis

I just did it. There's always room for improvement, but it is not desperately needed. There's not really a way to enhance checking to see if you can do it. I think the objective is stated nicely.

unix Keywords

9. Tab Completion

Definition

Tab completion is being able to auto-complete typing a command by hitting tab.

Demonstration

If you have a program called thebiggestnumberis, and you want to execute it, you would type ./thebiggestnumberis

But using tabcompletion you can just type ./thebi [hit tab] and it will automatically fill it.

If there is another program in the directory that is called thebiggestloseris, then this won't work because there are possible combinations. you will have to type out even more of the program name before the tab completion will work.

10. Wildcards

Definition

The wildcard is the * in unix, and basically means (anything or whatever can do here).

Demonstration

lab46:~/src/unix/Labs$ ls la ls: cannot access la: No such file or directory lab46:~/src/unix/Labs$ ls la* lab0.txt lab1.txt lab2.txt lab3.txt lab4.txt lab5.txt lab6.txt lab46:~/src/unix/Labs$

See how the wildcard enabled the ls command to actually work.. and it gave all names that began with the la[insert anything here]. Cool.

11. Job Control

Definition

Job control is basically multitasking. It gives you the power to perform actions and run them in the background, leaving you free to do whatever else you want. It also allows you to kill these other processes.

Demonstration

We can display current running processes with ps

We can tell a command to run in the background by adding a & to the end of the command. Running fg #(process number) will bring that thing back to the foreground.

You can also use kill commands to kill the process, or using ctrl + C

12. The UNIX Shell

Definition

The UNIX shell is the way that the user uses the OS, called a Command Line Interpreter (CLI).

Demonstration

The shell is the command prompt. Whoa!

13. Environment variable

Definition

An Environment variable is basically a thing that stores some useful piece of information. An example would be how $HOME holds the users home directory.

Demonstration
lab46:~$ echo $PATH
/home/smalik2/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/games
lab46:~$

14. $PATH

Definition

The $PATH variable holds the locations of executable programs.

Demonstration
smalik2@lab46:~$ echo $PATH
/home/smalik2/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/games
smalik2@lab46:~$ ls /usr/games
adventure   caesar     gomoku   nethack          primes  snake        worms
arithmetic  canfield   hack     nethack-console  quiz    snscore      wtf
atc         cfscores   hangman  number           rain    teachgammon  wump
backgammon  countmail  hunt     phantasia        random  tetris-bsd
battlestar  cribbage   mille    pig              robots  trek
bcd         dab        monop    pom              rot13   wargames
boggle      go-fish    morse    ppt              sail    worm
smalik2@lab46:~$

Based off this, we can see that /usr/games is in $PATH. I ran ls on that directory, and sure enough, the games listed there can be run as commands from my home directory.

15. The UNIX Programming Environment

Definition

The UNIX programming environment is basically just the ability to create programs using a UNIX operation system.. doesn't seem like there's much else to it.

Demonstration

16. Shell Scripting

Definition

I see shell scripting as 'programming' commands. You make a file and basically use bash to 'code' a series of commands and whatnot that the shell will run if you run the file.

Demonstration
echo enter your birth year
read birthyear
currentyear=$(date +%Y)
let birthyear=$currentyear-$birthyear
echo $birthyear
smalik2@lab46:~/src/unix/scripts$ ./age.sh
enter your birth year
1993
19
smalik2@lab46:~/src/unix/scripts$

unix Objective

unix Objective

The ability to accomplish/automate tasks.

Definition

Given a problem, one would be able to carry out the solution. Or be able to write a script to automate tasks to accomplish the goal - solving the problem.

Method

How easily I can do the labs.

Measurement

Normal stuff I can take care of reasonably easily. When it comes to scripting however, I have difficulty. It isn't impossible for me though.

Analysis

I can solve problems pretty effectively, especially with the help of google. Scripting was very difficult for me to get a grasp on, but now I am moderately comfortable with it. Overall I think I am pretty good at accomplishing/automating tasks - I would give myself a B in my capability.

Experiments

Experiment 4

Question

I'm not trying to answer a specific question, but the goal of this whole thing is to figure out all that inheritance stuff in C++ using the 'project' that Haas proposed to us in class. Of making a program that will perform and, or, not, nand, nor, etc.

Resources

All the stuff that we've done in class.

Hypothesis

The result will be a working program that will perform various logic functions using boolean values, and

Experiment

Working on coding the program.

Data

So far I have classes and inheritance working for and, or, and not. I have multiple inheritance applying to nor and nand working right now. I believe the only thing left is XOR.

All the files are in /home/smalik2/src/cprog/c++

Analysis

It's working well, the main obstacle was the syntax behind it all, as it is unlike anything I have ever seen.

Conclusions

When the material was originally taught, I understand the concept behind it but not how to do it. Now I have a very in depth understanding of it and how to utilize it.

Experiment 5

Question

In Case Study B for Unix/Linux, we were having fun with the dd command. At one point in the lab, Mason and I were combining our problem solving ability to tackle some of the more difficult questions, one of them being to add 17 bytes of information to the end of an 8kB file. We are supposed to pull JUST THOSE 17 BYTES from the file, using dd.

Eventually, Mason came up with the proposed spell: dd if=test.file ibs=c count=8017 skip=8kB of=testA.file Which worked beautifully.

It occurred to me that the count=8017 might be redundant, because the full file size is 8017 anyway - why would dd default to anything else?

So, my question is: would that command still work if we didn't specify count? I'm betting yes.

Resources

None really, except maybe:

man dd

Hypothesis

Oh I kind of already did this in the question section. I'm betting that the command will still work if we don't specify count, because count in that case was the full file size anyway.

Experiment

Do it with count, check result. Reset. Do it without count being specified, check result.

Data

lab46:~$ dd if=test.file ibs=c count=8017 skip=8000 of=testA.file
17+0 records in
0+1 records out
17 bytes (17 B) copied, 0.0441264 s, 0.4 kB/s
lab46:~$ cat testA.file 
more information
lab46:~$ dd if=test.file ibs=c skip=8000 of=testB.file
17+0 records in
0+1 records out
17 bytes (17 B) copied, 0.0454818 s, 0.4 kB/s
lab46:~$ cat testB.file 
more information
lab46:~$ 

Analysis

Yes, I was right. It still worked. Same result. Ohhhh I love being right. There were no shortcomings in any way, and my hypothesis was nicely applicable. Very smooth experiment.

Conclusions

When using dd, the count argument need only be used if you need to stop copying before you reach the end of the file. For example, in a 50 byte file, let's say you need bytes 3-18.

dd if=input.file ibs=c skip=3 count=15 of=output.file

Retest 2

Perform the following steps:

State Experiment

http://lab46.corning-cc.edu/opus/spring2012/jcavalu3/start#experiment_1 Josh Cavaluzzi

What would be printed if I replace the %u with the $d for an unsigned integer?

Resources

* Do you feel the given resources are adequate in providing sufficient background information? Yes * Are there additional resources you've found that you can add to the resources list? Not particularly, it's a pretty simple concept that can be easily surmised. * Does the original experimenter appear to have obtained a necessary fundamental understanding of the concepts leading up to their stated experiment? Yes. * If you find a deviation in opinion, state why you think this might exist. I agree with everything stated.

Hypothesis

Hypothesis: I believe that the printed value will be the same ONLY if it is within the range of the signed integer data type. Ex. If the user inputs a value between 0 and 2,147,483,647, then it should print out fine, but if the value is greater than that range, then the value will “roll over” to the next integer in the signed integer data type, which would make the value a negative number. Due to the data type only covering positive numbers (unsigned integer), it can go to larger numbers in the 4 bytes it is given for memory, but if it is printed as a signed integer, then it will only be able to print out half of the positive integers that it could as an unsigned integer, so it will go back over into the negative numbers until it satisfies the amount of digits it has.

  • Do you feel their hypothesis is adequate in capturing the essence of what they're trying to discover?

Yes

  • What improvements could you make to their hypothesis, if any?

None.

Experiment

  • Are the instructions correct in successfully achieving the results?

Yes

  • Is there room for improvement in the experiment instructions/description? What suggestions would you make?

Not realy. * Would you make any alterations to the structure of the experiment to yield better results? What, and why? Nope.

Data

Publish the data you have gained from your performing of the experiment here.

I used his code and got the exact same results.

Analysis

Answer the following:

  • Does the data seem in-line with the published data from the original author? Yes
  • Can you explain any deviations? There weren't any.
  • How about any sources of error? Not really. Unless a computer has a different definition for an integer.. but we were using the same system.
  • Is the stated hypothesis adequate? Yes.

Conclusions

Answer the following:

  • What conclusions can you make based on performing the experiment? He's right.
  • Do you feel the experiment was adequate in obtaining a further understanding of a concept? Yes
  • Does the original author appear to have gotten some value out of performing the experiment? Yes
  • Any suggestions or observations that could improve this particular process (in general, or specifically you, or specifically for the original author).

Nope

Part 3

Entries

Entry 9: April 17, 2012

I'm currently doing Unix Case Study B (still a little behind, but catching up quickly!).

The first part has us using the dd command. I found this funny because over the past month I've picked up this habit of flashing different cell modems on my phone. In order to flash them, I have to connect to my phone using the android debugging bridge (which let's me set up a shell on my phone, accessed through my computer), and then use dd to data dump the data in the cell modem files into the proper related phone directories.

It's important because well, I've used it for tasks before. Being able to use this tool is pretty helpful. It allows me to grab parts of files and put them separately, or move parts of files into other files etc.

Just a fun little thing.

Entry 10: April 20, 2012

For the past couple of days I've been doing Lab B for unix. I really like having this newfound power to go through files and sort them and do searches and getting what I want out of the files. Very empowering feeling. I like it so much that writing the scripts for this lab are semi enjoyable, until I run into a huge block (like I am right now) that I can't for the life of me figure out.

It's really important to have this ability because when it comes to information manipulation, this ability is absolutely essential. The lab has some pretty excellent examples of uses, ending with scripts that automate the process so that you can just type in a command with some arguments and get masses of data from an html file.

Entry 11: April 26, 2012

Last night.. or rather earlier this morning, I complete Project 3. Because I love doing things in a timely manner.

Despite the negative Karma, I believe the fact that I made the arrays dynamically allocate themselves so that the answers printed are the TRUE values, instead of being cut off, was well worth the delay.

Once I had the core of the program finished (had it in one gigantic .c file) and working, I had only met 2/3 of the Projects requirements. Now I needed to split up the C source into a multifile version, C++ class based version, and C++ class based multifile version.

Thanks to all the work I put into the class based ,logic gate, C++ multifile program, doing the above was a sinch.

Even though I was half asleep and feeling quite dead after a long day (it was one in the morning) finishing the project was quite effortless. Other than having to look at my logic program for syntax, I already knew precisely what to do. :) It was quite nice, and it's good to be able to do that. Splitting a program into multiple files - even without doing a class based approach - makes the program much more organized.

Classes would make it even more organized: but it is better for longer programs, and the entire structure and gameplan has to be well thought out beforehand. The 'just sit down and spit it out' method doesn't work as well anymore.

Entry 12: May 2, 2012

The semester is rounding up, and I can't wait to continue taking courses next semester. I've learned a lot.

In regards to unix/linux, I really appreciate how well I know the system now. I know I'm not even near towards being a master at it, but the bit that I do now know has made everyday menial tasks much easier. I've even started writing scripts to do stupid little things. I wrote one that turns off my screen using a keyboard shortcut, and one that allows me to change the # of workplaces in ubuntu.

The code for these I majorly got online, I didn't know that stuff off the top of my head. But I then took that code and put it into scripts, so that should I ever need to use it again I could, quite easily. It's pretty cool. My multitasking productivity has gone up nicely because of it.

cprog Keywords

17. Namespaces [C++]
Definition

Namespaces are basically ways to create global variables, but with a sort of 'subscope' type of feeling. Basically, let's say you have the variable of 'health'. You have the health of your character and the health of a creature. Well, you can't use the same health for both. This is where namespaces come in - we can define your health under the namespace 'Character' or something, and the health of the creature under the namespace of 'Creature'. To call health, you need to specify the namespace::health now - ensuring that there is no mix up with the different healths.

Demonstration

The above paragraph is a pretty good example, but I'm going to put down some super basic code just to get the syntax on here.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>                                                                                                                                             
 
namespace Character
{
    int health=100;
    int combat;
    long long int gold;
}
 
namespace Creature
{
    int health=25;
    int combat;
    long long int gold = 7;
}
 
int main()
{
 
    printf("Do you wish to enter combat with 'Creature'?\n\n0 for no\n1 for yes\n");
    scanf("%u", &Character::combat);
 
    if (Character::combat == 0)
    {   
        printf("Have a nice glory-free day.\n");
        return 0;
    }   
 
    do  
    {   
        if(Character::combat == 1)
        {   
            Creature::combat=1;
        }   
        else
        {   
            Creature::combat=0;
        }   
        Creature::health=25;
        while((Character::combat==1) && (Creature::combat==1))
        {   
            Character::health = Character::health - 3;
            Creature::health = Creature::health - 7;
 
            if (Creature::health <= 0)
            {   
                Character::gold = Creature::gold + Character::gold;
                printf("You killed 'Creature'.\nYou received %llu gold.\nYou have %u health remaining", Creature::gold, Character::health);
                printf("\nYou now have %llu gold\n", Character::gold);
                break;
            }   
 
            if (Character::health <= 0)
            {   
                printf("You have died.\n");
                return 0;
            }   
        }   
 
        printf("Do you wish to fight another creature? 0 for no 1 for yes\n");
        scanf("%u", &Character::combat);
    }   
    while(Character::combat==1);
    printf("You have fled from combat.\n");
 
    return 0;
}

Alternatively (or additionally), if you want to demonstrate something on the command-line, you can do so as follows:

lab46:~/src/cprog/messingaround$ ./Namespaces 
Do you wish to enter combat with 'Creature'?

0 for no
1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 88 health remaining
You now have 7 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 76 health remaining
You now have 14 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 64 health remaining
You now have 21 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 52 health remaining
You now have 28 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 40 health remaining
You now have 35 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 28 health remaining
You now have 42 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 16 health remaining
You now have 49 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 4 health remaining
You now have 56 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You have died.
lab46:~/src/cprog/messingaround$ 
18. Functions, Parameters (Pass by: Value, Address, Reference), Return Types, Recursion, Command-line arguments
Definition

Functions are basically blocks of code that are run when called, and can be given inputs (parameters). You can pass parameters by value (just give it the identifier), Address (using the & symbol), and by Reference (by pointers, for passing an array).

Functions can return values of different types, whether they be int, float, etc.

Recursion is when you call a function within a function, with a conditional break.

Demonstration
#include<stdio.h>                                                                                                                  
#include<stdlib.h>
 
int sum(int, int, int, int);    //function prototype
 
int main()
{
    int a,b,c,d;
    a=b=c=d=0;
 
    printf("\nEnter four numbers\n");
    scanf("%d%d%d%d", &a, &b, &c, &d);
 
    printf("The sum of %d, %d, %d, and %d is: %d\n", a,b,c,d, sum(a, b, c, d));
 
    return (0);
 
}
 
 
int sum(int a, int b, int c, int d)
{
    int SUM;
 
    SUM = a + b + c + d;
 
    return (SUM);
}

Alternatively (or additionally), if you want to demonstrate something on the command-line, you can do so as follows:

#include <stdlib.h>                                                                                                                
#include <stdio.h>
 
int main(int argc, char **argv)
{
    unsigned char i;
 
    if(argc < 2)
    {   
        printf("%8s must be run with 1 or \
        more arguments, you only provided %hhu\n", *(argv+0),(argc-1));
        exit(1);
    }   
 
    printf("You ran this program with %hhu arguments, they are:\n", argc);
 
    for(i=0; i<argc; i++)
    {   
        printf("argv[%hhu]: %s\n", i, *(argv+i));
    }   
 
    return(0);
 
}
19. Templates, STL (Standard Template Library) [C++]
Definition

Templates are kind of like function overloading. Except, you do the SAME THING given different parameters.

The STL is basically a library just filled with tons of templates to do stuff.

Demonstration
#include <stdlib.h>                                                                                                                  
#include <stdio.h>
#include <cstdio>
#include <iostream>
 
using namespace std;
 
template <class T>  //The T will basically be replaced by whatever 
T larger (T x, T y) //data type is necessary
{
    if (x >= y)
    {   
        return x;
    }   
    else
    {   
        return y;
    }   
}
 
int main()
{
    int a = 1200, b = 12; 
    float c = 3.1415, d = 143.24;
    char e = 65, f = 'B';
 
    cout << larger(a,b) << endl;
    cout << larger(c,d) << endl;
    cout << larger(e,f) << endl;
 
    return 0;
}
lab46:~/src/cprog/messingaround$ ./Template 
1200
143.24
B
20. Classes (Objects, Constructor, Destructor, Access Control, Public, Protected, Private, Friend, “this” pointer) [C++]
Definition

Classes are wonderful little things good for organizing larger scale programs.

Objects are the things in the class, functions or variables or constants or friends, etc. Constructor is what runs when the class is being set up for usage. Optionary. Destructor is what runs when the class is deleted. Optionary. Access Control refers to the Public Protect and Private deal going on.

Public - Anybody can access this part. Protected - Only children can access this part (children are other classes that inherit from this class). Private - Only this class can access these parts. Friends - Allow you to rip through Access control, and access private parts from outside the class they belong to.

“This” pointer - When you make a new class to call and define it as a pointer, you have to use → to refer to it instead of a period.

Demonstration

There's two class-based programs in

cd /home/smalik2/src/cprog/c++

Also, Project 3.

21. Compiler, Preprocessor, Flags, Assembler, Linker, Multi-file programs (how to structure, how to compile)
Definition

The compiler takes your source code and translates it to assembly language.

The preprocessor deals with taking care of stuff before the actual compiling begins.

Flags are the command line arguments to the compiler, such as -02.

Assembler takes the assembly code (step 1 of compiling) and converts it into true machine code.

The Linker takes care of making sure that stuff from other libraries and header files and stuff will work correctly and be there.

Multi-file programs are programs made over multiple files.

Demonstration

I'll compile a multi-file program here.

lab46:~/src/cprog/c++/today$ ls
main.cc  rectangle.cc  rectangle.h  shape.cc  shape.h  square.cc  square.h  triangle.cc  triangle.h
lab46:~/src/cprog/c++/today$ g++ -c *.cc
lab46:~/src/cprog/c++/today$ ls
main.cc  rectangle.cc  rectangle.o  shape.h  square.cc  square.o     triangle.h
main.o   rectangle.h   shape.cc     shape.o  square.h   triangle.cc  triangle.o
lab46:~/src/cprog/c++/today$ g++ -o Program *.o
lab46:~/src/cprog/c++/today$ ./Program 
1 for Rectangle
2 for Square
3 for Triangle
2
You chose square. Enter the width/length: 12

The perimeter is: 48
The area is: 144

Einen schönen Tag noch, Ruck.

lab46:~/src/cprog/c++/today$ 
22. Type Casting Operators, Const-Volatility Specifiers (const, volatile) [C++]
Definition

Type Casting is basically converting some type of data into another type. Const is a keyword that means that the type can not be changed. Volatile is a keyword that means you can modify using some tricks.

Demonstration

We didn't really go into this in class, except for when we used arrays.

When we used malloc to create an array, we were type casting it so that the memory we gave to the array would behave properly - according to the data type that we wanted for the array.

float *Array;
Array = (float*)malloc(sizeof(float)*50);      //(float*) is a type cast.
23. typedef, enum, union
Definition

A typedef basically let's you take something, and create a shortcut for it. This shortcut now represents what you originally typedef, and the two can be used interchangeably. An enum is a data type that consists of named values. A union is kind of like a struct, where it holds a bunch of different types of data. The trick is, you can only have one type of data in it at a given time. Assigning new data, overwrites the old data.

Demonstration

There's a typedef in the EoCE. There's an enum and union in my cprog folder.

24. Structures (Declaration, Accessing Elements, Pointers to)
Definition

Structures are basically The C version of classes. They are heterogeneous data types, and can hold multiple things. Functions and data types. They are really good and useful for organization oriented stuff.

Demonstration

On the EoCE there is a lot of strcuture stuff on 0x6 and 0x7.

cprog Objective

cprog Objective

justify the use of various programming constructs within code solutions

Definition

This objective means being able to build a solution for a problem using some sensible approach. On top of that, you outta be able to come up with very sound reasons for your approach. (Why did I use classes to do this? For example).

Method

I can judge how well I organize my code, and whether or not my methods make sense/ are good.

Measurement

I normally take a very good approach in how I organize and construct my solutions to problems, so I figure I do a pretty decent job of it.

Analysis
  • How did you do? I think I did well.
  • Is there room for improvement? Of course there is!
  • Could the measurement process be enhanced to be more effective? I don't know - perhaps using an outside source. If somebody else can tell why I took an approach that's even better.
  • Do you think this enhancement would be efficient to employ? If people agreed to help me.
  • Could the course objective be altered to be more applicable? How would you alter it? Not particularly, I wouldn't alter it.

unix Keywords

17. Compiler, Assembler, Linker, Loader
Definition

The compiler takes the code and translates it into assembly code.

The assembler takes the assembly code and translates it into machine code - the resulting file being an object file.

The linker looks at the object file (which is linked to other object files and libraries, like the stuff from stdlib etc) and figures out how it all comes together, and assign memory locations to everything.

When it comes to load time, the loader creates a process and basically sets everything up for your program to run, and then launches into the instructions of your program.

Demonstration

It's possible to do these steps one at a time instead of letting gcc / g++ do it all for you. But it's rather painful.

g++ -c *.cc → will give you .o object files. These are compiled and assembled, so they are in machine code.

g++ -o Program *.o → This will link those object files, and give you a running program. yay!

18. Source Code, Object Code, Binary Code, Library
Definition

Source Code is the file that contains the code that you wrote.

Object Code is the file that contains the machine code, after the compiler and assembler are done with it.

Binary Code is the file that contains the machine code, and has been linked.

A library is a file that you can link to that contains many functions. There are math libraries, and then the standard libraries, etc.

Demonstration

We start with c source code files.
Then we translate them into object code files.
Then we finally link it all into a binary code file.
The last step also takes care of attaching the libraries I used and stuff.

lab46:~/src/cprog/projects/CProject2$ ls
Arrays.c  Functions.h  Math.c  Project2Monolithic.c
lab46:~/src/cprog/projects/CProject2$ gcc -c *.c
lab46:~/src/cprog/projects/CProject2$ ls
Arrays.c  Arrays.o  Functions.h  Math.c  Math.o  Project2Monolithic.c  Project2Monolithic.o
lab46:~/src/cprog/projects/CProject2$ gcc -o Program *.o
lab46:~/src/cprog/projects/CProject2$ ls
Arrays.c  Arrays.o  Functions.h  Math.c  Math.o  Program  Project2Monolithic.c  Project2Monolithic.o
lab46:~/src/cprog/projects/CProject2$ 
19. Pattern Matching
Definition

Pattern matching is the ability to find things that you're looking for, by using patterns to search for them.

Demonstration

Compiling a multifile program using patterns, instead of typing out a bunch of different file names.

lab46:~/src/cprog/c++/today$ ls
main.cc  rectangle.cc  rectangle.h  shape.cc  shape.h  square.cc  square.h  triangle.cc  triangle.h
lab46:~/src/cprog/c++/today$ g++ -c *.cc
lab46:~/src/cprog/c++/today$ ls
main.cc  rectangle.cc  rectangle.o  shape.h  square.cc  square.o     triangle.h
main.o   rectangle.h   shape.cc     shape.o  square.h   triangle.cc  triangle.o
lab46:~/src/cprog/c++/today$ g++ -o Program *.o
lab46:~/src/cprog/c++/today$ ./Program 
1 for Rectangle
2 for Square
3 for Triangle
2
You chose square. Enter the width/length: 12

The perimeter is: 48
The area is: 144

Einen schönen Tag noch, Ruck.

lab46:~/src/cprog/c++/today$ 
20. Regular Expressions
Definition

Regular Expressions, or RegEx, are algorithms that will match something.
By using these, you can search for, let's say, any word in a txt file that contains the gerund 'ing'.
It's pretty powerful stuff.

Demonstration

I have a file with a bunch of courses. Let's say I only want the Shortcut version (like, BUSN 0003 and FYEX 1000).

I can pipe the output through egrep which uses RegEx to match up to what I want.

The hard part, is coming up with the RegExp.

lab46:~/src/unix/courselist$ cat test.file
HIPAA - 77017 - BUSN 0003 - 001
Computer Keyboarding - 77015 - BUOT 1061 - 001
Word Processing for Non-Major - 77016 - BUOT 1062 - 001
Intro Graphical User Interface - 77002 - CSST 1031 - 001
OSHA Special Topics (30ct hr) - 77011 - ENVR 0030 - 001
Natural Gas Equipment Oper - 77014 - ENVR 0072 - 001
First Year Experience - 77005 - FYEX 1000 - 001
First Year Experience - 77004 - FYEX 1000 - 002
BasicLifeSupport-Prof. Rescuer - 77006 - HLTH 1010 - 001
BasicLifeSupport-Prof. Rescuer - 77007 - HLTH 1010 - 002
American History II - 77020 - HIST 1120 - 001
Achievement Motivation - 77021 - HUSR 1000 - 001
Care.&Aging Issue-Healthy Func - 77029 - HUSR 1411 - 001
Caregiving&Aging Issues-Common - 77030 - HUSR 1412 - 001
Lean Special Topic (24cnt) - 77012 - LEAN 0024 - 001
LEN Special Topic (57 cnt hr) - 77027 - LEN 0057 - 001
Excel Advanced Workshop - 77025 - EXCL 0004 - 001
Intro. to MasterCam Design - 77026 - MCAM 0113 - 001
Structures of Mathematics I - 77028 - MATH 1110 - 001
Medical Terminology - 77013 - MEDT 0030 - 001
Nurse Aide/Home Health Aide - 77022 - MDNC 0315 - 001
Child Abuse Recognition - 77023 - PDEV 0011 - 001
Child Abuse Recognition - 77024 - PDEV 0011 - 002
Child Psychology - 77010 - PSYC 2207 - 001
Abnormal Psychology - 77009 - PSYC 2215 - 001
Cross-Country Skiing (co-ed) - 77018 - RECC 1014 - 001
Wilderness Navigation - 77019 - RECC 1015 - 001
Introduction to Sociology - 77003 - SOCI 1010 - 001
The Vegetarian Adventure - 77008 - WELL 1011 - 001
lab46:~/src/unix/courselist$ cat test.file | egrep -o '[A-Z]?[A-Z]{3} [0-9]{4}'
BUSN 0003
BUOT 1061
BUOT 1062
CSST 1031
ENVR 0030
ENVR 0072
FYEX 1000
FYEX 1000
HLTH 1010
HLTH 1010
HIST 1120
HUSR 1000
HUSR 1411
HUSR 1412
LEAN 0024
LEN 0057
EXCL 0004
MCAM 0113
MATH 1110
MEDT 0030
MDNC 0315
PDEV 0011
PDEV 0011
PSYC 2207
PSYC 2215
RECC 1014
RECC 1015
SOCI 1010
WELL 1011
lab46:~/src/unix/courselist$ 
21 Filtering
Definition

Filtering is basically a program that gets data from standard input and then writes results to standard output. Like running grep on the cat from a file.

Demonstration

So, cat on a file outputs that files contents to standard output. If I pipe this to grep, grep will accept that standard input (that was output from cat) and then return it's answer to standard output.

Here we are printing a .html file to standard output, finding all the instances of CSCS, and then counting how many times that CSCS appears.

lab46:~$ cat fall2011-20110417.html | grep -o 'CSCS' | wc -l
51
lab46:~$ 
22. networking, UNIX Networking Tools
Definition

We never really went into networking with UNIX. It's such a broad topic that I don't really know how to get into it either.

Demonstration
23. Security
Definition

In UNIX/Linux the way that the system is set up provides good security by itself.

Since all files have permissions, just setting up the system to provide the correct permissions to the correct users ensures that the wrong people can't get their hands on files they shouldn't.

Taking advantage of the root-group-owner permission system is a great way of providing security in a multi-user system.

On top of it all, UNIX/Linux systems don't really have many viruses to begin with. All the viruses created target Windows and occasionally OS X.

Demonstration
24. X Window System
Definition

The X Window System is a software system that provides a GUI basically.

It has a very strong UNIX/Linux philosophy operating behind it.

It's designed to accept added functionality, and leaving it up to the user to determine what they want to do with it.

Demonstration

unix Objective

unix Objective

understanding and use of pattern matching

Definition

It's pretty straight forward. This means that we can use tools like grep, or even understand the syntax for searching for patterns instead of specifics using things like ls

Method

How well I utilize regexp.

Measurement

After struggling through the labs related to pattern matching and regexp and grep and all that good stuff, I feel pretty confident in my ability to use patterm matching.

Analysis
  • How did you do? Good
  • Is there room for improvement? Oh yes, I still struggled with finding a solution at a glance.
  • Could the measurement process be enhanced to be more effective? Not really, it's pretty easy to test it.
  • Do you think this enhancement would be efficient to employ? N/A
  • Could the course objective be altered to be more applicable? How would you alter it? Not really. maybe specify regexp.

Experiments

Experiment 7

Question

If I have a double pointer, to pass a value to it from scanf do I have to dereference the double pointer only once? (That would make it 'referenced' by one layer, in my mind).

Resources

Don't really need resources, it's a straightforward test.

Hypothesis

I think it will work because I ran into something similar doing project4. I had an array and was using scanf to fill it, so it was a single pointer. To use scanf, I just called the name. No dereference or anything.

Experiment

I'm going to write a simple program. Make a double pointer and see if I can scanf and print the value the way I believe it will work.

Data

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3
  4 int main()
  5 {
  6     int **numbers;
  7
  8     *numbers = (int*)malloc(sizeof(int)*1);
  9
 10     printf("HEY!!! Enter a number. Please? :)\n");
 11
 12     scanf("%d", *numbers);
 13
 14     printf("\nHEY!!! The number you entered? Yeah. It should be %d.\n", **nu    mbers);
 15
 16     return 0;
 17 }
lab46:~/src/cprog/messingaround$ ./scanfdoublepointer
Segmentation fault
lab46:~/src/cprog/messingaround$

Analysis

Based on the data collected:

  • Was your hypothesis correct? I'm not sure.
  • Was your hypothesis not applicable? I'm starting to feel it's not applicable.
  • Is there more going on than you originally thought? (shortcomings in hypothesis) Yeah. I keep segfaulting.
  • What shortcomings might there be in your experiment? I got a segfault.
  • What shortcomings might there be in your data? I got a segfault.

Conclusions

What can you ascertain based on the experiment performed and data collected? Document your findings here; make a statement as to any discoveries you've made.

Well, no matter what, I keep getting a segfault. I'm guessing that this would mean my hypothesis was incorrect.

Experiment 8

Question

I wonder what would happen if I tried to chmod using permissions like 888, or something like that.

Resources

Nothing was consulted.

Hypothesis

I'm betting that it either doesn't work, or it defaults to 777 or something.

Experiment

I am going to try it out and see what happens.

Data

lab46:~/src/unix/scripts$ ls
age.sh       csd.sh  firstforloop.sh  guess1.sh     mail.sh     script2.sh
botstart.sh  files   firstlist.sh     histogram.sh  script1.sh
lab46:~/src/unix/scripts$ chmod 888 age.sh
chmod: invalid mode: `888'
Try `chmod --help' for more information.
lab46:~/src/unix/scripts$ chmod 10292 guess1.sh
chmod: invalid mode: `10292'
Try `chmod --help' for more information.
lab46:~/src/unix/scripts$ chmod 77 age.sh
lab46:~/src/unix/scripts$ ls -lh age.sh
----rwxrwx 1 smalik2 lab46 120 Mar  8 11:45 age.sh
lab46:~/src/unix/scripts$ chmod 777 age.sh
lab46:~/src/unix/scripts$

Analysis

Based on the data collected:

  • Was your hypothesis correct? - Yes
  • Was your hypothesis not applicable? - N/A
  • Is there more going on than you originally thought? (shortcomings in hypothesis) - I decided to test if I only provided like a 77, and it affected just owner and group.
  • What shortcomings might there be in your experiment? - Nothing really.
  • What shortcomings might there be in your data? - Nothing

Conclusions

Chmod doesn't work if you provide something higher than a 7, or longer than 3 digits.

Retest 3

Perform the following steps:

State Experiment

Whose existing experiment are you going to retest? Provide the URL, note the author, and restate their question.

Resources

Evaluate their resources and commentary. Answer the following questions:

  • Do you feel the given resources are adequate in providing sufficient background information?
  • Are there additional resources you've found that you can add to the resources list?
  • Does the original experimenter appear to have obtained a necessary fundamental understanding of the concepts leading up to their stated experiment?
  • If you find a deviation in opinion, state why you think this might exist.

Hypothesis

State their experiment's hypothesis. Answer the following questions:

  • Do you feel their hypothesis is adequate in capturing the essence of what they're trying to discover?
  • What improvements could you make to their hypothesis, if any?

Experiment

Follow the steps given to recreate the original experiment. Answer the following questions:

  • Are the instructions correct in successfully achieving the results?
  • Is there room for improvement in the experiment instructions/description? What suggestions would you make?
  • Would you make any alterations to the structure of the experiment to yield better results? What, and why?

Data

Publish the data you have gained from your performing of the experiment here.

Analysis

Answer the following:

  • Does the data seem in-line with the published data from the original author?
  • Can you explain any deviations?
  • How about any sources of error?
  • Is the stated hypothesis adequate?

Conclusions

Answer the following:

  • What conclusions can you make based on performing the experiment?
  • Do you feel the experiment was adequate in obtaining a further understanding of a concept?
  • Does the original author appear to have gotten some value out of performing the experiment?
  • Any suggestions or observations that could improve this particular process (in general, or specifically you, or specifically for the original author).