Presentation is loading. Please wait.

Presentation is loading. Please wait.

Review of Linux and C CSCI/CMPE 3334 David Egle.

Similar presentations


Presentation on theme: "Review of Linux and C CSCI/CMPE 3334 David Egle."— Presentation transcript:

1 Review of Linux and C CSCI/CMPE 3334 David Egle

2 Brief history of UNIX/Linux
Developed at Bell labs round 1970 (Ken Thompson, et. al.) Written primarily in C Was portable (less than 10% in assembly language) Had a unified approach to files, devices, interprocess I/O (treated everything as a file) Had a replaceable user interface Multiuser/multitasking environment Networking was implemented early

3 History 2 By 1990’s many variations But none were free
Two main versions (and many minor) System V, release 4 (AT&T) BSD (Berkeley standard distribution) But none were free 1991, a Finnish college student, Linus Torvalds, decided to create his own version, called Linux, based on the published manuals for UNIX (by using his own code, he avoided any copyright issues).

4 History 3 Torvalds published his version on the Internet (via a bulletin board called USENET) Many people were interested and contributed to this effort Today, many distributions of Linux exist (see futurist.se/gldt), but there is a central clearinghouse for any modifications to the basic Linux (kernel.org) Linux has all of the features of UNIX, plus some new ones

5 User interface The user interface is called the shell
There are many different shells available, and all are user configurable to some extent Some are command line shells, others are GUI shells Common command line shells sh (original Bourne shell) csh (adds features found in the language C) ksh (Korn shell) bash (Bourne again shell)

6 Utilities needed for this course
Help man – gives help on a specific command File utilities ls – list the files in a directory cat – display the contents of a file less – a more sophisticated file viewer rm – remove a file cp – copy a file mv – move/rename a file

7 Utilities needed for this course 2
Directory commands cd – change directory mkdir – create a directory rmdir – remove an empty directory Editors vi emacs nano gedit (in windowing environment) Compilers gcc g++

8 Utilities needed for this course 3
Miscellaneous commands tar – allows several files to be put into a single file for ease in ing or saving gzip – compression utility gdb – a debugging tool

9 Creating/running a program in Linux
Design algorithm on paper Code the algorithm using an editor Compile and link your program gcc -o executable myprog.c Run the program ./executable To keep record of program output (file called ‘typescript’) script …. exit

10 Using tar Command format (for us)
creating tar file tar –cf filename.tar list of files (may be wildcarded) extracting tar file tar –xf filename.tar To compress the file at the same time, add the option -z

11 A Brief Introduction to C

12 Similarities with C++ Variables Expressions Assignments
But no bool data type Expressions Assignments Selection statements Looping statements Structs Need to use the word struct when declaring variables Arrays Pointers

13 Differences from C++ Input/Output Functions Strings
No iostream or fstream Functions No reference variables No overloading Strings Only arrays of type char Dynamic memory allocation File handling No classes No operator overloading

14 Input/Output Need to use stdio #include <stdio.h>
This handles standard I/O (keyboard and monitor) and file I/O Use the scanf function for input and printf function for output

15 scanf Family of Functions
There are different scanf functions scanf: used to read from an input device fscanf: used to read from a file sscanf: used to read from a string

16 scanf Basic syntax scanf(“format string”, list of variables);
The format string tells the C compiler how many variables are to be read in and their respective types Since C does not use reference variable, the list of variables MUST be addresses (use the & operator) Example: scanf(“%d %d”, &x, &y);

17 scanf format specifier
There are over 40 different formats – only a few are covered here The specifier prototype is %[*] [width] [length] specifier The specifier at the end is the most significant component, since it defines the type See table next slide

18 Format Specifiers %d Scan an integer as a signed decimal number. %i
Scan an integer as a signed number. Similar to %d, but interprets the number as hexadecimal when preceded by 0x and octal when preceded by 0. %f  Scan a floating-point number in normal (fixed-point) notation. %g, %G  Scan a floating-point number in either normal or exponential notation. %g uses lower-case letters and %G uses upper-case. %x, %X  Scan an integer as an unsigned hexadecimal number. %o  Scan an integer as an octal number. %s  Scan a character string. The scan terminates at whitespace. A null character is stored at the end of the string, which means that the buffer supplied must be at least one character longer than the specified input length. %c  Scan a character (char). No null character is added. white space Any whitespace characters trigger a scan for zero or more whitespace characters. The number and type of whitespace characters do not need to match in either direction.

19 Examples Read in a string (spaces are delimiters) char str[100];
scanf(“%s”, str); /* problem if > 99 chars */ Read in integers scanf(“%d %d”, &x, &y); Read in floating point values scanf(“%f %f”, &a, &b); Read in hexadecimal values scanf(“%x %x”, &s, &t);

20 Examples using width Read 20 characters into a string char str[21];
scanf(“%20s”, str); /* need to store null */ Read in two digit integers separated by spaces scanf(“%2d %2d”, &x, &y); Read in hexadecimal values with no separation scanf(“%2x%6x”, &s, &t);

21 Suppressing input scanf can read a field but not assign it to any variable by preceding the specifier with an * Consider for example, scanf(“%d%*c%d”, &x, &y); If you entered “10, 10”, the 10 would be read into x, the comma would be read and ignored, and the second 10 would be read into y Note that this could also be done by specifying scanf(“%d, %d”, &x, &y);

22 printf Basic syntax printf(“format string”, list of variables);
The format string tells the C compiler how many variables are to be displayed and their respective types Note that the variables are passed by value (not by address) Example: printf(“The input is x = %d, y = %d”, x, y);

