Вы находитесь на странице: 1из 2

colons $HOME is the path of the Unix file system: -root directory, everything users home directory else

stems from it. 2 types of file: files and directories

Unix

Commands: ls a:all(including . files) l:long list format g:like l but dont list owner R:list subdirectories recursively r: revers order while sorting S: sort by filesize 1: list 1 file per line t: sort by modifications time U: do not sort list entries in directory order v: sort by version grep general form: grep [options] Pattern[file] c: suppress normal output, instead print a count of matching lines H:show file name on output | i: ignore case| h:suppress printing file names when grepping multiple file names n:prefix output with line number chmod General form: chmod [ugo][+][rwx]filenam rm: remove file f: forced, no messages i: prompt for files eg rm if * mv: move file cp: copy file cat: show contents of the file more less: like cat but can move through the file mkdir rmdir: create/remove directory pwd: show the current directory path passwd: change password netfile netget tar: make/extract edit archives man Special characters *:wildcard, anything .:current directory [ ]: can be anything inside the brackets [a-z] [0-9] eg ls *.c: list all .c files gcc *.c compile all .c files < >: use as input/output to file >>: append output to file | : pipe the output of the command on the left into the input of the command on the right Shell variables: $PATH contains the all the paths that the shell looks through for commands separated by

commands cont. diff: compare two files for differences sdiff: shows the differences side by side sort: default it sort alphabetically, with repeats u: unique f: ignore case r: reverse order apropos: searches database for matching keywords provided by the user gzip/gunzip: compresses/expands files Shell scripts All shell scripts start with: #!/bin/bash shell variables shell variables can be created by going VARNAME=value and this is accessed by $VARNAME make sure there is no space between equals sign and stuff around it. shell script ARGUMENTS are stored in special vars $1, $2, $3 etc ($0 is the program name) $* shows all script arguments control structures examples: if: if test $1== fred then echo first arg is fred fi for: for name in $* do gcc $name.c o $name done will compile all .c files given the filenames as argument while: while test $result!=10 do ...done test is used to test for equality, evalutate Boolean expressions command substitution use backquotes to indicate that the contents inside is a command to be run and the output used as arguments for another command. e.g. myprog `cat argfile` will run cat, take the output and use this as arguments for myprog. top shows running processes dynamically grep example grep [Bb]ob data* scans each file whose name starts with data and print lines containing Bob or bob

C Linked Lists: Defining the element typedef struct Node { int val; struct Node *next; }Node; Add element to front of list /*listp points to the first element *newp is the element to be added */ Node * addtoFront(Node *listp, Node *newp) { newp->next = listp; return newp; } Add element to back of list Node *addToEnd(Node *listp, Node *newp) { Node *p; if(listp == NULL) return newp; for(p = listp; p->next != NULL; p = p->next) ; p->next = newp; return listp; } Deallocate a complete list void freeAll(Node *listp) { Node *p; for( ; listp != NULL; listp = p) { p = listp->next; free(listp->content); /*watever data it holds*/ free(listp); } } Delete the first element in the list Node *deleteFirst(Node *listp) { Node *p; if(listp ! = NULL) { p = listp; listp = listp->next; free(p); } return listp; } Count the number of elements in a list int count(Node *listp) { int count = 0; for( ; listp != NULL; count++) listp = listp->next; return count; } Arrays Strings: a string is a char array with a NULL terminator at the end one form of declaration: char string[ ] = i am red; this will be a char array with 9 elements, 8 for I am red and 1 for the \0 character. -Variables may alter their rvalues but not their lvalues -A pointers rvalue is the lvalue of another variable so that arithmetic operations are permitted Array pointers int A[N]; int *pa; = A; then A[i] is equivalent to *(pa + i) Pass by value: passing the value of the arguments directly.

