C/C++ Programming Journal
August 28th, 2013
This is the first day of class.
Class Websites
An important thing introduced to the class today was the class website.
This page is important because it contains all the tasks for the semester, and it serves as a central hub for all notes in the class.
lab46
The actual place where the magic happens. Lab46 is the server that we must ssh into in order to do class work.
In order for me to get into the server I have to use a program called putty.
Once Installed its very simple to get to the server.
login as :
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 .
.. . . . . . . . . . ..
No mail.
Challenging Concepts
August 29th, 2013 - Lab
GNU
Today we learned about GNU
GNU - GNU not UNIX GNU created collection of tools
Diagram given to us by Joe the hierarchy of coding
c - higher level
translate ~ compile ~ gcc
processor
Hello World
int main (int a, char **){
printf ("Hello World!!!");
}
This alone is not enough to get GCC to be able to compile the program.
We have to add a bit of code to be beginning of the program for it to work.
If we include “# include <stdio.h>” at the begining then it should work.
stdio is the standard IO file
UNIX Commands
GCC
GCC manual gcc.gnu.org
-W ~ shows warnings when compiling
-Wall - shows all warnings
gcc -Wall -o “output file” “c file name”
gcc uses file name extensions to help figure out what it should be doing and what kind of file it is dealing with
Bash
; = statement terminator
{ } = block or group statements
( ) = Function
? mark = keeps the value of the last command
&& = logical and only true when both true
Challenging Concepts
I am struggling to wrap my head around just how C works. I have dealt with other coding languages before, but they actually made sense.
Learning the whole case sensitive commands is also difficult for me.
Things to look into
GCC manual gcc.gnu.org
section 3 look at ~ see it goes through phases 1: preproccessing 2: compilling 3: assembling 4: linking
August 30th, 2013
Review
Shell in UNIX called bash
c environment is ran within shell environment using ./
cant run c programs without
OS obviously
in bash a dash means an argument
Class Repository
The class repository is a version controlled storage system for keeping files of any kind.
We can return to any stage in the file's life cycle.
Great for in case our program stops working, we can roll back
This is a distributed revision control system - you get your files from the server but you can serve the server from a terminal location using this system
lab46:~$ hg help
Setup Step 1 - Cleaning src directory
Setup Step 2 - Making new src directory
Setup Step 3 - Local Cloning
lab46:~$ hg clone http://www/hg/user/(username) ~/src
Setup Step 3 - Alternative Remote Cloning
lab46:~$ hg clone http://lab46.corning-cc.edu/hg/user/(username) ~/src
Setup Step 4 - Restoring src content
lab46:~$ cd src
lab46:~$ lab46:~/src$ mv ~/src.bak/* ~/src/
lab46:~/src$ rmdir ~/src.bak
Setup Step 5 - Customizing Repo
The name of the settings file for mercurial is hgrc
The file is located in /src/.hg
We need to change a few settings for it to work how we want
lab46:~/src$ vi .hg/hgrc
[paths]
default = http://www/hg/user/(lab46username)
[web]
push_ssl = False
allow_push = *
[ui]
username = (your real first name followed by last name, space separated) <(lab46username)@lab46.corning-cc.edu>
[auth]
lab46.prefix = http://www/hg/user/(lab46username)
lab46.username = (lab46username)
lab46.schemes = http
Setup Step 6 - Ignoring File Types for sync
Sync Step 1 - Checking for changes in src folder
Sync Step 2 - Adding files to the tracking
lab46:~/src$ hg add
lab46:~/src$ hg add
adding pokemon.c
lab46:~/src$
Sync Step 3 - Committing and pushing files
lab46:~/src$ hg commit -m "(something to note about the commit that can be easily referenced)"
lab46:~/src$ hg push
http authorization required
realm: Lab46/LAIR Mercurial Repository (Authorization Required)
user: <lab 46 user name>
password: <lab 46 password>
pushing to http://www/user/<lab 46 user name>
searching for changes
remote: adding changesets
remote: adding manifests
remote: adding file changes
remote: added <#> changesets with <#> change to <#> file
Alternative Sync Step 1
If working in a situation where you are not the only person working on the files, then you would need to pull changes from the repository
This generally works the same way as push, you are prompted for your lab46 username and password.\
The command to pull is pretty obvious
lab46:~/src$ hg pull
lab46:~/src$ hg update
Challenges
I have dealt with revision control systems before, being that I have had a class with Joe. When I had my class with joe, we used a
GUI for the file syncing. Getting used to the syncing with a CLI is going to be a difficult adjustment.
I also host a cloud service of my own using owncloud which is much like this, but I am going to try out syncing the class repo to my raspberry pi. I am not sure if I can though, but it is worth a shot. A port might be blocked preventing me from doing so, but I noticed the guide suggested doing so.
September 4th, 2013
There were lots of things covered today the primary thing was data-types
Data Types
Integer Types ~ length describes the size of the storage allocated ~ most likely to be used
char ~ short for character has a dual purpose of being able to display character data
short int ~ short integer ~ describes a small scale integer
Int ~ integer ~ a thing that represents a whole number
long int
long long Int
Signed and Unsigned versions of all exist
One will be assumed automatically
if you want it to be signed then it has to be + or negative numbers
if you care that there is a sign then specify it
Floating Point
Scaler
Pointer Types ~ memory variables not really a thing that stands by themselves utilize the existing types ~ describing the region of memory that is pointing at something with specified property
Composite
Arrays ~ all of the other types can be represented as an array homogenous in an array every element needs to be of the same data type
Structures (struct) ~ heterogeneous can be of any types
Things to note
Integer array is no different than having separate integer storage points
Consider the performance requirements of your program and try to keep them reasonable even with the limits of memory being pushed daily to extreme ends. Proper coding is a must
most programing books for c use argc argv as their examples
main has the ability to communicate with the system
Variables defined by the command line
Example : int main (int argc, char ** argv)
argc is an argument count
when ever you see a * that is not there for multiplication it denotes use of pointers
with the program knowing what it was called at run time, it can behave differently depending on how it was called
Common Escape Characters
\0 nul terminator ~ its how string termination is determined ~ translates to an asci character
\n new line ~ most used
\b back over the characters
\a
\l clear screen sometimes
\f
\t tab ~ second most used
OS Specific Notes
1) unix use line feeds to denote end of line
2) dos / windows use crlf carriage return line feed
3) mac used cr carriage return
Source Code
source code portability ~ when you have the source code not only can you run it on other systems but you can fix it and enhance it for your own needs
binary code portability ~ no system requirement but needs a specific program to help
1) jAVA ~ java vm needs to be available ~ need to be running a similar version
2) Interpreters
3) flash ~ with limits
1) c got its name to fame from source code portability
2) having the source code in a c compiler allows me to run the c code in any system
Storage Requirements and Usage
How much storage does it use?
What are the range of values we can store in them?
declare the existence of the variable
always a good thing to initialize your variable
Finding the size
printf is formatted text
every string has a nul terminator in it of \0 its hidden non printable character
% sign is a substitution that is about to take place in a printf
%d = e
%v = f
%c = g
substitution happens at order of things
%hhu means half half unsigned integer which means char
%hu means half unsigned integer
%u unsigned integer
%hd means half signed integer
%lu means
%lu means
Example for unsigned char
#include <stdio.h>
int main( )
{
signed char sc;
unsigned char uc;
sc = 0;
uc = 0;
printf("an unsigned char is %hhu bytes \n", sizeof(uc));
printf("lower bound is % hhu \n", uc);
printf ("upper bound is % hhu \n", (uc - 1));
return(0);
}
Challenges
This is really stepping into the unknown for me.
I have never really thought of the actual size of things.
I do not understand the whole unsigned and signed stuff yet
Hopefully it will become clear with time
Update
Unsigned
1 #include <stdio.h>
2 int main( )
3 {
4 unsigned char uc=0;
5 unsigned short int us=0;
6 unsigned int ui=0;
7 unsigned long int ul=0;
8 unsigned long long int um=0;
9 //unsigned char
10 printf("A unsigned char is %d byte\n",sizeof(uc));
11 printf("Lower bounds is %hhu\n", (uc));
12 printf("Upper bounds is %hhu\n\n", (uc-1));
13 //unsigned short
14 printf("A unsigned short is %d bytes\n",sizeof(us));
15 printf("Lower bounds is %hu\n", (us));
16 printf("Upper bounds is %hu\n\n", (us-1));
17 //unsigned int
18 printf("A unsigned int is %d bytes\n",sizeof(ui));
19 printf("Lower bounds is %u\n", (ui));
20 printf("Upper bounds is %u\n\n", (ui-1));
21 //unsigned long
22 printf("A unsigned long is %d bytes\n",sizeof(ul));
23 printf("Lower bounds is %lu\n", (ul));
24 printf("Upper bounds is %lu\n\n", (ul-1));
25 //unsigned long long
26 printf("A unsigned long long is %d bytes\n",sizeof(um));
27 printf("Lower bounds is %llu\n", (um));
28 printf("Upper bounds is %llu\n\n", (um-1));
29 return(0);
30 }
A unsigned char is 1 byte
Lower bounds is 0
Upper bounds is 255
A unsigned short is 2 bytes
Lower bounds is 0
Upper bounds is 65535
A unsigned int is 4 bytes
Lower bounds is 0
Upper bounds is 4294967295
A unsigned long is 8 bytes
Lower bounds is 0
Upper bounds is 18446744073709551615
A unsigned long long is 8 bytes
Lower bounds is 0
Upper bounds is 18446744073709551615
Signed
1 #include <stdio.h>
2 int main( )
3 {
4 signed char sc=0;
5 signed short int ss=0;
6 signed int si=0;
7 signed long int sl=0;
8 signed long long int sm=0;
9 //signed char
10 printf("A signed char is %d byte\n",sizeof(sc));
11 printf("Lower bounds is %hhd\n", ((unsigned char)(sc-1)/2)+1);
12 printf("Upper bounds is %hhd\n\n", ((unsigned char)(sc-1)/2));
13 //signed short
14 printf("A signed short is %d bytes\n",sizeof(ss));
15 printf("Lower bounds is %hd\n", ((unsigned short)(ss-1)/2)+1);
16 printf("Upper bounds is %hd\n\n", ((unsigned short)(ss-1)/2));
17 //signed int
18 printf("A signed int is %d bytes\n",sizeof(si));
19 printf("Lower bounds is %d\n", ((unsigned int)(si-1)/2)+1);
20 printf("Upper bounds is %d\n\n", ((unsigned int)(si-1)/2));
21 //signed long
22 printf("A signed long is %d bytes\n",sizeof(sl));
23 printf("Lower bounds is %ld\n", ((unsigned long)(sl-1)/2)+1);
24 printf("Upper bounds is %ld\n\n", ((unsigned long)(sl-1)/2));
25 //signed long long
26 printf("A signed long long is %d bytes\n",sizeof(sm));
27 printf("Lower bounds is %lld\n", ((unsigned long long)(sm-1)/2)+1);
28 printf("Upper bounds is %lld\n\n", ((unsigned long long)(sm-1)/2));
29 return(0);
30 }
A signed char is 1 byte
Lower bounds is -128
Upper bounds is 127
A signed short is 2 bytes
Lower bounds is -32768
Upper bounds is 32767
A signed int is 4 bytes
Lower bounds is -2147483648
Upper bounds is 2147483647
A signed long is 8 bytes
Lower bounds is -9223372036854775808
Upper bounds is 9223372036854775807
A signed long long is 8 bytes
Lower bounds is -9223372036854775808
Upper bounds is 9223372036854775807
September 5th, 2013 - Lab
Review
Create a CMD Shortcut
right click on a cmd shortcut
go to the properties
go to the target
if you leave the start in blank, then the start in section uses the current working directory instead
Differences
cmd /? you
in UNIX you have -h and in windows you have /?
in windows you use a \ for a path separator and / is an option
in windows you call scripts files batch files or .bat
MinGW
Environment
environment is the memory space in which the processes are working in
set ~ spits out all environment variables
all environment variables have an equal sign
you cant have spaces in environment variables
on left side is the environment name and on the right is the variable
CLI Interpenetrate
two major types of commands in a command line interpenetrate
internal (Unix and Linux ~ built into the command line inter - knows where to go )
external
if it cant find it it searches for a file with that name and the file is executable, it will execute it
in windows cmd looks in the current directory first, unix / linux does not look in the current directory
path = something sets the path directory
C and C++
Joe Rant
look at section 5
You might see someone start a hello world program that starts
Void main ( Void ) {
}
vs
Int main (int a , char ** ) {
}
Void is a data type but nothing is something so you have to have a data type for nothing
what is the answer to y = f(x)?
not enough information. can agree it is a function. is it a call or a definition?
this is the notion of a function call
reason its hard to decide is that the function has never been defined
if i see a set of parenthesis and something to the left its not always a function , it could be part of order of operations
a(b)+c(d); is it a definition or a function call
functions exponents roots multiplication division addition subtraction logical operations
Functions Have
1)Name
2)Input
3)Output
Variables Have
1)Name
2)Value
3)Data type~ tells us how much memory we have to store values
try different combinations
argc is the count
argv is the vector
we can nest function calls, there are limits on how many levels you can nest, a max on grouping with parentheses
numerical limits and sizes
almost all c keywords are small list
basic things you want from any language you learn
1) learn basic output
2) learn basic input
section 1719 is input out stdio
C was born in a unix type environment
i/o is a stream of bits
Unix Output
Things To Work On
START COLAB ON
UNIX / Microsoft Command Reference ~ a Cheat Sheet equivalence
mingw bin folder file descriptions
gcc options for 1) preprocess 2) compile 3) assemble 4) link
figure out the other switches for these and how they would work
file name extensions too ~ gcc documentation on bitbucket section 3 of manual
4 ~ 9899 section 5 pull out what we find most important
freestanding hosted arguments reference for main( ) 5 9899 section 6
language for 9899 section 7 library
input output
Closing Thoughts and Challenges
Switching back to a windows environment (At Joes Request) has caused me a lot of confusion
MinGW has yet to install right for me, and I really hop e I can avoid using it.
September 6th, 2013
Signed Char
#include <stdio.h>
int main( )
{
signed char sc;
unsigned char uc;
sc = 0;
uc = 0;
printf("a signed char is %hhu bytes\n", sizeof(sc));
printf("lower bound is %hhd\n",((unsigned char)(uc-1)/2)+1);
// printf("upper bound is %hhd\n",((unsigned char)(uc-1)/2));
printf("upper bound is %hhd\n", 0xFFFF & 0x80);
return(0);
}
Unix Specifics
/usr/include has the system header directory. headers that can be used for programming
anything with a # is a preprocessor
when you do # something its actually like inserting the entire code into yours
do include statements at the top
#include “ filename” makes it break off into a directory specific file
Challenges and Closing Thoughts
September 11th, 2013
Sizes
Sizes can change throughout the years ( Int or long int could have changed )
It is important to know if they have changed so that you can create things that work with the system
the header files will talk about the limits of the system
be mindful that the header files will not accurately reflect system limits. they reflect the standard
PrintF Review
Display things with printf
printf() - not a keyword
keywords - base commands available to us
c has a set of keywords avalible to them Examples :
short
int
char
all the variable types
* - / * ^ &
Function of STDIO.h
printf() lets us display information ~ information in man 3 printf - is a family of functions - at the top of the manual it shows you the list of functions covered in the manual- the first line under the synopsis is that it tells you the include files you need to include to use the function
fprintf and sprintf most likely to be used
scanf() lets us get information from the user
int main ( ) - main is a function we are creating
malloc( ) ~ gives you a memory address called a return value, when it is done we capture it ~ gives you raw memory
Good Programming
always good to put your variables at the top of the program for readability
if you like indentation always use 4 spaces, if you like tab always use tab
you can not name a variable after a keyword
with scanf you need to put the address of the storage location not the variable
a string of characters is also called an array of characters in -c
%s please interperate input as string data
%c prints out ascii character of value
address is the pointer without the star
& - give location of address
all strings in c need a mechanism to know when the string ends \0 also known as the null terminator is needed to let c know that a string is over
Example Program of the Day
1 #include <stdio.h>
2 #include <stdlib.h>
3 int main( )
4 {
5 char *name,fi;
6 name=NULL;
7 fi=0;
8 unsigned char age=0;
9 printf("Please enter your name");
10 name=(char*)malloc(sizeof(char)*20);
11 scanf("%s", name);
12 printf("%s, what is your age?",name);
13 scanf("%hhu",&age);
14 fi=*(name+0);
15 printf("%s, your initial is %c (%hhu) and you are %hhu years old\n",name ,fi,fi,age);
16 return(0);
17 }
September 12th, 2013 - Lab
September 13th, 2013
If Statements
If mods
* "When writing IF statements it is good to remember"
- "> greater than"
- "< less then"
- ">= greater than or equal to"
- "<= less than or equal to"
- "== Check equality ( is this equal to)"
- "!= not equals"
- "= sets equality"
- "if statements do not need a semicolon"
- "you can have if statements"
- "else statements"
- "with else if"
- "have have exactly 1 if"
- "can have only "
- "exactly 1 else"
- "0 or more else if"
- "if(0) - true"
- "if(1) - false"
If Types
do while - run through the loop and then see if it should run again
while
for - need starting value - setting start value - second part is how long do we want to loop - third part
Misc stuff
We learned about things with I but they cant be posted in wiki syntax
Counting arguments
We created a program to count the arguments on the command line, and then express them with different output styles.
running the program with the ./program-name then the count of the values after the program
September 18th, 2013
GD
Today we learned about a image manipulation library called GD.
GD is often used with things like php
C programs can be written to utilize the package.
-
1 # include <stdio.h>
2 # include <gd.h>
3 # define BLACK 0
4 # define RED 1
5 # define GREEN 2
6 # define BLUE 3
7 # define WHITE 4
8 # define YELLOW 5
9 int main()
10 {
11 FILE *out; // lets us interact with files in this case an output file
12 char outfile[]="/home/jkosty6/public_html/snowmanhouseccc.png";
13 gdImagePtr img;
14 unsigned int color[5];
15 unsigned short int high,wide,x;
16 wide=800;
17 high=600;
18 img=gdImageCreate(wide,high);
19 color[BLACK]=gdImageColorAllocate(img,0,0,0);
20 color[RED]=gdImageColorAllocate(img,255,0,0);
21 color[GREEN]=gdImageColorAllocate(img,0,255,0);
22 color[BLUE]=gdImageColorAllocate(img,0,0,255);
23 color[WHITE]=gdImageColorAllocate(img,255,255,255);
24 color[YELLOW]=gdImageColorAllocate(img,255,255,0);
25 gdImageFilledRectangle(img,0,0,wide-1,high-1,color[BLACK]);
26 gdImageFilledRectangle(img,wide/3,high/1,wide/1,high/3, color[YELLOW]);
27 gdImageFilledRectangle(img,wide/3,150,wide/1,200, color[BLUE]);
28 gdImageFilledRectangle(img,300,400,400,500, color[BLACK]);
29 gdImageFilledRectangle(img,650,400,750,500, color[BLACK]);
30 gdImageFilledRectangle(img,450,400,600,high-1, color[BLACK]);
31 gdImageFilledArc(img, 90, 90, 180, 180, -270, -90, color[RED], gdArc);
32 gdImageFilledArc(img, 180, 90, 180, 180, -270, -90, color[RED], gdArc);
33 gdImageFilledArc(img, 270, 90, 180, 180, -270, -90, color[RED], gdArc);
34 gdImageFilledArc(img, 90, 300, 100, 100, 360, 0, color[WHITE], gdArc);
35 gdImageFilledArc(img, 90, 400, 130, 130, 360, 0, color[WHITE], gdArc);
36 gdImageFilledArc(img, 90, 500, 180, 180, 360, 0, color[WHITE], gdArc);
37 out=fopen(outfile, "wb");
38 gdImagePngEx(img,out,-1);
39 fclose(out);
40 gdImageDestroy(img);
41 return(0);
42 }
Thoughts
September 19th, 2013 - Lab
September 20th, 2013
Loops
int i;
for (i=0; i<10;i++)
{
printf("%d\n",i);
}
prints out characters 0 to 9 then exits
for(start, condition, step) ~ numeric based loop, know where you start, know where you end, tell it how you wish to get there
for portion does not end with a ;
when you loop, you loop based on your looping variable
in this case our looping variable is i
second part of the thing is our loop as long as section ( i<10)
third part is how we get there (i++)
loop allows us to repeat a block of code
Loops in GD
http://lab46.corning-cc.edu/~jkosty6/classgd.png
1 # include <stdio.h>
2 # include <gd.h>
3 # define BLACK 0
4 # define RED 1
5 # define GREEN 2
6 # define BLUE 3
7 # define WHITE 4
8 int main()
9 {
10 FILE *out;
11 char outfile[]="/home/jkosty6/public_html/classgd.png";
12 gdImagePtr img;
13 unsigned int color[5];
14 unsigned short int high,wide,x,y;
15 wide=641;
16 high=641;
17 img=gdImageCreate(wide,high);
18 color[BLACK]=gdImageColorAllocate(img,0,0,0);
19 color[RED]=gdImageColorAllocate(img,255,0,0);
20 color[GREEN]=gdImageColorAllocate(img,0,255,0);
21 color[BLUE]=gdImageColorAllocate(img,0,0,255);
22 color[WHITE]=gdImageColorAllocate(img,255,255,255);
23 gdImageFilledRectangle(img,0,0,wide-1,high-1,color[BLACK]);
24 // {
25 // for(x=0;x<8;x++)
26 // for(y=0;y<8;y++)
27 // if ((x + y) % 2 == 0)
28 // {
29 // gdImageFilledRectangle(img,(80*x)+5,(80*y)+5,(80*x)+75,(80*y)+75,color[BLUE]);
30 // }
31 // else
32 // {
33 // gdImageFilledRectangle(img,(80*x)+5,(80*y)+5,(80*x)+75,(80*y)+75,color[RED]);
34 // }
35 // }
36 gdImagePngEx(img,out,-1);
37 fclose(out);
38 gdImageDestroy(img);
39 return(0);
40 }
Thoughts
After playing with GD for a few days, I am finding it to be more difficult that its worth.
UPDATE
I have figured out what my problem was. I had deleted the line 36
1 # include <stdio.h>
2 # include <gd.h>
3 # define BLACK 0
4 # define RED 1
5 # define GREEN 2
6 # define BLUE 3
7 # define WHITE 4
8 int main()
9 {
10 FILE *out;
11 char outfile[]="/home/jkosty6/public_html/classgd.png";
12 gdImagePtr img;
13 unsigned int color[5];
14 unsigned short int high,wide,x,y;
15 wide=641;
16 high=641;
17 img=gdImageCreate(wide,high);
18 color[BLACK]=gdImageColorAllocate(img,0,0,0);
19 color[RED]=gdImageColorAllocate(img,255,0,0);
20 color[GREEN]=gdImageColorAllocate(img,0,255,0);
21 color[BLUE]=gdImageColorAllocate(img,0,0,255);
22 color[WHITE]=gdImageColorAllocate(img,255,255,255);
23 gdImageFilledRectangle(img,0,0,wide-1,high-1,color[BLACK]);
24 {
25 for(x=0;x<8;x++)
26 for(y=0;y<8;y++)
27 if ((x + y) % 2 == 0)
28 {
29 gdImageFilledRectangle(img,(80*x)+5,(80*y)+5,(80*x)+75,(80*y)+75,color[BLUE]);
30 }
31 else
32 {
33 gdImageFilledRectangle(img,(80*x)+5,(80*y)+5,(80*x)+75,(80*y)+75,color[RED]);
34 }
35 }
36 out=fopen(outfile, "wb");
37 gdImagePngEx(img,out,-1);
38 fclose(out);
39 gdImageDestroy(img);
40 return(0);
41 }
September 25th, 2013
Today we learned a lot about arrays
Arrays
array[0] same as *(array+0) ~ access first element of an array
Is a homogeneous composite variable qualifier type
arrays modify an existing data-type
you are taking a type and making many of them, in that sense it is a composite type
a character array must contain characters only
with an array it is under one common name and we can arithmetically reach what we want
when you see arrays you almost always are dealing with loops
we can make arrays out of anything , int , char, gd points
first point of an array is index 0, the first element is the first thing you encounter which is always 0
the second element is the first offset which would be 1, when we look at memory addresses whats actually happening in memory is that if it is an int then we have 4 bytes per offset in an array
when we tell it to move in 1 or 2 in an array it moves in what ever the unit value of our array is, if its int, we move in 4 each time
we use arrays to store common data, things we want to put together. coordinates could work
Example
you have 3 int sized boxes located right after each other
because there are many, its a composite
because it gives us many it must be the same, int array must be all integers
Scalers
with individual variables with 1 scaler, if w wanted to deal with 3 variables with 3 values we would us scalers
if we wanted 3 int sized memory but call them one name we would use a array, same amount of space as separate scalers
we can access them using one name using an array instead of a scaller
we can simplify our code by using only one name instead of many, we use name plus offset
with this we can create loops to access each element in an array, if we used scalers we would need to use if statements to hit each separate named variables
===GD Arrays==-
gd allows us to create polygons by using arrays
this is like a datatype ~ gdpoint
its doing a struct ~ struct is like an array but the values do not need to be the same
Example
gdPoint triangle[3]; ~ array of 3 gd points
triangle[0].x = wide/2;
triangle[0].y = 0;
triangle[1].x =0;
triangle[1].y =high-1;
triangle[2].x =wide -1;
triangle[2].y = high -1;
Challenges
Thoughts
Drawing with GD using exact x and y values with arrays is actually easier in my opinion than the alternative
September 27th, 2013
Today we just finished working on our GD pictures.
October 2nd, 2013
Shifts
» logical right shift
« logical left shift
1 #include <stdio.h>
2 int main ()
3 {
4 int a =5;
5 printf("%d\n",a);
6 a=a|6;
7 printf("%d\n",a);
8 a=a&9;
9 printf("%d\n",a);
10 a=!a;
11 printf("%d\n",a);
12 a=a^7;
13 printf("%d\n",a);
14 return(0);
15 }
16
shifts the data to get to the right location
usually deals with external devices
bitwise or
inclusive either must be true
exclusive one must be true but not both
Example
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int getval(int,int); ~ prototyping
5 int main()
6 {
7 int i,x,u,l;
8 printf("Enter a number:");
9 scanf("%d",&i);
10 srand(i);
11 printf("Give me the highest number.");
12 scanf("%d",&u);
13 printf("Give me the lowest number.");
14 scanf("%d",&l);
15 for (i=0;i<12;i++)
16 {
17 x=getval(u,l);
18 printf("%d ",x);
19 }
20 printf("\n");
21 return(0);
22 }
23 int getval (int top, int bottom)
24 {
25 int result;
26 result = rand() %top + bottom;
27 return(result);
28 }
October 4th, 2013
We created a program to tell you the ascii value of something, and changing a letters case
1 #include <stdio.h>
2 int main()
3 {
4 char x=0;
5 char y=0;
6 printf("Enter a number (0-255): ");
7 scanf("%hhu", &x);
8 printf("Enter a character: ");
9 scanf("%c", &y);
10 printf("x is numerically %hhu and characterally %c \n",x,x);
11 scanf("y is numerically %hhu and characterally %c \n",y,y);
12 printf("x+48 characterally is %c \n", (x+48));
13 scanf("y+32 character is %c \n", (y+32));
14 return(0);
15 }
enter in a data stream, stays behind in data stream
line feed - unix - asci 10
carriage return line feed - windows - 13 and 10
carriage return - mac - 13
we need to fix our program to take care of the enter
getchar(); gets rid of the extra new line command
to get to ascii version of a number add 48
to go from upper to lower case ascii add 32
scanf
fscanf read from file
sscanf read from string
getchar
fgetc read character from file
fgets read multiple characters from file
man 3 fgetc
Function Stuff
print f and scan f are just function calls
we can go and find them inside the c library
keywords are not functions
with gd we are looking into a bunch of libraries
we use a bunch of predefined functions
we dont have to write as much in c so we can build sooner than later
getval - function name
thing to left of get val is a return type
int getval (int top, int bottom - parameters - external bits of information that we can send or pass into the function
get val passing by value
x = getval(u,l)
its taking the contents of u and putting them in top
they are not the same variable
they are seperate
its just at this point they have the same value
they dont reference the same memory location so they are seperate from eachother in almost every way with no way of causing conflicts or affecting each other beyond the starting point
c does passing by address
value vs reference
lets say we wanted to pass top by address, we need to communicate the memory address using pointers
if we made top a pointer in our function, we need to update our prototype to be an intiger pointer
if we do memory references then they change together
return a array char* to return
gd is an api like an android dev kit
October 9th, 2013
Compiling
WIKI DOESNT LIKE MY CODE
this program is over 800 lines after all the preprocessing
it converts it to assembly language
complex code could end up compiling slower than longer code
its what you do, second is how much is there
Limits
c code is portable but it has its limits
opening a file on windows is different than on unix
if you have a symble defined
some symbols exist on the different systems only
P.P.D.
#include - inserts the files contents into your file
#define
# fdef
#fndef
#fndef
#endif
gcc -E hello.c |less shows all of the PPDs
cd /usr/include ~ locations of all header files - system header directory
it prevents the file from being included multiple times
struct _IO_FILE; - global variable . everything can see it
possics compliant code - can check for it and run if it is
variable arguement - … - write functions that take as many arguements as you want
gcc -S first.c
Structs
struct - is a container variable except its different than an array but it can have different types
io file is a type of struct
every time you want to use an io struct you have to type struct and io
typedef struct _IO_FILE FILE; - sets up an alias so that every time we type file, we get the other line
struct is programable datatype
FILE *out; - out is a file pointer
Closing
It was interesting to see just how long a code is after adding in the headerfiles
October 11th, 2013
Today was the knowledge assessment. It was a little difficult at first, but when I really read the problems, I figured them out. Except the last one that blew my mind. A time based RNG
October 16th, 2013
Object oriented and C
object oriented program is just code organization and techniques you inflict on your code
in C++ programming you take on the role of a manager and you manage your code
up to this point we have been playing the role of the end developer we write from the ground up
this role is still valid and has to be filled still
people have to make subroutines
object oriented makes managing these individual tasks easier to manage
we can continue to be the end devs but wrapping in C++ around it
with C++ you really dont write a C++ program, you outline a C program with C++ syntax
Arrays vs structs
arrays - are homogonous datatypes - means all the same type - many - every element must be the same- if an int every must be int - reference one name mulltiple values
structs - or stuctures - heterogenous type - meaning they dont have to be the same, only have to be the same if you want them to be the same - reference one name - struct could contain any comibation of anuthing
struct you have to identify it with the word struct
struct thing {
int a;
int b[20];
float c;
int d;
short int e;
}; ~ one of the few times you need a semi colon after a closing bracket in C
struct thing stuff; ~ one thing from struct "thing" and we named it stuff
stuff.a =12;
stuff.b[ j ]='A'; ~
#include <stdio.h>
int main( )
{
int i,j,k;
struct person {
char name [24];
char age;
float height;
};
typedef struct person ID;
ID db [4];
for (i=0; i<4; i++)
{
printf("Entry [%d] name : ");
scanf("%s",ID[i].name);
printf("age");
scanf("%hhu",&(ID[i]age));
printf("height : ");
scanf ("%f",&(ID[i]height));
}
//print it all back out
return(0);
}
Thoughts
Structs have me at a loss, but I am sure I will know them soon enough
October 18th, 2013
C plus plus
in c you use gcc
c++ you use g++
.c for c files
.cc .cpp .c++ .C for c++
first C++ program
1 #include <stdio.h>
2 int main ( )
3 {
4 printf("Hello, world!\m");
5 return (0);
6 }
most of the time all valid c code is valid c++ code
pretty much all of c is in c++
some of c is not included
void * is not in c++
all of our datatypes are still there
with c++ we gain a few structs
g++ -o helloplus hello.cc
#include <cstdio> prefered c++ way of adding headerfiles
struct
class ~ the thing we define such a struct
object ~ int a ~ int class and a is object ~
classes have access control. allow or prohibit how people access parts of our data
public: functions or variables we wish for people to have access to
functions that are public that give you assess - assessor methods - method is fancy name for function
constructor - class name no type with any peramiters
in c you cant have two functions by the same name but in c ++ you can
contructor is a special kind of function. every class can have one. dont have to have one. whati t does is let you run code upon extantionation
private only accesavble to class
October 23rd, 2013
Program with classes
today we wrote a program with classes and structs to it dealing with the sides of a shape and then outputting them
Class square {
public
square( );
void setside(int);
int getside( );
int area( );
int perimeter( );
private
int x;
};
square :: square( )
{
x=0;
}
void square :: setside(int side)
{
x=side;
}
int square :: getside( )
{
return(x);
}
int square :: area( )
{
return(X * X);
}
int square :: perimeter( )
{
return( 4 * x );
}
int main ( )
{
square s1;
square s2;
s1.setside(4);
s2.setside(12);
printf("s1's side is %d\n", s1.getside( ));
printf("s1's area is %d\n", s1.area( ));
printf("s1's perimeter is %d\n", s1.perimeter( ));
return(0);
}
October 25th, 2013
what if we had an array
we have to create our own addition multiplication if we break it out
we get to implement our own datatype
we start by writing a header-file
as we model this there are a few things at play
the length of the number
what do we want to represent in our bignum
we can control how big we want it to be
the other is that we can determine if its positive or negative
the third is the base that we want to apply to it
we could do a base of anything 17 18 or even the base 10 system that we are so accustom to using in our every day life
bignum.h
#ifndef _BIGNUM_H
#define _BIGNUM_H
class BigNum {
public:
BigNum( );
BigNum(unsigned int);
unsigned char getbase( );
unsigned char getlength( );
unsigned char getsign( );
void SetBase (unsigned char);
void SetLength (unsigned char);
void SetSign (unsigned char);
void zero( );
void print ( );
private:
unsigned char base;
unsigned char Length;
unsigned char sign;
unsigned char *data;
October 30th and November 1st, 2013
This week we continued work on our program, but this week we added the ability to increment our numbers.
we read our numbers from left to right
we have an issue of implementation with storage. do we want to store it from right to left or from left to right
we read from left to right currently
December 11th, 2013
Tape
I finally was able to get tape to work
Storage.h
#ifndef _STORAGE_H
#define _STORAGE_H
using namespace std;
class storage
{
public:
storage();
int getCapacity();
int getFree();
int getUsed();
protected:
int load();
void store(int);
bool pos(int);
private:
int data[256];
int used;
int available;
int loc;
};
#endif
Storage.cc
#include "storage.h"
#include <iostream>
storage :: storage()
{
int i;
used = 0;
available = 255;
for (i = 0; i < 256; i++)
data[i] = 0;
loc = 0;
}
int storage :: getCapacity()
{
return used + available + 1;
}
int storage :: getFree()
{
return available + 1;
}
int storage :: getUsed()
{
return used;
}
int storage :: load()
{
return data[loc];
}
void storage :: store(int value)
{
if (used < 255)
{
data[loc] = value;
used++;
available--;
}
else
cout << "Error! Out of space!" << endl;
if (value == 0)
{
used--;
available++;
if(used > 255)
used = 255;
if(used < 0)
used = 0;
if(available > 255)
available = 255;
if(available < 0)
available = 0;
}
}
bool storage :: pos(int location)
{
bool retval = true;
if ((location >= 0) && (location <= 255))
loc = location;
else
retval = false;
return retval;
Tape.h
#ifndef _TAPE_H
#define _TAPE_H
#include <iostream>
#include "storage.h"
class tape : public storage
{
public:
tape();
int read();
void write(int);
void forward();
void backward();
void rewind();
void setlabel(string);
string getlabel();
int getpos();
private:
string label;
int position;
};
#endif
Tape.cc
#include "storage.h"
#include "tape.h"
#include <cstdio>
tape::tape()
{
position=0;
pos(position);
label="TapeYo";
}
int tape::read()
{
return(load());
}
void tape::write(int num)
{
store(num);
}
void tape::forward()
{
if (position==255)
{
printf("You have reached the end of the tape!\n");
position--;
pos(position);
}
else
{
position++;
if (position==255)
{
printf("You have reached the end of the tape!\n");
position--;
pos(position);
}
}
}
void tape::backward()
{
if (position==0)
{
printf("You have reached the end of the tape!!\n");
position++;
pos(position);
}
else
{
position--;
if (position==0)
{
printf("You have reached the end of the tape!\n");
position++;
pos(position);
}
}
}
void tape::rewind()
{
while(position!=0)
{
position--;
}
pos(position);
}
void tape::setlabel(string labelstr)
{
label=labelstr;
}
string tape::getlabel()
{
return(label);
}
int tape::getpos()
{
return(position);
}
Main.cc
#include <cstdio>
#include "tape.h"
#include <iostream>
using namespace std;
int main()
{
tape t;
char choice;
int tapeinputval;
while(choice!=113)
{
printf ("\n================================================\n");
printf ("The Tape Is Currently At Position ");
cout << t.getpos();
printf ("\n\n");
printf ("Please Choose A Command For The Tape To Take\n\n");
printf ("f = move the tape forward\n");
printf ("b = move the tape backward\n");
printf ("r = rewind the tape\n");
printf ("e = read what is stored at current position\n");
printf ("w = write at current position\n\n");
printf ("Use q to quit\n");
printf ("================================================\n");
cin >> choice;
printf ("\n");
switch(choice)
{
case 102:
t.forward();
printf ("The Tape Has Moved To Position ");
cout << t.getpos();
printf ("\n");
break;
case 98:
t.backward();
printf ("The Tape Has Moved To Position ");
cout << t.getpos();
printf ("\n");
break;
case 114:
t.rewind();
printf ("The Tape Has Moved To Position ");
cout << t.getpos();
printf ("\n");
break;
case 101:
printf ("The Tape Is Currently At Position ");
cout << t.getpos();
printf (" and stored here is ");
cout << t.read();
printf ("\n");
break;
case 119:
printf ("Please enter a value to store at current position \n");
cin >> tapeinputval;
t.write(tapeinputval);
printf ("\nThis position now stores the value ");
cout << t.read();
break;
case 113:
return(0);
}
}
}
December 12th, 2013
Big Num
I managed to get increment and decrement to work. From these two things I can do almost anything
Base.cc
#include "bignum.h"
unsigned char BigNum::getBase()
{
return(base);
}
void BigNum::setBase(unsigned char base)
{
this -> base = base;
}
Bignum.h
#ifndef _BIGNUM_H
#define _BIGNUM_H
class BigNum
{
public:
BigNum();
BigNum(unsigned char);
unsigned char getBase();
unsigned char getLength();
unsigned char getSign();
void setBase(unsigned char);
void setLength(unsigned char);
void setSign(unsigned char);
void zero();
void print();
void increment();
void decrement();
private:
unsigned char base;
unsigned char length;
unsigned char sign;
unsigned char *data;
};
#endif
Length
#include "bignum.h"
unsigned char BigNum::getLength()
{
return(length);
}
void BigNum::setLength(unsigned char length)
{
this -> length = length;
}
Print.cc
#include "bignum.h"
#include <cstdio>
void BigNum::print()
{
int i;
for(i=0; i<length; i++)
{
printf("%d", *(data+i));
}
printf("\n");
}
Sign.cc
#include "bignum.h"
unsigned char BigNum::getSign()
{
return(sign);
}
void BigNum::setSign(unsigned char sign)
{
this -> sign = sign;
}
Zero
#include "bignum.h"
void BigNum::zero()
{
for(int i=0;i<length;i++)
{
*(data+i)=0;
}
}
create.cc
#include <cstdlib>
#include <cstdio>
#include "bignum.h"
BigNum::BigNum()
{
length = 8;
base = 10;
sign = 0;
data = (unsigned char*)malloc(sizeof(char)*length);
this -> zero();
}
BigNum::BigNum(unsigned char length)
{
this -> length = length;
base = 10;
sign = 0;
data = (unsigned char*)malloc(sizeof(char)*this -> length);
this -> zero();
}
increment.cc
void BigNum::increment()
{
char carryvalue=1;
{
for(int i=0;i<length;i++)
{
char endresult = *(data+(length-1)-i);
char addedvalue = endresult + carryvalue;
if ((addedvalue > 9) && ((addedvalue%10)==0))
{
addedvalue = 0;
carryvalue = 1;
}
else
{
carryvalue = 0;
}
*(data+(length-1)-i) = addedvalue;
}
}
}
decrement.cc
void BigNum::decrement()
{
char carryvalue=1;
{
for(int i=0;i<(length-1);i++)
{
char endresult = *(data+(length-1)-i);
char subtractedvalue = endresult - carryvalue;
if ((endresult <= 0) && (carryvalue == 1))
{
subtractedvalue = 9;
carryvalue = 1;
}
else
{
carryvalue = 0;
}
*(data+(length-1)-i) = subtractedvalue;
}
}
}
main.cc
Division is not done yet, but it is a work in progress.
#include "bignum.h"
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cstdio>
using namespace std;
int main()
{
int choice;
printf("\n\n================================================================\n");
printf( "How would you like to increment or decrement a number?\n");
printf( "\n0 - Subtraction");
printf( "\n1 - Addition");
printf( "\n2 - Multiplication");
printf( "\n3 - Division !! NOT WORKING - WORK IN PROGRESS !!\n\n"); // work in progress
printf( "Your Choice is :");
cin >> choice;
BigNum num;
num.setBase(10);
int i,x;
int loop1,loop2;
int loop3,loop4;
int loop5,loop6;
int loop7,loop8;
int sub1,sub2;
int div1,div2;
int z,w;
{
if (choice ==3)
{
printf ("================================================================\n");
printf ("\nDivision Mode\n");
printf ("\nEnter Your First Number: ");
cin >> div1;
printf ("Enter Your Second Number: ");
cin >> div2;
printf ("\n================================================================\n");
{
if (div1 > div2)
{
loop7=div1;
loop8=div2;
{
for(i=0;i<=loop7;i+=loop8);
{
num.increment()
}
//other division stuff not done
num.print();
}
}
else
{
loop7=div2;
loop8=div1;
{
for(i=0;i<=loop7;i+=loop8);
{
num.increment();
}
//other division stuff not done
}
num.print();
}
}
}
else if (choice == 2)
{
printf ("================================================================\n");
printf ("\nMultiplication Mode\n");
printf ("\nEnter Your First Number: ");
cin >> loop5;
printf ("Enter Your Second Number: ");
cin >> loop6;
printf ("\n================================================================\n");
{
for(i=0;i<loop5;i++)
{
for(x=0;x<loop6;x++)
{
num.increment();
}
}
}
num.print();
}
else if (choice == 1)
{
printf ("================================================================\n");
printf ("\nAddition Mode\n");
printf ("\nEnter Your First Number: ");
cin >> loop1;
printf ("Enter Your Second Number: ");
cin >> loop2;
printf ("\n================================================================\n");
{
for(i=0;i<loop1;i++)
{
num.increment();
}
for(i=0;i<loop2;i++)
{
num.increment();
}
}
num.print();
}
else
{
printf ("================================================================\n");
printf ("\nSubtraction Mode - Largest of The Two Numbers Sorted As Minuend\n");
printf ("\nEnter Your First Number: ");
cin >> sub1;
printf ("Enter Your Second Number: ");
cin >> sub2;
printf ("\n================================================================\n");
{
if (sub1 > sub2)
{
loop3=sub1;
loop4=sub2;
{
for(i=0;i<loop3;i++)
{
num.increment();
}
for(i=0;i<loop4;i++)
{
num.decrement();
}
}
num.print();
}
else
{
loop3=sub2;
loop4=sub1;
{
for(i=0;i<loop3;i++)
{
num.increment();
}
for(i=0;i<loop4;i++)
{
num.decrement();
}
}
num.print();
}
}
}
}
return(0);
}
December 13th, 2013
UNIX/Linux Fundamentals Lecture Journal
August 28th, 2013
First Day of Class
Class Websites
An important thing introduced to the class today was the class website.
This page is important because it contains all the tasks for the semester, and it serves as a central hub for all notes in the class.
Joining IRC Server
The lab46 server has an
IRC server ~ great for collaboration and for messing around
Log onto a terminal
SSH Lab46 or lab46.corning-cc.edu if out of lab
screen
irssi
/server irc
/join csci
/join unix
screen -r is used to rejoin the chat after leaving
ctrl A + D leaves the chat system and returns you to home
screen -ls tells you about your current screen
alt + number to switch irc servers
Challenges
August 30th, 2013
UNIX
UNIX is a Philosophy
Small is beautiful ~ do more with less ~ hardware doesn't need to be that strong to run Linux or UNIX mostly UNIX cause of the old computers only running on a few kb of ram
do one thing and do that one thing extremely well ~ example LS what does LS do it lists files extremely well ~ which is what it was designed to do. cant copy files or do anything other than what it was designed to d
everything is a file in a UNIX system ( only about 90% true ) UNIX introduced the concept of io streams or data streams
IO STREAMS
Standard input STDIN
standard output STDOUT
standard error STDER
IO redirection
> redirect stdout and turn it into a write operation. write operation starts at the beginning of the file and writes on the next available lines
» redirect stdout and append the file with a write operation.
2> redirect standard error Write
2» redirect standard error append
< redirects standard input
File Control
lab46:~$ cat "myfilename"
Shortcuts and Commands
lab46:~$ morse < "file name"
CP ~ short for copy file creates a duplicate EXAMPLE ~ (cp thing stuff creates a copy of thing and names it stuff)
MV ~ moves the file file is no longer where it was. moves file to same directory under different name if wished. UNIX does not have a rename command because of the redundancy in it
RM ~ rm filename ( removes the file that is listed after RM) rm - i defaults with a prompt making sure that you want to delete the file ,can override with -f force, rm -rf deletes a directory even with stuff rf means recursive goes deeper until its all gone rm -rf * would delete all directories because * is a wildcard
LN ~ creates shortcuts to files ln -s filename1 filename2 makes a shortcut of filename1 named filename2 and without -s makes it a semi replication
ls -l ~ long list of things in directory
diff ~ shows differences between files
touch “filename” ~ makes a file
Thoughts and closure
Shortcuts and commands really make navigating UNIX a lot easier.
A lot of this raises the question “ why should we do something when the computer can do it for us?”
It also makes us ask “at what point do we stop doing the manual labor?”
September 4th, 2013
programming languages are lower level than the shell.
lower the level the more control you can have over the details, but the more you have to do by hands.
Higher level the less control you have but you have to do less
UNIX Shell Control
Commands
pwn ~ shows the current directory that the user is in
$USER ~ shows the current user that you are logged in with
$ ~ stands for variable expansion does its best to show the contents of a variable
Example :
stuff=“things”
echo $stuff
you get “things” displayed
LS Coloration
When you use the command LS, you get multiple colored results.
These colors each represent a different type of file.
The Defaults are as follows
blue - directory files
cyan - light blue - symbolic link
red - broken symbolic link - or - compressed files
magenta - bright purple - media files
green - executable file
yellow - special ( device ) file such as keyboard or mouse
white foreground and red background - set uid set gid file
Navigational Activity
lab46:~$ pwd
lab46:~$ mkdir closet
lab46:~$ cd closet
lab46:~/closet$
Type in pwd again, and the path listed would have been appended to your new location
This leads into two types of paths
absolute path - contains the entire addresses
relative path - contains a character or shorter name to represent the path to location of file or user
lab46:~/closet$ touch skeleton
Using ls, there should now be a file named skeleton in the closet
Next we will create a file named cake, but we will use echo to create the file and content
lab46:~/closet$ echo "ingredients" > cake
This creates a file named cake with the word ingredients in it
To add to the file without removing all content, we must replace > with » a
lab46:~/closet$ echo "diamond pickaxe" >> cake
File Properties
ls -l - lists all files
la -la ~ addition of “a” includes hidden files in the listing of files
every directory has a “.” and a “..” in it
shift and \ is a | or a pipe character. it merges commands or settings together
ls -l | less ~ lists the list in a paging format
ls -l | more ~ lists the list without the ability to search or go up
tty
ldd ~ print dependencies
mesg ~ using an n or a y toggles the settings for whether or not messages can be sent
Permissions
Every file has permission settings
After an ls -la, you can see what type of file a file is, and who controls it
- ordinary file
L - symbolic link
Bc - block and character
S - socket
p - pipe
The second third and forth spot represents user permission and owner
The fifth sixth and seventh spot represents the group the file belongs to
The eighth ninth and tenth spot represent the permissions of the world, or global environment
These are followed by
followed by name of owner
followed by group ownership
r ~ read - 4
w ~ write - 2
x ~ execute except for a directory that means its searchable - 1
- ~ no permission - 0
t ~ sticky bit add on for file permissions you can write but cant delete
s ~
Directory Structure
Default Directories
/ ~ directory known as root directory
bin ~ directory means binary essential files for basic system usage
dev ~ directory for devices or special files
etc ~ system configuration files such as ldap ntp
lib ~ libraries such as the c library at libc.so.6
lib64 ~ links to lib directory
lib32 ~ separate 32bit layer library considered foreign
root ~ root users home directory
lost+found ~ recovered files from a disk rarely used only when there is a serious hardware problem
mnt ~ mount point for storage or media
media ~ same as mnt
opt ~ optional software or commercial vendors
proc ~ information on running processes ~ has a directory for every running process
sbin ~ essential tool for administrator
selinux ~ security Linux extension
sys ~ modern replacement of proc machine readable instead of user readable. easier for machine to reach
tmp ~ TEMP FILES
var ~ variety of things that fit nowhere else such as mail from lab 46
usr ~ provides usr useful stuff not critical for operation, place for text editors ~ local/bin contains mods
file categories
regular ordinary files ( text files mp3s movies)
directory files / link files (is a file that contains other files or reference other files)
special files
Thoughts on the day
We learned a lot about how the subsystem in linux and unix works
Knowing what the default directories were, really helped to draw a parallel to the windows environment
With the lecture I was finally able to understand the meaning of chmod 777 that I use ever so much in my daily time. I know it is now read write and execute for all users. I feel silly for not knowing that.
September 6th, 2013
Shell
OS Specifics
-
Some of the OSes have the same kind of shell
Some of the OSes have a different shell
It is good as a computer personal to familiarize with most of them
mac - finder
unix - bash sh tosh csh zsh rc fish ksh ~ change shell with chsh
windows - explorer
Nesting
Nesting is opening something within something that can be opened within that nearly indefinitely
You can nest the shell bash many times over
if you type bash in bash it becomes nested
-bash
|_bash
|_bash
|_bash
Output Manipulation
“ ~ half quite, allows variable expansion
' ~ full quote, literal quote offering no expansion - gives back exactly what you typed
` ~ back tick back-quote - allow command expansion
my example will not work in wiki syntax and crashes my opus upon saving
This embeds the results of a command string right into the output syntax
Knowing how to do these can really help with controlling output
There are other special things you can use to manipulate the data output
\ “whack” - toggle special meaning of the following character ex \n newline \t tab
“date” gives back date
* means 0 or more of anything
? means 1 of any character
[ ] character class put sequence of characters in it ~ matches all enclosed
[^ ] inverted character class ~ matches none enclosed
lab46:~$ ls ????
Thoughts
Knowing how to control the output is an amazing ability, I Just think i will struggle with remembering which one does what
I also know that after working with unix in cli, switching back to windows is going to be a challenge
September 11th, 2013
Today we learned about VI
Vi
VI / VIM - it does things extremely well. it is a good text editor
ed - line editor edit your file a line at a time
One of the first application of UNIX was a text editor for a secretary
The need for a visual editor was what birthed VI
Bill joy - created vi
came up with the idea to allow every key on the keyboard to be a command
Key can be used for commands and can be used for input. it has two commands
1: COMMAND MODE ~ what you start vi in
2: INPUT MODE → INSERT MODE
A and M are common between the qwerty and other keyboard styles
a and m both do things in both modes
VI Commands
these will even show up in the normal CLI with CTRL + value
sometimes case of character changes command
^ snaps you to begining of current line horizontal
$ is end of current line horizontal
G is end line vertically
x delete single character
u undo for line
X backspace
d$
d^
dd - deletes entire line
p pastes dd line below
P pastes dd line above
anything can be prefixed with a number to multiply the commands
anything can be prefixed with the letter c pops you in place of where command was issued
cc changes whole line
I takes you to insert at begining on line
a takes you insert after character
A takes you insert end of line
o inserts new line below current
O iinserts new line above current
u
U
yy copies without cutting
/ followed by something lets you search
: extended command mode
:.co+0 pastes at current location
:.co4
. MEANS CURRENT LINE
.+2m$ current line plus next two lines move to end of file
SOURCE COMMAND DESTINATION
:w is save
:q quit
:wq save and quit
:w filename saves as name
ZZ will only save an exit if you saved
:%s/e/EE/g
:set tabstop=4
syntax on
syntax off
set number
set nonumber
set cursor line
vi ~/vimrc to edit vi
Thoughts
Its nice to have learned a few new VI commands I didnt know before
September 13th, 2013
Bash
Today almost everything learned was pure bash
la -a shows all hidden files
.plan contains your plan
finger (user name) - gives your output
.signature your signature
.bashrc
PS1 changes your prompt appearance Example PS1='C:\\\w> ' makes it say C:\~>
cd and a few characters and pressing tab will complete the directory name for you
running old command !412
ctrl + r searches for commands
first line of shell script should always be the following
#!/bin/bash - this is called a shbang
bash scripting is basically executable pseudo code
We made two scripts
1 #!/bin/bash
2 #
3 # script1.sh - my first script
4 #
5 echo -n "What is your name?"
6 read name
7 echo "Hi, ${name} how are you?"
8 exit 0
This asks for your name and asks how you are
and
1 #!/bin/bash
2 #
3 # scipt2.sh - my second script
4 #
5 pick=$((RANDOM%91+1))
6 echo -n " Pick a number :"
7 read number
8 if [ "$pick" -eq "$number" ]; then
9 echo "you win"
10 elif [ "$pick" -gt "$number" ]; then
11 echo "$pick > $number you lose"
12 else
13 echo "$pick < $number you lose"
14 fi
15 exit 0
this one is a number game that has you guess a number
September 18th, 2013
Today we learned about how processes work
Process Termination
ctrl c generates a signal interrupt
ctrl d is mapped to the end of file character
end of file characters will exit a file
you can log out of a terminal by doing ctrl d
all your terminal session is, is an open file waiting for the end of file command to occur
-
The “kill” command will terminate a process
man kill - lists all of the 64 kill commands you can use
ctrl z pauses the process without actually stopping it
when you type “jobs” it lists the processes stopped
when you type sleep 3600& , it adds to the list of things in the jobs command
Background and Foreground Processes
multitasking - each login session that you have, you have a foreground and a background, running something at your prompt such as (vi) then vi is currently in the foreground
the unix system is called a multi-user multi-tasking operating system
some programs can be put and run in the background without using the foreground
we are limited to one foreground per loin session
we can put any number of things in the background granted that they don't require user interaction via a keyboard
1) stopped - in the background not doing anything, not working towards finis hing its process
2) running - means the job is running in the background perfectly fine
Each job has a number that is personal to itself called a PID
With the ps command, we can find out the PID number for something
With the PID number we can send something into the background
bg (job number) can move a thing to the background
fg (job number) can move a thing to the foreground
Some processes will not go into the background
you can not be running cat in the background because it requires interaction , and it instantly goes back to stopped once the terminal is not focused on it
screen the program that we are using for our irc server is actually tricking the system into having a multi-foreground environment
daemon is something that you can run in the background that is launched from the terminal then happily running along in the background without needing a terminal to input any information, usually involved in web-servers
daemons are also considered servers in the unix system
daemons end with the letter d
apache d more than likely the apache daemon
all a server means is that it is handling a piece of software that can handle requests
ctrl l refreshes your screen, and then you will only see what you put there cat is an actual program in our path that we can run
when we run cat once, that program running is called a process
a process is a program in action
We can time a program to run
Example
(sleep 30;ls)& runs ls after 30
Thoughts
Its nice seeing how processes work. I have dealt with daemons before, so I understand them well enough.
September 20th, 2013
Today we learned mostly about the cat command but we also learned about a few other things
General Stuff
I am going to list it all out since it doesnt really group at all
Regular Expressions - set of characters used to represent a pattern
Basic Regular expression- not garrented to be universal
. - match any single symbol
* - 0 or more of the previous
\< match start of word
\> match end of word
^ - match start of line
$ - match end of line
[ ] = match one of enclosed
[^ ] = do no match any of the enclosed
( ) =
| = logical or
Cat Commands
cat words |grep '….'|wc -l replace …. with search parameters
cat words |grep '^….$'|wc -l finds all 4 letter words
cat words |grep '^.[aeiouyAEIOUY]..$'|wc -l - find second character vowel
cat words |grep '…..e$'|wc -l - six or more ending in e
cat words |grep '^……*e$'|wc -l - six or more ending in e
cat words |grep '^[sS].*[mM].*[eE]$'|wc -l - word starting in S, ending in E, m in the middl
cat words |grep '^.*[aeiouy][aeiouy].*$'|wc -l - two or mor
cat words |egrep 'ed$|ing$' |wc -l - ends in ed or ing
cat words |egrep '^pre|^pro|ly$' |wc -l - begins with pre or pro or ends in ly
Thoughts
its fun looking at the dictionary and playing with cat
September 25th, 2013
Cli Scripting
for ((i=0;i<10;i++));do
> echo"$i"
> done
first part is the starting point
second part is do as long as
third part is how you get to the end
the double parenthesis allow for multiple levels of arithmetic
XTE
xte - part of a tools suite called xautomation
With XTE we can create scripts that move the mouse, click, and do keystrokes
Example
xte 'mousemove 0 0'
xte 'sleep 1'
xte 'mouseclick 1'
xte 'mousedown 1'
xte 'sleep 1'
xte 'mousemove 100 100'
xte 'sleep 1'
xte 'mouseup 1'
xte 'mousemove 300 250'
xte 'sleep 1'
xte 'mouseclick 1'
1 xte 'mousemove 0 0'
2 xte 'sleep 1'
3 xte 'mouseclick 1'
4 xte 'mousedown 1'
5 xte 'sleep 1'
6 xte 'mousemove 100 100'
7 xte 'sleep 1'
8 xte 'mouseup 1'
9 xte 'mousemove 300 250'
10 xte 'sleep 1'
11 xte 'mouseclick 1'
12 xte 'sleep 1'
13 xte 'mousemove 40 110'
14 xte 'sleep 1'
15 xte 'mouseclick 1'
16 xte 'sleep 1'
17 xte 'mousemove 40 130'
18 xte 'mouseclick 1'
19 xte 'sleep 1'
20 xte 'mousemove 600 110'
21 xte 'mouseclick 1'
22 xte 'mousemove 200 200'
23 xte 'mouseclick 1'
24 xte 'mousedown 1'
25 for ((x=200;x<500;x+=50));do
26 y=200;
27 xte "mousemove $x $y"
28 xte "usleep 200000"
29 done
30
31 for ((y=200;y<500;y+=50));do
32 x=500;
33 xte "mousemove $x $y"
34 xte "usleep 200000"
35 done
36
37 for ((x=500;x>190;x-=50));do
38 y=500;
39 xte "mousemove $x $y"
40 xte "usleep 200000"
41 done
42
43 for ((y=500;y>190;y-=50));do
44 x=200;
45 xte "mousemove $x $y"
46 xte "usleep 200000"
47 done
48 xte "mouseup 1"
Thoughts
Xte is fun and I could see many good, and bad uses for it for torturing my clients
September 27th, 2013
Today we created a program that opens xpaint and draws something specific
I chose to draw a battle scene from pokemon using xpaint
so far I only have the frame drawn from the picture
1 xte 'mousemove 200 200'
2 xte 'mouseclick 1'
3 xte 'mousedown 1'
4 for ((x=200;x<360;x+=10));do
5 y=200;
6 xte "mousemove $x $y"
7 xte "usleep 10000"
8 done
9
10 for ((y=200;y<344;y+=4));do
11 x=360;
12 xte "mousemove $x $y"
13 xte "usleep 10000"
14 done
15
16 for ((x=360;x>200;x-=10));do
17 y=344;
18 xte "mousemove $x $y"
19 xte "usleep 10000"
20 done
21
22 for ((y=344;y>196;y-=4));do
23 x=200;
24 xte "mousemove $x $y"
25 xte "usleep 10000"
26 done
27 xte "mouseup 1"
28
29 for ((x=350;x>209;x-=10));do
30 y=340;
31 xte "mousemove $x $y"
32 xte "mousedown 1"
33 xte "usleep 10000"
34 done
35 xte "mouseup 1"
36
37 for ((x=350;x>209;x-=10));do
38 y=339
39 xte "mousemove $x $y"
40 xte "mousedown 1"
41 xte "usleep 10000"
42 done
43 xte "mouseup 1"
44
45 for ((x=350;x>209;x-=10));do
46 y=337
47 xte "mousemove $x $y"
48 xte "mousedown 1"
49 xte "usleep 10000"
50 done
51 xte "mouseup 1"
52
53 for ((y=335;y>302;y-=1));do
54 x=211
55 xte "mousemove $x $y"
56 xte "mousedown 1"
57 xte "usleep 10000"
58 done
59 xte "mouseup 1"
60
61 for ((y=335;y>302;y-=1));do
62 x=210
63 xte "mousemove $x $y"
64 xte "mousedown 1"
65 xte "usleep 10000"
66 done
67 xte "mouseup 1"
68
69 for ((y=335;y>302;y-=1));do
70 x=208
71 xte "mousemove $x $y"
72 xte "mousedown 1"
73 xte "usleep 10000"
74 done
75 xte "mouseup 1"
76
77 for ((y=335;y>302;y-=1));do
78 x=349
79 xte "mousemove $x $y"
80 xte "mousedown 1"
81 xte "usleep 10000"
82 done
83 xte "mouseup 1"
84
85 for ((y=335;y>302;y-=1));do
86 x=350
87 xte "mousemove $x $y"
88 xte "mousedown 1"
89 xte "usleep 10000"
90 done
91 xte "mouseup 1"
92
93 for ((y=335;y>302;y-=1));do
94 x=352
95 xte "mousemove $x $y"
96 xte "mousedown 1"
97 xte "usleep 10000"
98 done
99 xte "mouseup 1"
100
101 for ((x=350;x>209;x-=10));do
102 y=300
103 xte "mousemove $x $y"
104 xte "mousedown 1"
105 xte "usleep 10000"
106 done
107
108 for ((x=350;x>209;x-=10));do
109 y=299
110 xte "mousemove $x $y"
111 xte "usleep 10000"
112 done
113 xte "mouseup 1"
114
115 for ((x=342;x>268;x-=1));do
116 y=290
117 xte "mousemove $x $y"
118 xte "mousedown 1"
119 xte "usleep 10000"
120 done
121 xte "mouseup 1"
122
123 for ((x=271;x<275;x+=1));do
124 y=289
125 xte "mousemove $x $y"
126 xte "mousedown 1"
127 xte "usleep 10000"
128 done
129 xte "mouseup 1"
130
131 for ((x=273;x<275;x+=1));do
132 y=288
133 xte "mousemove $x $y"
134 xte "mousedown 1"
135 xte "usleep 10000"
136 done
137 xte "mouseup 1"
138
139 for ((y=290;y>278;y-=1));do
140 x=342
141 xte "mousemove $x $y"
142 xte "mousedown 1"
143 xte "usleep 10000"
144 done
145 xte "mouseup 1"
October 2nd, 2013
Arrays
What if we only had one value that we could call with one subscript value
they are commonly subscripted with the [ ] brackets
some languages may start at one and some languages start at 0
bash like c programming starts at z
first value would be [0]
second would be [1]
third would be [2]
you can have a common name to each value
so
name[0]
name[1]
name[2]
Loops
for((i=0; i<12; i++)); do
echo -n "Enter scores:"
read score
battleexp[$i]=$score
done
total=0
for((i=0; i<12;i++)); do
let total = $total + ${battleexp[$i]}
done
"Your total score is $total"
October 4th, 2013
Scripts vs programs
differences between scripts and programs
interperated - interperates each line as it goes
html
bash
wbscript
php
python
javascript
compiled - everything is translated upfront so that the computer can understand it
c
c++
pascal
fortran
bopl changed to b and that changed to c
source code portability to make up for the inability to have things ready for all devices
the compiled product can not be moved to the device but the source code can be compiled onto the new device
ascii ebcdic
hardware choices dwindled after the 90s
cellphones and tablets brought back into competition the diversity
with a c compiler you do not have to have any realization of differences just re compile
low level - assembly and machine code
high level - java c++ python
the higher the level, the less you get to interact with the hardware
in c you have # include <stdio.h>
its a preproccessing directive
its a step c goes through
it does work before it processes the syntax
grabs the file and takes it contents and dumps them right into our file
c is terminated with a semi colon
#include <stdio.h>
int main ()
{
printf(“Hello World'\n”);
return(0);
}
Thoughts
This is all review from C programming
October 9th, 2013
October 11th, 2013
Today was the knowledge assessment, it was fairly simple other than the last problem. The problem where we were asked to make the brute program work.
October 16th and 18th 2013
This week we worked on some bash scripts for checking if a directory exists
1 #!/bin/bash
2 #
3 #
4 #
5 #
6 #
7 if [ -z "$1" ]; then
8 echo -n "Enter a path: "
9 read path
10 chk=`ls $path 2>&1 | grep 'No such file'| wc -l`
11 if [ "$chk" -eq 1 ]; then
12 path=`pwd`
13 fi
14 else
15 paths="$1"
16 fi
17 echo $path
18 cd $path
19 max=0
20 for file in `ls -1d` * ; do
21 c=`echo $file | wc -c`
22 echo "c is $c"
23 data[$c]=$((${data[$c]}+1))
24 if [ "$max" -lt "$c" ]; then
25 max=$c
26 fi
27 done
28 for (( i=1; i<=$max; i++));do
29 printf "%2d | " $i
30 if [ -z "${data[$i]}" ]; then
31 data[$i]=0
32 fi
33 for ((j=0;j<${data[$i]};j++)); do
34 echo -n "*"
35 done
36 done
October 23rd, 2013
Today we created a script that would run a simple website using our UID as a port number
#/bin/bash
#
while true; do
{ echo -e 'HTTP/1.1 200 OK \r\n'; cat /etc/motd;} | nc -l 5836
done
We also learned about the different protocols on the internet and about error codes
October 25th, 2013
Today we learned how to cat a file, but to organize the output in a readable manner, or however we want it to be organized
some examples
cat file | grep "<th class="ddtitle'
sed stream editor
cat winter2014-20131025.html | grep '^<th class="ddtitle' | sed 's/^<th class="ddtitle.*crn_in=.....">//g' | sed 's/<\/a><\/th>//g'
cat winter2014-20131025.html | grep '^<th class="ddtitle' | sed 's/^<th class="ddtitle.*crn_in=.....">//g' | sed 's/<\/a><\/th>//g' | sed 's/^\(.*\) - \(.....\) - \(.*\) - \(...\)$/\2:\3-\4:\1/g'
October 30th and November 1st, 2013
This week we continued to work on cating the course list file.
We were given a small script to mess around with
ifs=; for line in `cat consolodate`; do
crn=`echo $line | sed 's/^.* - \(.....\) - .....*$/\1/g'
touch $crn
echo $line >> $crm
done
we learned about ifs internal field separator
we were also given
cat catstuff | enhance | enhance | ENHANCE > coursedata
December 13th, 2013
UNIX/Linux Fundamentals Case Study Journal
Case Study 0x1: Archive Handling
1)
From the archives/ subdirectory of the UNIX public directory (/var/public/unix/archives):
a) Copy the archive1.tar.gz and archive2.zip files to your home directory.
b) i did this with cp -r /var/public/unix/archives .
2)
to open the files tar and zip files
a) zip uses unzip command
b) tar uses tar xvzf for tar.gz
c) found the information in the man page
3) tar -cf arc.tar archives
4) gzip -9 tar
5) they are different
a) zip compresses and organizes into a single file
b) tar organizes into a single file and gzip compresses a single file
things make more sense now
Case Study 0x3: The Puzzle Box
1.
b the file seems to be a simple text file
c when catting the file it seems to be a text file
d the file is now a gzip compressed file
e the file is now a max compression file
2.
it doesnt appear to be a text file
the file is actually a tar file
cp unix.text /var/public/unix/file/submit/$USER-file.txt && echo “Success”
cat unix.text | mail -s ”[CS: FILE]“ wedge@lab46.corning-cc.edu $USER
The people that talked to me are aforce2 lwall1
Jkosty has messages disabled. Write write you have write permissions turned off
Waiting for a connection. Can join peoples invites
Aforce2 and lwall1
You can open a shell using esc
Case Study 0x5: Web Pages
Case Study 0x6: Device Files
1
BLOCK DEVICES
xvda1
xvda2
xvda3
character devices
vcs
vcs1
vcsa
2
3
4
5
6
7
Case Study 0x7: Scheduled Tasks
Case Study 0x8: Data Types in C
1
2
3
4
A 4294967295
B yea it was the max value for unsigned int
C -1 is the value
D I did because signed can go negative
6 the result is the before number being the max and the after being the least
It does make sense since the range is -32768 to 32767. It rolls over to the lowest value after adding one to the maximum value
1 #include <stdio.h>
2
3 int main()
4 {
5 unsigned int a, x;
6 signed short int b, y;
7
8 a = 0; // zero not letter "O"
9 b = 32767;
10 x = a - 1;
11 y = b + 1;
12
13 printf("signed short int before: %hd \t after: %hd\n", b, y);
14
15 return(0);
16 }
Case Study 0x9: Fun with grep
B cat pelopwar.txt | grep coast | wc –l causes 9 matches
Case Study 0xA: Data Manipulation
Copying
We can copy from source to destination using dd command
Doing this created a near duplicate file.
The permissions are different
The owner is different
The size is the same
The output is identical
Comparisons
We can compare files line by line using the diff command
md5sum(1): computes an MD5 hash of a file's contents, creating a unique data fingerprint
Case Study 0xB: Groups and Security
UNIX/Linux Fundamentals Lab Journal
Lab 0x0: Introduction to UNIX/Linux and Lab46
UNIX Facts
History
Originally developed by Bell Labs
From the 1970s
Many companies are switching to a UNIX system to save money
Many large and important fields ( Such as Space Exploration ) use UNIX
General Function
Word
word
wOrD
wOrd
User names on UNIX are normally lower case
passwords contain any number of combinations of letters, numbers, and symbols
Connecting To The Server
login as :
password :
MOTD
__ _ _ _ __ . . . . . . . . . . . . . . . . . . . . . . . . .
| | __ _| |__ / | |_/ / . 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 .
.. . . . . . . . . . ..
Unix Location
The default directory prompt is ”~“
This symbol actually represents a real directory on the system
Using the PWD command we get ( with my log on )
lab46:~$ pwd
/home/jkosty6
Unix Navigation
lab46:~$ cd src
lab46:~/src$
lab46:~/src$ pwd
/home/jkosty6/src
lab46:~/src$ cd ..
lab46:~$
lab46:~$ cd ..
lab46:/home$
Listing
lab46:~$ ls
Desktop Downloads Music Public Videos bin hw src
Documents Maildir Pictures Templates a.out closet public_html
Creating
lab46:~$ mkdir temp
lab46:~$ mkdir bin
lab46:~$ rmdir temp
People On The System
lab46:~$ who
This lists out all active logons
You can message any of the people online, but only as long as they have a + next to their name
To turn off messages you type
lab46:~$ mesg n
Mail
lab46:~$ alpine
ALPINE 2.00 MAIN MENU Folder: INBOX 1 Message +
? HELP - Get help using Alpine
C COMPOSE MESSAGE - Compose and send a message
I MESSAGE INDEX - View messages in current folder
L FOLDER LIST - Select a folder to view
A ADDRESS BOOK - Update address book
S SETUP - Configure Alpine Options
Q QUIT - Leave the Alpine program
Copyright 2006-2008 University of Washington
? Help P PrevCmd R RelNotes
O OTHER CMDS > [Index] N NextCmd K KBLock
To Check our email we press I and enter , this takes us to our index
To send an email we press C and enter , and fill in the needed information
Mailing list
Our class has a mailing list
-
Find the UNIX options and subscribe
Ones subscribed a test email can be sent to the mailing list at the address unix@lab46.corning-cc.edu
I sent one with the subject “Testing” and the body “testing, please ignore”
It worked as seen here
Unix is a Philosophy
Terminology
Strongest account on the system
Typically used by the system admin
has no restrictions imposed on it or protections
The starting part in a subtree of a file system
on lab 46 it is our folder
Units of data on a filesystem
Normally in 512 or 1024 byte blocks
CDs use 2048 byte blocks
Rare hardware sometimes uses its own blocks
1024 bytes
Sometimes refereed to as a KiB
Binary representation often shows it as being 1000bytes
This is often the case with hard drive manufacturers who see their hard drives with 1000 multiples instead of 1024
Means the system can handle multiple users at once
These users can do their own commands
Unix is this type of system
Means a system can handle multiple tasks
Means a system can handle multiple users running multiple different tasks at the same time
acronym for “Mail User Agent
Mail client
Allows the user to send or receive email
A gathering of email addresses used to create a discussion forum
allows for centralized announcements relayed to people
a message sent to a mailing list is called a post
When you send a message yourself its called posting
any string of characters that manipulate features after being typed in a prompt
Logging Off The Lab
Lab 0x1: Basic Utilities and their Manual Pages
Unix Commands
list is ls
copy is cp
move is mv
remove is rm
link is ln
Listing things
Unix has a command to list things called ls
When you type “ls”, you get a list of all the files or directories inside of your current directory
These files can be colored differently to reflect what type of file they are
The “ls” command can have additional arguments added to it to help narrow down your results
for example ls -l would result in something like this
lab46:~$ ls -l
-rw-r--r-- 1 jkosty6 lab46 440 Sep 13 10:15 2.00 MAIN MENU Folder: INBOX 1 Message +
drwxr-xr-x 2 jkosty6 lab46 6 Aug 28 12:20 Desktop
drwxr-xr-x 2 jkosty6 lab46 20 Aug 29 15:28 Documents
drwxr-xr-x 2 jkosty6 lab46 6 Aug 28 12:20 Downloads
lrwxrwxrwx 1 jkosty6 lab46 17 Aug 25 11:56 Maildir -> /var/mail/jkosty6
drwxr-xr-x 2 jkosty6 lab46 6 Aug 28 12:20 Music
drwxr-xr-x 2 jkosty6 lab46 6 Aug 28 12:20 Pictures
drwxr-xr-x 2 jkosty6 lab46 6 Aug 28 12:20 Public
drwxr-xr-x 2 jkosty6 lab46 6 Aug 28 12:20 Templates
drwxr-xr-x 2 jkosty6 lab46 6 Aug 28 12:20 Videos
-rwxr-xr-x 1 jkosty6 lab46 6561 Aug 29 16:34 a.out
drwxr-xr-x 2 jkosty6 lab46 6 Sep 3 08:57 bin
drwxr-xr-x 3 jkosty6 lab46 46 Sep 4 15:37 closet
-rwxr-xr-x 1 jkosty6 lab46 16638 Aug 29 16:42 hw
drwx-----x 2 jkosty6 lab46 6 Aug 26 2009 public_html
drwx------ 6 jkosty6 lab46 83 Sep 13 16:35 src
lab46:~$
Adding -l makes it list everything but also list all permission values and ownership information
This can be used to find out the size of files
For example if we wanted to find out the size of the grep file in bin we would get a result like this
-rwxr-xr-x 1 root root 119288 Apr 21 2010 grep
This shows us that it is 119288 in size
We can also use this to get a time stamp on a file
If we used this to look at cat for example
-rwxr-xr-x 1 root root 52288 Apr 28 2010 cat
Copying Things
If we wanted to copy something we would use the “cp” command
If we wanted to change to our home directory we would type just “cd”
To copy a file into our working directory we would type
lab46:~$ cp (directory and file name of target)
lab46:~$ cp (original copy name SPACE duplicate name)
Moving Things
lab46:~$ mv (file name) (directory destination)
lab46:~$ mv (old file name) (new file name)
Removing things
Shortcuts and links
lab46:~$ ln [-s] (target file) (shortcut file)
Manuals
UNIX contains manuals about most, if not all of its programs within itself
These can be easily accessed using the command “man” followed by the command you wish to inquire about
You can also skip to a specific section by adding in a section number before or after the command in question
Once a manual is open, you can navigate it using the arrow keys, and you can quit using q
Lab 0x2: Files and Directories
Unix File System
Master Directories
Unix handles its file system much differently than what we are used to with windows
Its filesystem is broken up into many parts
The parts are kind of easy to figure out what they stand for
/ - Root, the lowest you can go on a system, it is the base or foundation for the entire
OS
bin - Essential basic tools for normal system usage
etc - the systems configuration files
home - directory location of the system user files
lib, lib64, lib32 - system libraries very important and can be different depending on the architecture of your system
mnt - place where file systems get mounted such as hard drives
root - the administrator or super users folder
sbin - necessary system admin utilities
tmp - Temporary directory
usr - Additional (secondary) system functionality & userspace tools
var - Misc. items that have no place such as mail
lab46:~$ cd /
lab46:/$
lab46:/$ ls
bin etc lib lost+found opt sbin sys var
boot home lib32 media proc selinux tmp vmlinuz
dev initrd.img lib64 mnt root srv usr
lab46:/$
of all of these directories, some of them can not be accessed
root folder is one of them, unless you are root
Home Directory
lab46:/home$ cd /
lab46:/$ cd home
lab46:/home$ cd jkosty6
lab46:~$
Working Directory
As stated before, the current directory you are in is the working directory
It can be reached by typing in the “pwd” command
Path-names
Absolute - The exact location in the file system - the pwd command returns this
Relative - The exact location on the file system is unknown and only comparable to the specific location
There are hidden files referenced when you list all with ls -a
These files are .. and .
Every directory has these
.. refers to the previous directory
. refers to the current directory
These can be used as relative pathnames comparable to your current working directory
You can change directory using them such as cd .. would move you to the lower directory
Files
Regular Files - Text and executable files
Directories - A file that points to other files
Special Files - Devices and network specific items
user - the owner of the file
group - the group that owns a file
other - everyone else
read
write
execute
read 4 r view / read the file
write 2 w save / create / modify / delete the file
execute / search 1 x run / parse through contents of a file
You add together the values you want in order to reflect what you want
example 421 would make a user have read, group have write, global have execute, - 777 would be all 3 for all 3
Lab 0x3: Text Processing
Cat Command
lab46:~$ cd /etc
lab46:/etc$ cat motd
__ _ _ _ __ . . . . . . . . . . . . . . . . . . . . . . . . .
| | __ _| |__ / | |_/ / . 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 .
.. . . . . . . . . . ..
Other Commands
lab46:/etc$ wc passwd
27 32 1135 passwd
lab46:/etc$ wc -l passwd
27 passwd
This shows there are 27 lines
There is the “head” command
This command shows how ever many lines you specify
with head -n –lines=16, we could display the first 16 lines of something
The tail command lets us show the last lines of a file
If we use tail -f, we can monitor a file
we could use this to monitor lists and modifications
VI Commands
i - insert before cursor
o - insert line below
O - insert line above
a - insert after cursor
:wq - save and exit
:w - save the file
:q! - quit without saving
ZZ - quit and save only if changed
h (or left arrow) - move cursor left
j (or down arrow) - move cursor down
k (or up arrow) - move cursor up
l (or right arrow) - move cursor right
Lab 0x4: UNIX Shell Basics
Background
Operating Systems
Kernel - the core of the
OS. It handles everything- manages I/O, etc.
Drivers - components that instruct the kernel how to function or deal with a piece of hardware.
Userspace - non-kernel level. System applications, utilities, files. Users exist here, hence the name “user space”
Userspace
At this level there are multiple servers running
these servers are called daemons
users of the system have access via a shell
shell, or command interpreter (or command processor)
ITs responsible for
interactive use
customization
programming
Control Characters
Control Code System Code Description
CTRL-C INTR interrupt
CTRL-D EOF issue end of file character
CTRL-G sound bell
CTRL-H BS send backspace
CTRL-J LF send linefeed
CTRL-L refresh screen
CTRL-M CR send carriage return
CTRL-Q XON start code*
CTRL-S XOFF stop code*
CTRL-V escape the following character
CTRL-Z SUSPEND suspend current job
CTRL-[ ESC send escape character
Dot files
In unix there are hidden files called dotfiles, and used on login or for configuration purposes
dotfile description
.bash_profile The first personal initialization file bash searches
.bashrc Session personalization file called by .bash_profile
.cshrc A personal initialization file for the csh/tcsh shells
.exrc A configuration file for vi/ex
.signature Text file containing a signature banner for e-mail
.plan A personal banner file that is displayed on finger(1) lookups
.forward A file used in automatic e-mail forwarding
.pinerc A configuration file for pine
.vimrc A configuration file for vim
1 I see pokemon
2 John Kosty
3 C / C++ and UNIX
Environment Values
$PATH
$HOSTNAME
$USER
$TERM
$SHELL
printenv utility list yours environment variables
You can create aliases using the alias command
You can remove aliases with unalias command
alias nameofalias=“utility -options –options”
history
you can view your history with the history command
! makes you do something special with history
!history_number you will run the command represented by the number
Tab completions
Conclusions
Its nice review on how to use the command line's more unique features
Lab 0x5: More UNIX Shell Explorations
Wild Cards
Symbol Description
* match 0 or more characters
? match exactly one character
[ ] character class - match any of the enclosed characters.
[^ ] inverted character class - do not match any of the enclosed characters.
IO Redirection
The terminal sends and receives data by three means
Standard Input (stdin), Standard Output (stdout), and Standard Error (stderr)
The shell has a was of using these
Symbol Description
> STDOUT redirection operator
>> STDOUT append redirection operator
< STDIN redirection operator
2> STDERR redirection operator
2>> STDERR append redirection operator
| pipe
Pagers are programs created to handle the output of something
They can also be used to limit the output so that reading is easier
Page by page
line by line
The commands more or less are pagers
Quotes
Symbol Name Description
` backquote command expansion
' single (or full) quote literal quote, no expansion
" double (or partial) quote variable expansion
===Conclusions===
Nice review from C
Lab 0x6: Shell Scripting Concepts
Running a script
We were told to make a script with this inside of it
ls ~
df
who
if we try to run it using (dot slash) it will say we lack the permission.
We can view the permissions on the file by doing ls -la script1.sh
The owner has read and write. The user has read. Global has read
We can use chmod to change the permissions on the file to what we would like
chmod 777 script1.sh
The script works
Philosophy
Anything that you can type on the command line can be added to the script
Simple I/O
There are two easy ways to do IO
Echo - echo “phrase to echo” ~ -n gets rid of newline after command
Read - read variable ~ variable is anything we define. can call it with $variable
let - enables simple mathematical functions - lab46:~$ let num1=$num1+$num2
echo "What is your birth year?"
read birth
currentday=$(date | awk ' {print $6}')
let output=$currentday-$birth
echo $output
Shabang
Selection
Often times we have to compare things with our scripts
If statements are one of the options
The sample code gives the user a prompt for input twice and stores the data
#!/bin/bash
echo -n "Pick a number: "
read num1
echo -n "Pick another number: "
read num2
if [ "$num1" -lt "$num2" ]; then
echo "$num2 is greater than $num1"
fi
if [ "$num1" -lt "$num2" ]; then
echo "$num2 is greater than $num1"
elif [ "$num2" -lt "$num1" ]; then
echo "$num1 is greater than $num2"
fi
if [ "$num1" -lt "$num2" ]; then
echo "$num2 is greater than $num1"
elif [ "$num2" -lt "$num1" ]; then
echo "$num1 is greater than $num2"
else
echo "$num1 and $num2 are equal in value"
fi
* we can make a program that asks for a number and generates a random number to guess against.
#!/bin/bash
pick=$(($RANDOM % 20))
echo "Pick a number between 1 and 20"
end=4
counter=0
while [ "$counter" -lt "4" ]; do
read picked
if [ "$pick" -eq "$picked" ]; then
echo "$picked is the number!"
exit
elif [ "$pick" -lt "$picked" ]; then
echo "$picked is greater than the number!"
let counter=counter+1
elif [ "$pick" -gt "$picked" ]; then
echo "$picked is less than the number!"
let counter=counter+1
fi
done
iteration
Starting condition
a loop until condition
and a method to get there
#!/bin/bash
for((i=1; i<=10; i++)); do
printf "$i "
done
prints the provided script without newline
#!/bin/bash
for((i=20; i>=2; i--)); do
printf "$i "
done
steps backwards from 20 to 2
in the provided list based for loop
The loop goes 8 times
The fifth time through the color is blue
echo -n "First color is: "
for color in red orange yellow green blue indigo violet; do
if [ "$color" == "indigo" ]; then
echo "$color"
echo -n "The last color is: "
elif [ "$color" == "violet" ]; then
echo "$color"
exit
else
echo "$color"
echo -n "Next color is: "
fi
done
is my modified code
echo "Give me a number"
read number
echo $number > file$number
the code to create file with number
#!/bin/bash
printf "Please enterdirector to process: "
read directory
printf "Processing ...\n\n"
echo "Directory: $directory"
cd "$directory"
filecount=$(ls -la | wc -l)
if [ "$filecount" -gt "60" ]; then
filecount=60
fi
echo "Total Files: $filecount"
Lab 0x7: Job Control and Multitasking
Viewing Processes
* We learned about multitasking
* we can see the running processes with PS command
* this works with
lab46:~$ ps
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
jkosty6 11177 0.4 0.1 13644 2004 pts/24 SNs 23:20 0:00 -bash
jkosty6 11206 8.0 0.0 8588 988 pts/24 RN+ 23:23 0:00 ps u
* we can see our processes in other shells using the same
ps -e lists all processes on the system
Running in the background
using & you can instruct a command to run in the background
The count file is a C file
You can determine this with the file command
gcc -o count count.c
./count
output is
real 0m36.795s
user 0m35.482s
sys 0m0.608s
adding an & to it runs it in the background
The Command Separator
We can use the semicolon as a command seperator to so that once the first command is done the second one executes
Task 1
sleep 8 ; ls /var > multitask.lab.txt &
Task 2
you cant log out cause tasks are stopped
this might be incase you dont want to terminate the jobs you can keep running them
the links job is number 2
bringing it to foreground caused error
moving it back to background worked
fg 1 foregrounded cat
cat is gone
all jobs gone
Kill
We can kill processes using kill
8 kill -l
a 1
b 34
c 9
d 2
jkosty6 + pts/55 2013-12-12 15:35 . 3574 (cpe-69-204-219-21.stny.res.rr.com)
jkosty6 + pts/82 2013-12-12 11:25 . 24306 (cpe-69-204-219-21.stny.res.rr.com)
dev/pts/82
dev/pts/55
kill -9 24369
killed pts/82
no messages at all just closed putty
no longer logged in twice
Applying skills
ps -e | grep statd
the PID of init is 1
root own cron 1190 is pid
cron is a task scheduler
Lab 0x8: The UNIX Programming Environment
GNU C compiler
We can compile a file with
gcc -o output input.c
GNU C++ Compiler
g++ -o output input.cc
We can compile with this
GNU Assembler
to assemble an assembly file we can do
as -o outpout.o input.s
to run it on the system we need to do
ld -o binary object.o
Prodedure
copied over the files
compiled them with
as -o helloASM.o helloASM.S
ld -o helloASM helloASM.o
gcc -o helloC helloC.c
g++ -o helloCPP helloCPP.cc
Executing it
If we run it without a ./ it will fail to run saying command not found
with ./ it executes it from the current directory, so it works
Putting back together
helloC.c is a ASCII C Program Text file
helloASM.S is a ASCII assembler program test file
helloCPP.cc is a ASCII C++ Program text file
if we compile with gcc -S helloC.c it turns it into assembly and an assembly file
when we cat or VI the file we can see that it is pure assembly
if we type
as -o hello.o helloC.s
it creates an ELF 64bit LSB relocatable x86-64 sysv not stripped
it seems to have been turned into an object form of the S file
Make Files
You can run make files to deal with multiple source files that need compiling at once
Lab 0x9: Pattern Matching with Regular Expressions
Procedure
We can use the grep command to narrow down our results in files
cat /etc/passwd | grep System
would limit it to only lines with system
lab46:~$ cat /etc/passwd | grep '^[jpk]'
proxy:x:13:13:proxy:/bin:/bin/sh
cat regex.html | sed 's/<centre>/<center>/g' | sed 's/<\/CENTRE>/<\/center>/g' | sed 's/<b>/<strong>/g' | sed 's/<\/b>/<\/strong>/g'
cd /etc/dictionaries-common/
found it using ls -la and looking at the link
seems to be just a text file with all the words
98569 words and you get it with cat words | wc -l
5 character length cat words | grep “^…..$”
all words starting with jpk cat words | grep “^[JPKjpk]”
first begining middle middle last last cat words | grep “^[jJ].*[pP].*[kK]$”
begin and end with vowel cat words | grep “^[aeiouy].*[aeiouy]$”
begin initial vowel second est last cat words | grep “^[jJpPkK][aeiouy].*[est]$”
dont start with initial cat words | grep “^[^jJpPkK]”
all 3 letter words ending in e cat words | egrep '^..[e]$'
contain bob not ending in b cat words | grep 'bob.*[^b]$'
all words starting with blue cat words | grep '^blue'
contains no vowels cat words | grep '^[^aeiouyAEIOUY]*$'
dont begin vowel. second letter anything. third abcd ends in vowel cat words | grep '^[^aeiouyAEIOUY].[abcd]*[aeiouyAEIOUY]$'
Lab 0xA: Data Analysis with Regular Expressions and Scripting
Obtaining data
cp /var/public/unix/courselist/fall2011-20110417.html.gz .
72355
gzip compressed file
gunzip fall2011-20110417.html.gz
2427432
98%
Raw Data
you use the slash then search parameter
most of them have the same filler junk around them
Isolating
cat fall2011-20110417.html | grep crn
yes it does
yes
Filtering unessessary
cat fall2011-20110417.html | grep crn | sed 's/<th class="ddtitle" scope="colgroup"><a href="https:\/\/.*crn_in=.....">//g'
cat fall2011-20110417.html | grep crn | sed 's/<th class="ddtitle" scope="colgroup"><a href="https:\/\/.*crn_in=.....">//g' | sed 's/<\/a>.*$//g' | awk '{print $1}' | uniq | wc -l
348
Lab 0xB: Filters
Today the lab was about filters.
* We can get the Standard output of a file by catting it
* We can pipe the file with wc -l to count the lines in the file
Keyword Filtering
* We can filter out all lines in a file by piping it with grep “keyword”
* we can filter out all lines in a file by piping it twice to see if both lines contain something cat “filename” | grep “keyword” | grep “keyword”
To find students that are freshmen
cat sample.db | grep Freshmen
cat simple.db | sort | grep Freshman
cat simple.db | uniq | sort | grep Freshman
cat simple.db | uniq | sort | grep Freshman | wc -l
Filter Manipulation
lab46:~$ echo "hello there:this:is:a:bunch of:text." | cut -d":" -f1,6
hello there:text.
Sed
We can search and replace parts of a string using the sed command
Using sed, we can fix our cut output to eliminate the :
to change everything from t to T
lab46:~$ echo "hello there:this:is:a:bunch of:text." | cut -d":" -f1,6 | sed -e 's/:/ /g' | sed -e 's/t/T/g'
"hello there:this:is:a:bunch of:text." | cut -d":" -f1,6 | sed -e 's/:/ /g' | sed -e 's/\./\*/g'
Head and tail
Procedure