23 printf format specifier
There are over 40 different formats – only a few are covered here The specifier prototype is %[flags] [width][.precision] [length] specifier The specifier at the end is the most significant component, since it defines the type See table next slide

24 Format Specifiers d or i Signed decimal integer 392 x
Unsigned hexadecimal integer 7fa X Unsigned hexadecimal integer (uppercase) 7FA f Decimal floating point 392.65 e Scientific notation (mantissa/exponent), lowercase 3.9265e+2 E Scientific notation (mantissa/exponent), uppercase 3.9265E+2 g Use the shortest representation: %e or %f G Use the shortest representation: %E or %F a Hexadecimal floating point, lowercase 12af A Hexadecimal floating point, uppercase 12AF c Character s String of characters sample p Pointer address b % A % followed by another % character will write a single % to the stream.

25 Examples Display a string char str[100];
printf(“You entered: %s\n”, str); Display integers printf(“x = %d, y = %d”, x, y); Display floating point values printf(“Values are %8.3f %10.2f\n”, a, b); Display hexadecimal values printf(“s = %x, t = %x”, s, t);

26 Output form The output of the printf is determined by the string in the format specifier If you leave out something, it will not be printed There is no endl manipulator – you must use the \n to display a new line

27 Example #include <stdio.h> int main() { double item; item = ; printf(“%f\n”, item); printf(“%10f\n”, item); printf(“%012f\n”, item); return 0; } Output of this program: Note that the default precision is 6. The leading 0’s are produced by the 0 in the specifier

28 Example #include <stdio.h> int main() { printf(“%.4f\n”, ); printf(“%08d\n, 1000); printf(“%10.15s\n”, “This is a simple test”); return 0; } Output of this program: This is a simpl For int types, the precision specifies number of digits For strings, the precision specifies the max field length

29 Justifying output The default justification is right-justify
To specify left-justification, use %-8d Example: printf(“%8d\n”, 100); printf(“%-8d\n”, 100); displays as 100

30 Console I/O To read a character from the keyboard char ch;
ch = getchar(); Note that most implementations buffer the input until the user presses the enter key To write a character to the screen putchar(ch); Note that these simply read and write characters – no translation to any format is done

31 Functions Since C does not support reference parameters, you must use pointers when using parameters to pass back information The following function would be called by swap(&a, &b) void swap(int *x, int *y) { int t; t = *x; *x = *y; *y = t; } Note the use of the dereferencing operator *

32 Dynamic Memory Allocation
To allocate space for variables use malloc int *x = (int *) malloc( sizeof(int) ); int *x_array = (int *)malloc( sizeof(int) * 10 ); Use free to release the memory free( x ); free( x_array );

33 File handling File pointer: pointer to a structure that defines various things about the file – name, status, current position in the file, etc. A file pointer is a variable of type FILE (defined in stdio.h) Example FILE *input, *output;

34 Common file functions Name Function fopen() Opens a file fclose()
Closes a file putc() Writes a character to a file getc() Reads a character from a file fseek() Positions (seeks) to a specified byte in the file fprintf() Writes to the file (like printf is to standard output) fscanf() Reads from the file (like scanf is to standard input) feof() Returns true if end-of-file is reached ferror() Returns true if an error has occurred fgets() Reads a string of characters into a char array rewind() Resets file position locator to the beginning of the file

35 fopen() Serves two purposes Syntax: FILE *fp;
Opens disk file for use Returns file pointer that identifies that file Syntax: FILE *fp; fp = fopen(filename, mode); Here filename is a character string (may be a variable, or a constant), and mode is a string containing the desired open status

36 fopen modes Mode Meaning “r” Open text file for reading “w”
Open text file for writing (destroys file if it already exists) “a” Open text file for appending “rb” Open binary file for reading “wb” Open binary file for writing “ab” Open binary file for appending “r+” Open text file for read/write “w+” Create text file for read/write “a+” “rb+” Open binary file for read/write “wb+” Create binary file for read/write “ab+”

37 Examples of fopen() Open a text file for writing FILE *fp;
fp = fopen(“test”, “w”); Note that this is usually written as if (( fp = fopen(“test”, “w”)) == NULL) { printf(“cannot open file ‘test’\n”); exit(); }

38 fclose() Serves two purposes Syntax: fclose(fp);
Writes any data remaining in disk buffer to file Does a formal close on file at level of the OS Syntax: fclose(fp); Here fp is the file pointer returned by the fopen() Note that a 0 return signifies a successful close Any other value indicates an error

39 fscanf Read from a file Syntax: FILE * pFile; char name [100];
pFile = fopen ("myfile.txt",“r"); fscanf (pFile, "%s", name);

40 fprintf Write to a file Syntax: FILE * pFile; char name [100];
pFile = fopen ("myfile.txt","w"); fprintf (pFile, "Name %d [%-10.10s]\n",n+1,name);

41 putc() and getc() Write or read a single character Syntax: char ch;
putc(ch, fp); ch = getc(fp);

42 feof(), ferror(), and rewind()
Check for end of file feof(fp) Returns true if end of file reached Check if error occurred during last file operation ferror(fp) Returns true if error occurred – determination of error is system dependent Reset file position locator to beginning of file rewind(fp)

43 fgets() Syntax: fgets(str, num, fp);
Read up to num-1 characters from the stream fp and puts them in the character array str. Reading stops when new-line char or EOF is received. A null is placed in array after last character read Note that the new-line char is stored in the string Example: char str[128]; fgets(str, 128, fp);

44 Examples using fgets()
Read from a file char str[128]; fgets(str, 128, fp); To read from the keyboard, the input stream is stdin fgets(str, 128, stdin);


Download ppt "Review of Linux and C CSCI/CMPE 3334 David Egle."

Similar presentations


Ads by Google