Pass by reference void swap(int *a, int *b)/*swaps 2 integers*/ { int tmp = *a; /*pass the address of each integer *a = *b; *and then do the swap using the *b = tmp; *dereference operator*/ } Enumerated types can have user defined types that map onto integers eg enum day_name { Sun, Mon, Tue, Wed, Thu, Fri, Sat, day_undef }; Structures can hold multiple data types eg struct A{ /*declaration of struct As*/ int a; struct A x; int b; struct A *p; int c[10]; }; x.a will retrieve the value of a in x and x.b etc p->a will retrieve the value of a of the struct that p points to p->c[0] gets the first element of c of the struct that p points to Memory areas -Stack: local variables, function arguments, return addresses, temporary storage -Heap: dynamically allocated memory, malloc/salloc -Global/static: global variables, static variables -Code: program instructions Make CC:=gcc CFLAGS:= -Wall W ansi pedantic g $(CFLAGS) LDFLAGS:= $(LDFLAGS) scaffold filename: filename.o file1.o file2.o ... $(CC) $(CFLAGS) $(LDFLAGS) o filename file1.o.... clean: rm f *.c filename Standard library functions <stdio.h> fopen /*opens the file filename, for reading r or writing w as specified by type*/ FILE *fopen(char *filename, char *type) fgets /*reads one line from filep, keeps \n at the end, reads at most n -1 chars returns string on success, NULL otherwise*/ char *fgets(char *string, int n, FILE *filep) fprintf /*like printf but specify a file to print to eg stdout, stderr or a FILE**/ int fprintf(FILE *filep, char *format/*, [arg]) popen /*opens a pipe to the shell command pointed to by command type specifies read r or write w returns a file pointer to the pipe, NULL otherwise*/ FILE * popen(const char *command, const char *type) pclose /*closes the pipe filep*/ int pclose(FILE *filep) <string.h> strcpy/strncpy/*copies src to dest, strncpy copies at most n characters*/ char *strcpy(char *dest, char *src) char*strncpy( , count) strcmp/*returns -1 if string1 < string2, 0 if string1=string2 1 if string1 > string2 int *strcmp(const char *string1, const char *string2) int *strncmp(const char *string1, const char *string2, size_t count)/*compares at most count characters*/ strcat/*concatenates src onto end of dest returns a pointer to dest*/ char *strcat(char *dest, const char *src) char * strncat(char *dest, const char *src, size_t count) strlen/*returns the length of string*/ int strlen(const char *string) <signal.h> has functions that can send signals to other processes. eg. int kill(pid_t pid, int sig) sends sig to the process with id pid)

C Standard library functions cont. <stdlib.h> qsort /*the compare fn must compare 2 elems of the type that the array stores*/ void qsort(arrytosort, nooelems, sizeof elem, compare fn) compare returns -1 if 1st one is less than 2nd one 1 if 1st one is more than the 2nd one 0 if they are equal malloc/*allocates size bytes onto the heap, returns a pointer to the allocated memory, NULL if insufficient me) void *malloc(size_t size) salloc/*safely allocates memory by checking return value of malloc*/ void *salloc(size_t size) { void *result; if((result = malloc(size)) == NULL) { fprintf(stderr, cannot malloc %d bytes\n, size); exit(1); } return result; } realloc/*allocates space on the heap for the data in ptr in size bytes, returns a pointer to the allocated area*/ void *realloc(void *ptr, size_t size) <ctype.h> Macros /*where c is a character*/ isalpha(c) /*true is c is a letter*/ isupper(c) islower(c) isdigit(c) isalnum(c)/*is a letter or a number*/ isspace(c)/*space, tab, form feed, CR or new line*/ ispunct(c) toupper(c) tolower(c) isprintf(c)/*a printing character*/ <unistd.h> exit /*stops execution of a process*/ void exit(int status) getopt: processes arguments and options from the command line /*returns: EOF when there are no more options ? on an unrecognised option : on the absence of a required value for an option*/ /*argc and argv are the normal arguments in main. specifier states which options are valid. */ int getopt(int argc, char *const argv[ ], const char *specifier); extern char *optarg; extern int optind, opterr, optopt; <sys/types.h><sys/stat.h> stat /*places information about filename in area ointed to by status returns 0 on success, -1 on fail*/ int stat(const char *filename, struct stat *status) <unistd.h><sys/types.h> exec: suspends the current process and starts another process. switches program execution to another program /*if successful, it does not return. any return indicates failure. returns -1 if the program was not found, 0 or greater if exec itself failed*/ int execl(const char *filename, const char*arg, ...) fork: creates a child process that is a copy of the memory image of the parent. duplicates the current process /*on success, returns 0 to child process, pid of child to parent process. on error, returns -1*/ pid_t fork(void) wait: after forking, the child process will do exec to start a new program. the parent continues to execute. the parent can ignore the child or wait for it to exit. wait waits for termination of the child process with status value. status points to an integer containing the status returned by child process. /*on success, returns pid of terminating process, if there is no child process to wait for, returns -1*/ pid_t wait(int *status) Preprocessor #ifndef UTIL_H #define UTIL_H /*function declarations*/ #endif conditional inclusion #ifdef, #if, #ifndef, #else, #elif, #undef

