Presentation is loading. Please wait.

Presentation is loading. Please wait.

C Programming CISC3130, Spring 2011 Dr. Zhang 1.

Similar presentations


Presentation on theme: "C Programming CISC3130, Spring 2011 Dr. Zhang 1."— Presentation transcript:

1 C Programming CISC3130, Spring 2011 Dr. Zhang 1

2 Midterm Review Program: your C/C++ program, system command (ls, mv,…), a bash script, a PERL script, … a static entity, a file exists in the disk Process: a dynamic entity, representing each program that is being executed in the system Program, user, states (running, waiting for I/O, ready), opened files, memory (current values of variables) … Operating system schedules multiple processes in the system to best utilize system resources (CPU, disk, networking…) Related command: ps, at, nice, To run a program in background: use &

3 Midterm Review When running a program,
Standard input/output/error: can be redirected Command line arguments: to pass arguments to a program e.g., ls -l ~ e.g., headtail 6 6 file.txt Return value: 0 for successful execution, 1 for failure or negative results In C/C++ program, the main( ) function returns value In Bash, you use exit 1 to return 1 to caller …

4 Standard input, output, error
On startup, each program (bash script, C/C++ program) has access to three files: Keyboard input Putty window, terminal 4

5 input/output redirection
Review of the syntax ./a.out > my_output ./a.out < my_input ./a.out >> existing_output ./a.out < input > my_output 2> error_msg To discard output, redirect it to /dev/null What’s happening ? Shell opens/creates the files, and “starts” the program with its input/output/error redirected. Will study how it is done (through system calls) later … 5

6 Simple example: can you write C++ version?
A very simple C program #include <stdio.h> main() { char yourName[256]; printf ("Your name ?\n"); if (fgets (yourName,256,stdin)==NULL) fprintf (stderr,"No input"); else printf("hello, %s\n", yourName); } 6

7 Standard input Standard input (0):
Default: the keyboard How to read standard input from a file ? using < How to read standard input from the script ? Here document, << In bash script, use “read x” to read from standard input a value for variable x In C++: use cin

8 Standard output Standard output (1):
Default: terminal (window); can be redirect using >, or >> In C++: cout In C ? Will study later in this class Bash script: many commands write to standard output echo command printf command 8 8

9 Command line arguments
Strings passed after the command name; separated by spaces e.g. ls –l ~, rm –i *.o e.g. echo Hello world e.g. pick `cat students.txt` e.g. mv a.c b.c String enclosed by quotes are treated as single argument mv b.c “test b.c”, mv b.c ‘test b.c’

10 Command line arguments (cont’d)
Commands interpret the arguments Typically, dash (-) denotes an option e.g. the “-l” options for ls means “long listing” to remove a file named “-raw” ? rm “-raw” does not work rm ./-raw

11 Command line arguments (cont’d)
Access command line arguments Bash: $1,$2,… $#, $* Example: display_argument #!/bin/bash set -x i=1 while [ $i -lt $# ] do echo ${$i} i=`expr $i + 1` done

12 Script: reverse Functions: display command line arguments in reverse order, i.e., last word first, to standard output $ reverse apple banana orange orange banana apple

13 Next C/C++ programming with a focus on
Standard I/O File system access System calls To review Bash and Unix/Linux command One new command every Tuesday One bash new feature/exercise every Friday