getopt while((opt = getopt(argc, argv, "apO:")) != EOF switch (opt) { case 'a': case 'p': A_OPTION = 1; P _OPTION = 1; case 'O': username = optarg case '?':exit(1); case ':': exit(2); Deleting certain elements from list Node *ptr = start; Node *tmp = ptr; while(ptr != NULL) { if((islower(*(ptr->name)) != 0) && (ptr == tmp)) { start = ptr->next; free(ptr); tmp = start; ptr = start; } else if((islower(*(ptr->name)) != 0) && (ptr != tmp)) { tmp->next = ptr->next; free(ptr); ptr = tmp->next; } else if((islower(*(ptr->name)) == 0) && (ptr == tmp)) { ptr = ptr->next; } else if((islower(*(ptr->name)) == 0) && (ptr != tmp)) { tmp = ptr; ptr = ptr->next; } mailer program: uses fork and exec FILE *file = popen("mail liljman@gmail.com", "w"); int c; while((c = getchar()) != EOF) { fprintf(file, "%c", c); } biggen: adds num to original val Node * biggen(Node *start, int num) { Node *ptr = NULL; while(start) { Node *newnode = salloc(sizeof(Node)); newnode->val = (start->val + num); newnode->next = NULL; ptr = addToEnd(ptr, newnode); start = start->next;

} return ptr; } printags: prints command line arguments char *w = malloc(sizeof(char)*SIZE); char *prime = w; for(i = 1; i < argc; i++) { while((*argv[i]) != '\0') { *w = *argv[i]; w++; argv[i]++; } *w = ' '; w++; } *w = '\0';

When creating strings, memory MUST be allocated for the string first either using an array of chars or salloc or direct declaration and initialisation. creating linked lists when creating the head, is Node *head, must be initialised to NULL. Node *head = NULL; /*argc is no. of arguments, argv is array of pointers to arguments*/ int main(int argc, char *argv[ ]) argv[0] is the name of the program NEVER CHECK FLOATS FOR EQUALITY system_example starts another program by forking and execing sys(char *command, char *filename) { int status; /* status returned by command */ int pid; /* process id of command */ int wval; /* value returned by wait */ switch(pid = fork()) { case 0: /* child exec's shell */ execl("/bin/sh", "sh", "-c", command, 0); /* fall through if exec fails */ case -1:/* could not fork */ /* print appropriate error message */ perror(filename); exit(1); default:/* parent waits for child to finish */ while ((wval = wait(&status)) != pid) if (wval == -1) return -1; } return status; srealloc void * srealloc(void *ptr, size_t size) { void *result; if ((result = realloc(ptr, size)) == NULL) { fprintf(stderr,"cannot malloc %d bytes\n", size); exit(1); } return result; } File descriptors are small integers indicating an open file. when a process is started file descriptor 0 is standard input, 1 is standard output and 2 is standard error output. Processes may sometimes wish to cooperate and exchange information during execution so they may use pipes and /or signals to do this. A thread is a like a process with these similarities and differences: Similarities: each has its own logical control flow, each can run concurrently, each is context switched Differences: threads share code and data, processes do not threads are less expensive than processes String functions sprint sprint is like printf except the output goes to a string instead of a file eg sprintf(outstr, Answer is %d, num) the scope of a variable is its visibility. a variable is only visible between the curly braces in which it is defined. Static structure of code holds from when the code is written (compile time). Dynamic/runtime structures differs according to data in individual runs. rot13 while(*string) { if(isalpha(*string)) { position = *string - 'A'; if(position < OFFSET) *string += OFFSET; else *string -= OFFSET; *string++;

Вам также может понравиться