14 C vs. C++: similarities Built-in data types: int, double, char, etc.
Preprocessor (handles #include, #define, etc.) Control structures: if, while, do, for, etc. 14

15 C vs. C++: similarities Operators: Arithmetic: + - * / ++ --
Assignment: = Comparison: == != < > >= <= if (i<=10) while (count!=20) Arithmetic/assignment: += -= *= /= counter += 1; // count = count+1; temp /= 10.0; // temp = temp/10.0; Logic: && || ! if (i<10 && !found) 15

16 C vs. C++: Similarities (cont’d)
There must be a function named main () Function definitions are done the same way Can split code into files (object modules) and link modules together

17 C vs. C++: Differences C does not support any function overloading
C does not have classes/objects All code is in functions (subroutines) C structures can not have methods C does not support any function overloading You cannot have two functions with same name In C++, compare (int first, int second) and compare(float first, float second) … C does not have reference variables remember in C++, double calculate_Area (Circle & myCircle);

18 C vs. C++: differences (cont.)
C input/output (I/O) is based on library functions printf, scanf , fopen, fclose, fread, fwrite,… In C++: cin, cout, cerr C does not have new or delete Use malloc, and free functions to handle dynamic memory allocation/deallocation C does not have string class In C++: string s("What we have here is a failure to communicate"); s=s+”!”; string sub = s.substr(21); cout << "The original string is " << s << endl; cout << "The substring is " << sub << endl;    

19 C string A “string” is an array of characters, terminated with null (‘\0’) char myStr[10]=“Hello”; myStr[0]=‘H’; myStr[1]=‘e’; myStr[2]=‘l’; myStr[3]=‘l’; myStr[4]=‘o’; myStr[5]=‘\0’; H e l l o \0

20 Handling strings in C char myStr[10]=“Hello”;
Library functions for operations on string: strcpy, strlen, strtok, strcat, … All using the ‘\0’ to tell where does a string ends … strcat (myStr, “!”);// append ! To the last non-null char str_len = strlen (myStr); // str_len is set to 5, the actual // length of the string, not the size of the array H e l l o \0

21 Typical C Program includes Defines, data type
#include <stdio.h> #include <stdlib.h> #define MAX 1000 typedef chra bigstring[MAX}; char * reverse (char *s ){ char buf[MAX}; int Ii, len; len=strlen(s); printf (“receiving %s\n”,s); for (i=0;i<len;i++) buf[i] = s[len-i-l]; buf[i] =‘\0’; strcpy (s,buf); return s; } void main (int argc, char ** argv){ if (argc==2) printf (“%s\n”,reverse (argv[1])); includes Defines, data type Definitions, global variable declarations Function definitions main()

22 C Libraries Standard I/O: printf, scanf, fopen, fread …
String functions: strcpy, strspn, strtok, … Math: sin, cos, sqrt, exp, abs, pow, log System calls: fork, exec, signal, kill,…

23 Simple C Program # include <stdio.h> int main (void) { printf (“Hello World \n”); return (0); }

24 Another Program #include <stdio.h> void printhello (int n ){ int i; for (i=0;i<n;i++) printf (“Hello world\n”); } void main(){ printhello(5);

25 Compiling on Unix We can use GNU compiler named gcc
gcc –o reverse reverse.cc Tells compiler to Create executable file with the Name reverse Tells compiler the name of input file

26 Quick I/O Primer: printf
int printf (const char *, … ); … means “variable number of arguments”, the first argument is required (a string). Given a simple string, printf just prints the string (to standard output).

27 Simple printf printf (“Hi – I am a string\n”); printf (“I\thave\ttabs\n”); char s[100]; strcpy(s, “printf is fun!\n”); printf (s);

28 Arguing with printf You can tell printf to embed some values in the string – these values are determined at run-time printf (“here is an integer: %d\n”, i); %d is replaced by value of the argument , i.e., i

29 More integer arguments
printf (“%d + %d = %d\n”, x, y, x+y); for (j=99;j>=0;j--) printf (%d bottles of beer on the wall\n”,j); printf (“%d is my favorite number\n”, 17);

30 printf is dumb %d is replaced by the value of the parameter when treated as an integer, even if the parameter is not an integer variable printf (“print an int %d\n”, “Hi Dave”); print an int printf ("print an int %d\n",12.3); print an int printf ("print chars as unsigned int %u %u %u\n",'a','b','c'); print chars as unsigned int

31 Other formats %d is a format – “treat the corresponding parameter as a signed integer” %u means unsigned integer %x means print as hexadecimal %s means “treat it as a string” %c is for character (char) %f is for floating point numbers %%: print a single ‘%’ e.g. printf (“%f%% of the population:\n”, 12.4);

32 Fun with printf char * s = “Hi Dave”;
printf (“the string \”%s\” is %d characters long\n”, s, strlen(s)); printf (“The square root of 10 is %f\n”,sqrt (10));

33 Controlling the output
There are formatting options that you can use to control field width, precision, etc. printf (“square root of 10 is %20.15f\n”,sqrt(10); square root of 10 is

34 Lining things up int i; for (i=0; i<5; i++)
printf (“%2d %f %20.15f\n”,I, sqrt(i),sqrt(i)); …..

35 Alas, we must move on There are more formats and format options for printf The man page for printf includes a complete description man 3 printf

36 Input - scanf scanf provides input from standard input
scanf use pointers, or addresses

37 Remember Memory Every C variable is stored in memory
Every memory location has an address In C, you can use variables called pointers to refer to variables by their address in memory

38 scanf int scanf (const char * format, … );
Remember “…” means “variable number of arguments” Uses format string to determine what kind of variable(s) it should read The arguments are the addresses of the variables scanf (%d %d”,&x,&y); x,y should be two integer variables

39 A simple example of scanf
float x; printf (“Enter a number\n”); scanf (“%f”,&x); printf (“Square root of %f is %f\n”,x,sqrt(x));

40 scanf and strings Using %s in a scanf tells scanf to read the next word from input – not a line of input char s[100]; printf (“Type in your name\n”); scanf (“%s”,&s); printf (“Your name is %s\n”,s);

41 Reading a line You can use function fgets to read an entire line
char *fgets (char *s, int size, FILE * stream); size is the maximum # of chars FILE is a file handle, for now, remember stdin (a constant): standard input Read a line (i.e., read character until newline is met or until reach maximum #) from specified file, and save to the string pointed to by s 41

42 Example of fgets char s[101]; printf (“Type in your name\n”); fgets (s,100,stdin); printf (“Your name is %s\n”,s);

43 A Real C Program A Program that accepts one command line argument
Treats the command line argument as a string, and reverses the letters in the string Prints out the reversed string For example $ ./reverse apple elppa $./reverse spring_song gons_gnirps

44 reverse.c (1) #include <stdio.h> /* printf */ #include <stdlib.h> /* malloc, free */ /* MAX is the size of largest string we can handle */ #define MAX 1000 typedef char bigstring[MAX];

45 reverse.c (2) /* reverses a string in place returns a pointer to the string */ char * reverse (char * s){ bigstring buf; int I, len; len = strlen (s); // fine the length of the string for (i=0;i<len;i++) buf[i] = s[len-i-1]; buf[i] = ‘\0’; // null terminate ! strcpy (s,buf); // put back to s return (s); }

46 reverse.c (3) void main (int argc, char ** argv) { if (argc<2){ printf (“Invalid usage: must supply s string\n”); exit(1); } printf (“%s\n”,reverse (argv[1]));

47 Using dynamic allocation
char * reverse (char * s) { char * buf; int I, len; len = strlen (s); // fine the length of the string buf = malloc (len+1); for (i=0;i<len;i++) buf[i] = s[len-i-1]; buf[i] = ‘\0’; // null terminate ! strcpy (s,buf); // put back to s free (buf); return (s); }

48 Compiling on Unix We can use GNU compiler named gcc
gcc –o reverse reverse.cc Tells compiler to Create executable file with the Name reverse Tells compiler the name of input file

49 Running the program $ ./reverse hidave evadih
$ ./reverse This is a long string sihT $./reverse “This is a long string” gnirts gnol a si sihT


Download ppt "C Programming CISC3130, Spring 2011 Dr. Zhang 1."

Similar presentations


Ads by Google