SysProg-Tutor 01 Introduction to C Programming Language
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

SysProg-Tutor 01 Introduction to C Programming Language

on

  • 743 views

 

Statistics

Views

Total Views
743
Views on SlideShare
743
Embed Views
0

Actions

Likes
1
Downloads
33
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

SysProg-Tutor 01 Introduction to C Programming Language Presentation Transcript

  • 1. Tutor Session - 1Chulalongkorn Tutor Session I: Introduction to C University Programming Language Wongyos Keardsri (P’Bank) Department of Computer Engineering Faculty of Engineering, Chulalongkorn University Bangkok, Thailand Mobile Phone: 089-5993490 E-mail: wongyos@gmail.com, MSN: bankberrer@hotmail.com Twitter: @wongyos 2110313 Operating Systems and System Programs (1/2010)
  • 2. Tutor Session - 1 Tutor OutlineChulalongkorn University Introduction While C History Do-While C Language VS Java Language For C Language Structure Functions and Program Types, Operators and Structure Expressions Non-Return Function Data Input and Output Return Function printf() The Standard C Library Functions scanf() Control Flow Array, Pointer and String If-Else Structures Switch File Operations 2 2110313 Operating Systems and System Programs (1/2010)
  • 3. Tutor Session - 1 IntroductionChulalongkorn University C History C is a structured computer programming language Appeared in1972 (1970s) Designed and Developed by Dennis Ritchie at the Bell Telephone Laboratories Derived from B and BCPL programming language Developed for the UNIX operating system 3 2110313 Operating Systems and System Programs (1/2010)
  • 4. Tutor Session - 1 IntroductionChulalongkorn University C History (Cont) Used and Implemented for: System programming Operating systems Embedded system applications C standard: ANSI C and ISO C Book: The C Programming Language, 2nd edition http://en.wikipedia.org/wiki/C_(programming_language) 4 2110313 Operating Systems and System Programs (1/2010)
  • 5. Tutor Session - 1 IntroductionChulalongkorn University C Language VS Java Language Example C Code (Hello.c) #include <stdio.h> main() { printf("Hello CPn"); } Example Java Code (Hello.java) public class Hello { public static void main(String[] args) { System.out.print("Hello CPn"); } } 5 2110313 Operating Systems and System Programs (1/2010)
  • 6. Tutor Session - 1 IntroductionChulalongkorn University C Language VS Java Language (Cont) C: Structured Java: Object-Oriented Programming Programming C Compiler Java Compiler (JVM) Editor: Turbo C, vi, etc. Editor: JLab, Eclipse, etc. Compile: (UNIX) Compile: gcc Hello.c javac Hello.java After compile After compile a.out Hello.class Run: Run: ./a.out java Hello Hello CP Hello CP Show an example Show an example 6 2110313 Operating Systems and System Programs (1/2010)
  • 7. Tutor Session - 1 IntroductionChulalongkorn University C Language Structure General format #include <stdio.h> Preprocessor / Including Library #include <…………………> main() { Begin Function main: [function-body]; [declaration-list] + [statement-list] } End . . Semicolon . type func() { Function func: [function-body]; [declaration-list] + [statement-list] } 7 2110313 Operating Systems and System Programs (1/2010)
  • 8. Tutor Session - 1 IntroductionChulalongkorn University C Language Structure (Cont) An example C code #include <stdio.h> main() { int sum; /* Variable declaration */ sum = 15 + 25; /* Value assignment */ printf("The sum of 15 and 25 is %dn", sum); } The sum of 15 and 25 is 40 8 2110313 Operating Systems and System Programs (1/2010)
  • 9. Tutor Session - 1 IntroductionChulalongkorn University C Language Structure (Cont) Compile C by UNIX command cc option file1 file2 … Example 1 gcc example.c Compile a.out ./a.out Run 9 2110313 Operating Systems and System Programs (1/2010)
  • 10. Tutor Session - 1 IntroductionChulalongkorn University C Language Structure (Cont) Example 2 gcc –c example.c Compile example.o Object file Convert to gcc –o example.run example.o Executable file example.run Executable file ./example.run Run 10 2110313 Operating Systems and System Programs (1/2010)
  • 11. Tutor Session - 1 IntroductionChulalongkorn University C Language Structure (Cont) Example 3 gcc –o example.run example.c Compile example.run Executable file ./example.run Run Wow 11 2110313 Operating Systems and System Programs (1/2010)
  • 12. Tutor Session - 1 Types, Operators and ExpressionsChulalongkorn University Data Types and Sizes char Character (8 bit) Ex. ‘A’, ‘a’, ‘F’ int Integer (16 bit) Ex. 12, -2456, 99851 float Real single (32 bit) Ex. 23.82, 567.008 double Real double (64 bit) Ex. 0.0002100009 short Shot integer (16 bit) Ex. -4, 18 long Long integer (32 bit) Ex. 9547604608456 unsigned Unsigned integer (16 bit) Ex. 2, 908, 1392 12 2110313 Operating Systems and System Programs (1/2010)
  • 13. Tutor Session - 1 Types, Operators and ExpressionsChulalongkorn University Variable Declaration type-specifier list-of-variables; Example int x, y, x = 5; float eps = 1.0e-5; int limit = MAXLINE+1; char s_name = A; char str[] = "Hello CP"; double dd = 0.000000000001; 13 2110313 Operating Systems and System Programs (1/2010)
  • 14. Tutor Session - 1 Types, Operators and ExpressionsChulalongkorn University Constant Declaration #define VARIABLE constant-value Note Example #define MAX 500 #include <stdio.h> #define XX 0 #define STEP 20 main() { #define PI 3.14159265 // Body program #define VTAB t } const char msg[] = "warning: "; const double e = 2.71828182845905; 14 2110313 Operating Systems and System Programs (1/2010)
  • 15. Tutor Session - 1 Types, Operators and ExpressionsChulalongkorn University Expression and Operations Arithmetic Operators Addition + Subtraction - Multiplication * Division / Modulation % Example fag = x % y; c = a – (a/b)*b; sum = var1 + var2 + var3; 15 2110313 Operating Systems and System Programs (1/2010)
  • 16. Tutor Session - 1 Types, Operators and ExpressionsChulalongkorn University Expression and Operations (Cont) Relational Operators Less than < a < 5 Less than or equal <= a <= b More than > a > b+c More than or equal >= a >= b + 5 Equal == a == -6 Not equal != a != 0 Logical Operators AND && (a > 0) && (b > 0) OR || (a <= 0) || (b <= 0) Negation ! !(a && c) 16 2110313 Operating Systems and System Programs (1/2010)
  • 17. Tutor Session - 1 Types, Operators and ExpressionsChulalongkorn University Expression and Operations (Cont) Bitwise Operators Bitwise AND & Bitwise OR (Inclusive OR) | Bitwise XOR (Exclusive OR) ^ Left shift << Right shift >> Ones complement ~ Example x = 01001011 y = 00101100 ~x = 10110100 x & y = 00001000 x | y = 01101111 x ^ y = 01100111 x << 2 = 00101100 17 2110313 Operating Systems and System Programs (1/2010)
  • 18. Tutor Session - 1 Types, Operators and ExpressionsChulalongkorn University Expression and Operations (Cont) Assignment Operators and Expressions op is + - * / % << >> & ^ | If expr1 and expr2 are expressions, then expr1 op= expr2 Equivalent to expr1 = (expr1) op (expr2) Example X += 1; Equivalent X = X + 1; 18 2110313 Operating Systems and System Programs (1/2010)
  • 19. Tutor Session - 1 Types, Operators and ExpressionsChulalongkorn University Expression and Operations (Cont) Conditional Expressions expr1 ? expr2 : expr3 If expr1 is true do expr2 If expr1 is false do expr3 Example a = 5; b = 10; min = (a < b) ? a : b; 19 2110313 Operating Systems and System Programs (1/2010)
  • 20. Tutor Session - 1 Types, Operators and ExpressionsChulalongkorn University Expression and Operations (Cont) Increment and Decrement Operators Pre-increment operation ++variable Post-increment operation variable++ Pre-decrement operation --variable Post-decrement operation variable-- Example x = 4; y = x++ + 5; //x = 5, y = 9 x = 4; y = ++x + 5; //x = 5, y = 10 20 2110313 Operating Systems and System Programs (1/2010)
  • 21. Tutor Session - 1 Types, Operators and ExpressionsChulalongkorn University Expression and Operations (Cont) Type Cast Operator (Casting) (type-specifier) expression; Example (double) date; float var1 = 2.7; int var2 = (int) var1; //var2 = 2 (char) x; (int) d1 + d2; 21 2110313 Operating Systems and System Programs (1/2010)
  • 22. Tutor Session - 1 Data Input and OutputChulalongkorn University printf() Statement printf() is a function for display result to standard output (Monitor, Screen) printf(format, arg1, arg2, …); Example printf(“Hellon”); //Hello int num = 2; printf(“%d is integer”, num); //2 is integer 22 2110313 Operating Systems and System Programs (1/2010)
  • 23. Tutor Session - 1 Data Input and OutputChulalongkorn University printf() Statement (Cont) Conversion Operation [printf()] d signed decimal conversion of an int or a long u unsigned decimal conversion of unsigned o unsigned octal conversion of unsigned x, X unsigned hexadecimal conversion of unsigned x = [a – f], X = [A - F] c single character conversion s string conversion f signed decimal floating point conversion e, E signed decimal floating point conversion in scientific notation 23 2110313 Operating Systems and System Programs (1/2010)
  • 24. Tutor Session - 1 Data Input and OutputChulalongkorn University printf() Statement (Cont) Example of printf() int j = 45, k = -123; float x = 12.34; char c = ‘w’; Result char *m = “Hello”; printf(“Hello 55”); Hello 55 printf(“Tax is %d”, j); Tax is 45 printf(“%d”, j+k); -78 printf(“%3d %d”, j, k); 45 -123 printf(“%f %.2f”, x, x); 12.340000 12.34 printf(“%c”, c); w printf(“%sn”, m); Hello printf(“%sn”, “Hello”); Hello printf(“%10sn”, “Hello”); Hello 24 2110313 Operating Systems and System Programs (1/2010)
  • 25. Tutor Session - 1 Data Input and OutputChulalongkorn University scanf() Statement scanf() is a function for read input from standard input (Keyboard) scanf(format, arg1, arg2, …); Example scanf(“%d %d %d”, &day, &month, &year); int num; printf(“Enter integer : ”); scanf(“%d”, &num); // Enter integer : 23 25 2110313 Operating Systems and System Programs (1/2010)
  • 26. Tutor Session - 1 Data Input and OutputChulalongkorn University scanf() Statement (Cont) Conversion Operation [scanf()] d signed decimal conversion of an int or a long u unsigned decimal conversion of unsigned o unsigned octal conversion of unsigned x, X unsigned hexadecimal conversion of unsigned x = [a – f], X = [A - F] c single character conversion s string conversion f signed decimal floating point conversion e, E signed decimal floating point conversion in scientific notation [] read only character in [ ], if [^ ] read different character 26 2110313 Operating Systems and System Programs (1/2010)
  • 27. Tutor Session - 1 Data Input and OutputChulalongkorn University scanf() Statement (Cont) Example of scanf() int d,m,y,x; char ch1,ch2; Result float f; scanf(“%d”, &x); 4 // x=4 scanf(“%2d%2d%4d”, &d,&m,&y); 22062007 // d=22, m=6, y=2007 scanf(“%d/%d/%d”, &d,&m,&y); 22/06/2007 // d=22, m=6, y=2007 scanf(“%c%c”, &ch1,&ch2); Ab // ch1=‘A’, ch2=‘b’ scanf(“%f”, &f); 2.3 // f=2.300000 27 2110313 Operating Systems and System Programs (1/2010)
  • 28. Tutor Session - 1 Control FlowChulalongkorn University Decision Statements If-Else Statement The if-else statement is used to express decisions. Formally the syntax is if (expression) { true statement } else { false statement } 28 2110313 Operating Systems and System Programs (1/2010)
  • 29. Tutor Session - 1 Control FlowChulalongkorn University Decision Statements (Cont) Nested If-Else The sequence of if statements is the most general way of writing a multi-way decision. Formally the syntax is if (expression) { statement } else if (expression) { statement } else if (expression) { statement } else { statement } 29 2110313 Operating Systems and System Programs (1/2010)
  • 30. Tutor Session - 1 Control FlowChulalongkorn University Decision Statements (Cont) Example of If-Else if (a < b) { if (score >= 80) printf(“a less than grade = ‘A’; bn”); else if (score >= 70) } else { grade = ‘B’; temp = a; else if (score >= 50) a = b; /* swap a */ grade = ‘C’; b = temp; /* and b */ else if (score >= 40) printf(“Interchange a grade = ‘D’; and bn”); else } grade = ‘F’; 30 2110313 Operating Systems and System Programs (1/2010)
  • 31. Tutor Session - 1 Control FlowChulalongkorn University Decision Statements (Cont) Switch Statement The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly. switch (expression) { case const-expr: statements case const-expr: statements default: statements } 31 2110313 Operating Systems and System Programs (1/2010)
  • 32. Tutor Session - 1 Control FlowChulalongkorn University Decision Statements (Cont) Example of Switch c = getchar(); switch (c) { case 0: printf(“Zeron”); break; case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: printf(“Ninen”); break; case : case n: newln++; break; case t: tabs++; break; default: printf(“missing charn”); break; } 32 2110313 Operating Systems and System Programs (1/2010)
  • 33. Tutor Session - 1 Control FlowChulalongkorn University Iteration Statements While Statement The expression is evaluated. If it is true, statement is executed and expression is reevaluated. This cycle continues until expression becomes false. while (expression) { Statement1; Statement2; ... } 33 2110313 Operating Systems and System Programs (1/2010)
  • 34. Tutor Session - 1 Control FlowChulalongkorn University Iteration Statements (Cont) Example of While #include <stdio.h> #define DOT ‘.’ main() { char C; while ((C = getchar())!= DOT) putchar(C); printf(“Good Bye.n”); } Result? 34 2110313 Operating Systems and System Programs (1/2010)
  • 35. Tutor Session - 1 Control FlowChulalongkorn University Iteration Statements (Cont) Do-While Statement The do-while, tests at the bottom after making each pass through the loop body; the body is always executed at least once. do { statement1; statement2; … } while (expression); 35 2110313 Operating Systems and System Programs (1/2010)
  • 36. Tutor Session - 1 Control FlowChulalongkorn University Iteration Statements (Cont) Example of Do-While int i = 1, sum = 0; do { sum += i; i++; } while (i <= 50); printf(“The sum of 1 to 50 is %dn”, sum); Result? 36 2110313 Operating Systems and System Programs (1/2010)
  • 37. Tutor Session - 1 Control FlowChulalongkorn University Iteration Statements (Cont) For Statement The for statement for (initial; expression; update) { statement; } Equivalent to initial; while (expression) { statement; update; } 37 2110313 Operating Systems and System Programs (1/2010)
  • 38. Tutor Session - 1 Control FlowChulalongkorn University Iteration Statements (Cont) Example of For for (i=1;i<=100;i++) { x += i; if ((x % i) == 0) { i--; } } for (i=0, j=strlen(s)-1; i<j; i++,j--) { c = s[i], s[i] = s[j], s[j] = c; } char c; int count; for (count=0; (c=getchar() != ‘.’); count++) { } printf(“Number of characters is %dn”, count); 38 2110313 Operating Systems and System Programs (1/2010)
  • 39. Tutor Session - 1 Control FlowChulalongkorn University Sequential Statements Break and Continue Statement The break statement provides an early exit from for, while, and do-while. break; The continue statement is related to break, but less often used; it causes the next iteration of the enclosing for, while, or do-while loop to begin. continue; 39 2110313 Operating Systems and System Programs (1/2010)
  • 40. Tutor Session - 1 Control FlowChulalongkorn University Sequential Statements (Cont) Example of Break and Continue int c; while ((c = getchar()) != -1) { if (C == ‘.’) break; else if (c >= ‘0’ && c <= ‘9’) continue; else putchar(c); } printf(“*** Good Bye ***n”); 40 2110313 Operating Systems and System Programs (1/2010)
  • 41. Tutor Session - 1 Functions and Program StructureChulalongkorn University Functions (Method in Java) break large computing tasks into smaller ones, and enable people to build on what others have done instead of starting over from scratch. function-name (argument declarations) { [ declaration-list] [ statement-list ] } 41 2110313 Operating Systems and System Programs (1/2010)
  • 42. Tutor Session - 1 Functions and Program StructureChulalongkorn University (Cont) Example of Function /* Programming in function */ main() { int hours, minutes, seconds; int total_time = 0; int convert(); printf(“Enter time in hours-minutes-seconds : “); scanf(“%d %d %d”, &hours, &minutes, &seconds); total_time = convert(hours, minutes, seconds); /* calling point */ printf(“The converted time is %d secondsn”, total_time); } 42 2110313 Operating Systems and System Programs (1/2010)
  • 43. Tutor Session - 1 Functions and Program StructureChulalongkorn University (Cont) Example of Function (Cont) /* Function (called function) */ int convert (h, m, s) int h, m, s; { int time; /* return-value variable */ time = (60 * h + m) * 60 + s; return time; /* exiting point */ } 43 2110313 Operating Systems and System Programs (1/2010)
  • 44. Tutor Session - 1 Functions and Program StructureChulalongkorn University Non-Return Function Example of Non-Return Function /* Main */ main() { void display(); display(); } /* Function Part */ void display() { printf(“*** Hello and Good bye ***”); } 44 2110313 Operating Systems and System Programs (1/2010)
  • 45. Tutor Session - 1 Functions and Program StructureChulalongkorn University Return Function Example of Return Function /* Main Function */ main() { float sq,x; float square(); sq = square(x); printf(“The square of x is %fn”, sq); } /* Function: square */ float square(x) { return(x * x); } 45 2110313 Operating Systems and System Programs (1/2010)
  • 46. Tutor Session - 1 Functions and Program StructureChulalongkorn University External Variable Example of External Variable main() { int k = 15; k = 5 func1(); k = 5 func2(); k = 15 printf(“k = %dn”, k); } int k = 5; /* External Variable */ func1() { printf(“k = %dn”, k); } /*Function 1*/ func2() { printf(“k = %dn”, k); } /*Function 2*/ 46 2110313 Operating Systems and System Programs (1/2010)
  • 47. Tutor Session - 1 Functions and Program StructureChulalongkorn University Recursive Function Example of Recursive Function main() { /* Main Part */ int j; long int factorial(); for (j = 0; j <= 10; j++) printf(“%2d! is %ldn”, j, factorial(j)); } long int factorial(n) /* Function Part */ int n; { if (n == 0) return (1); else return (n * factorial(n-1)); } 47 2110313 Operating Systems and System Programs (1/2010)
  • 48. Tutor Session - 1 Functions and Program StructureChulalongkorn University The Standard C Library Functions #include <stdio.h> clearerr fprintf fwrite rewind fclose fputc getc scanf feof fputs getchar sprintf ferror Fread gets sscanf fflush freopen printf ungetc fgetc fscanf putc fgets fseek putchar fopen ftell puts 48 2110313 Operating Systems and System Programs (1/2010)
  • 49. Tutor Session - 1 Functions and Program StructureChulalongkorn University The Standard C Library Functions (Cont) #include <math.h> acos(x) floor(x) atan2(x,y) asin(x) log(x) power(x,y) atan(x) log10(x) ceil(x) sin(x) cos(x) sinh(x) cosh(x) sqrt(x) exp(x) tan(x) fabs(x) tanh(x) 49 2110313 Operating Systems and System Programs (1/2010)
  • 50. Tutor Session - 1 Functions and Program StructureChulalongkorn University The Standard C Library Functions (Cont) #include <ctype.h> isalnum ispunct isalpha isspace isascii isupper iscntrl tolower isdigit toupper isgraph islower isprint 50 2110313 Operating Systems and System Programs (1/2010)
  • 51. Tutor Session - 1 Array, Pointer and StringChulalongkorn University Array Array is a group of related data items. In C, there is a strong relationship between pointers and arrays, strong enough that pointers and arrays should be discussed simultaneously. The declaration of one-dimensional array type array-name[number-of-elements]; int a[15]; a[0], a[1], a[2], … , a[14] = 15 Element 51 2110313 Operating Systems and System Programs (1/2010)
  • 52. Tutor Session - 1 Array, Pointer and StringChulalongkorn University Array (Cont) In the main memory Value Address a a[0] 5501 a[1] 5502 a[2] 5503 … … int a[15]; … … … … a[14] 5514 52 2110313 Operating Systems and System Programs (1/2010)
  • 53. Tutor Session - 1 Array, Pointer and StringChulalongkorn University Array (Cont) Example of Array /* Read five integers from the standard input and display them in reverse order */ #define MAX 5 main() { int j; int a[MAX]; for (j = 0; j < MAX; j++) scanf(“%d”, &a[j]); for (j = MAX - 1; j >= 0; j--) printf(“%dn”, a[j]); } 53 2110313 Operating Systems and System Programs (1/2010)
  • 54. Tutor Session - 1 Array, Pointer and StringChulalongkorn University Pointer A pointer is a variable that contains the address of a variable. Example of pointer Value Address x 25 7960 x = 25 int x = 25; int *px; … px = &x; int y = *px; px 7960 8132 px = &x //y = x = 25 y y = *px 54 2110313 Operating Systems and System Programs (1/2010)
  • 55. Tutor Session - 1 Array, Pointer and StringChulalongkorn University Pointer (Cont) Example (Cont) main() { int x = 5, *px; px = &x; int y = *px; printf("x = %dn", x); x = 5 printf("y = %dn", y); y = 5 printf("*px = %dn", *px); *px = 5 printf("&x = %dn", &x); &x = -4195036 printf("px = %dn", px); px = -4195036 printf("&y = %dn", &y); &y = -4195044 x = 34; printf("px = %dn", px); px = -4195036 printf("*px = %dn", *px); *px = 34 printf("y = %dn", y); y = 5 } 55 2110313 Operating Systems and System Programs (1/2010)
  • 56. Tutor Session - 1 Array, Pointer and StringChulalongkorn University Pointer (Cont) Example int x; int *px, *py; px x px = &x; py py = px; main() { int t[10]; int *pt; for (pt = t; pt < &t[10]; pt++) scanf(“%d”, pt); for (pt = &t[10]; pt >= t; pt--) printf(“%dn”, *pt); } 56 2110313 Operating Systems and System Programs (1/2010)
  • 57. Tutor Session - 1 Array, Pointer and StringChulalongkorn University Pointer (Cont) Example (Cont) int x = 1, y = 2, z[10]; int *ip; /* ip is a pointer to int */ ip = &x; /* ip now points to x */ y = *ip; /* y is now 1 */ *ip = 0; /* x is now 0 */ ip = &z[0]; /* ip now points to z[0] */ Help me!! 57 2110313 Operating Systems and System Programs (1/2010)
  • 58. Tutor Session - 1 Array, Pointer and StringChulalongkorn University String A string constant, written as "I am a string" is an array of characters. In the internal representation, the array is terminated with the null character 0 so that programs can find the end. Example char amessage[] = "now is the time"; /* an array */ char *pmessage = "now is the time"; /* a pointer */ 58 2110313 Operating Systems and System Programs (1/2010)
  • 59. Tutor Session - 1 Array, Pointer and StringChulalongkorn University String (Cont) Example of String char s1[] = “xyz”; char s2[] = {‘x’, ‘y’, ‘z’, ‘0’}; char *s3 = “xyz”; x y z 0 59 2110313 Operating Systems and System Programs (1/2010)
  • 60. Tutor Session - 1 Array, Pointer and StringChulalongkorn University String (Cont) Example /* COUNT THE LENGTH OF STRING */ main() { char *w = “good morning”; int len(); printf(“Lengths of string is %dn”, len(w)); } /* FUNCTION: len() for counting the length of string */ int len(string) char string[]; // char *string; { int count = 0; while (string[count] != NULL) count++; return (count); } 60 2110313 Operating Systems and System Programs (1/2010)
  • 61. Tutor Session - 1 StructuresChulalongkorn University A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling. Structures are called "records insome languages, notably Pascal. struct structure-name { type-specifier variable; Members ... }; 61 2110313 Operating Systems and System Programs (1/2010)
  • 62. Tutor Session - 1 StructuresChulalongkorn University (Cont) Example of Structure struct person { Record = Node int code; char name[30]; int string string float char address[40]; code name address salary float salary; }; struct point { int x; int x int y int y; }; 62 2110313 Operating Systems and System Programs (1/2010)
  • 63. Tutor Session - 1 StructuresChulalongkorn University (Cont) A struct declaration defines a type. struct structure-name variable-name,…; Or declare in struct structure-name { type-specifier variable; ... }variable-name; 63 2110313 Operating Systems and System Programs (1/2010)
  • 64. Tutor Session - 1 StructuresChulalongkorn University (Cont) Example of Structure Declaration struct person { struct person { int code; int code; char name[30]; char name[30]; char address[40]; or char address[40]; float salary; float salary; }; }p; struct person p; 64 2110313 Operating Systems and System Programs (1/2010)
  • 65. Tutor Session - 1 StructuresChulalongkorn University (Cont) A member of a particular structure is referred to in an expression by a construction of the form struct-variable-name.member-name Example p.code; p.name; p.address; p.salary; 65 2110313 Operating Systems and System Programs (1/2010)
  • 66. Tutor Session - 1 StructuresChulalongkorn University (Cont) Example of Struct Program /* ASSIGN AND PRINT A DATE */ main() { struct date { //Result int dd = 22; Date is 22/ 6/2007 int mm; int yyyy; }; struct date today; today.mm = 6; today.yyyy = 2007; printf(“Date is %2d/%2d/%4dn”, today.dd, today.mm, today.yyyy); } 66 2110313 Operating Systems and System Programs (1/2010)
  • 67. Tutor Session - 1 File OperationsChulalongkorn University The input and output functions, types, and macros defined in <stdio.h> represent nearly one third of the library. The following functions deal with operations on files: fopen(filename, mode); fclose(file pointer); feof(file pointer); getc(); putc(); 67 2110313 Operating Systems and System Programs (1/2010)
  • 68. Tutor Session - 1 File OperationsChulalongkorn University (Cont) fopen() - opens the named file, and returns a stream, or NULL if the attempt fails. Legal values for mode include: "r" open text file for reading "w" create text file for writing; discard previous contents if any "a" append; open or create text file for writing at end of file "r+" open text file for update (reading and writing) "w+" create text file for update, discard previous contents if any "a+" append; open or create text file for update, writing at end 68 2110313 Operating Systems and System Programs (1/2010)
  • 69. Tutor Session - 1 File OperationsChulalongkorn University (Cont) Example of fopen() to open file FILE *file; File Pointer FILE *fopen(); if ((file = fopen(“person.dat”, “r”)) == NULL) printf(“Cannot open a data filen”); else ... 69 2110313 Operating Systems and System Programs (1/2010)
  • 70. Tutor Session - 1 File OperationsChulalongkorn University (Cont) fclose() – close file, flushes any unwritten data for stream, discards any unread buffered input, frees any automatically allocated buffer, then closes the stream. It returns EOF if any errors occurred, and zero otherwise. Example int fclose(); ... if (fclose(file) != EOF) printf(“Cannot close filen”; else printf(“Now file is closedn”); 70 2110313 Operating Systems and System Programs (1/2010)
  • 71. Tutor Session - 1 File OperationsChulalongkorn University (Cont) feof() – check for end of file. if (!feof(file)) printf(“It is not the end of file nown”); getc() is equivalent to fgetc except that if it is a macro, it may evaluate stream more than once. int getc(file pointer); putc() is equivalent to fputc except that if it is a macro, it may evaluate stream more than once. int putc(char c, file pointer); putchar(c) is equivalent to putc(c,stdout). int putchar(char c); 71 2110313 Operating Systems and System Programs (1/2010)
  • 72. Tutor Session - 1 File OperationsChulalongkorn University (Cont) fprintf() converts and writes output to stream under the control of format. The return value is the number of characters written, or negative if an error occurred. int fprintf(file pointer, format, ...) fscanf() reads from stream under control of format, and assigns converted values through subsequent arguments, each of which must be a pointer. int fscanf(file pointer, format, ...) 72 2110313 Operating Systems and System Programs (1/2010)
  • 73. Tutor Session - 1 File OperationsChulalongkorn University (Cont) Example of File Operations Program /* A PROGRAM TO WRITE ONE LINE TO sample.txt */ #include <stdio.h> main() { FILE *fp; char c = ‘ ‘; fp = fopen(“sample.txt”, “w”); printf(“Enter text belown”); while (c != ‘n’) { c = getchar(); putc(c, fp); } fclose(fp); } 73 2110313 Operating Systems and System Programs (1/2010)
  • 74. Tutor Session - 1 File OperationsChulalongkorn University (Cont) Example of File Operations Program (Cont) /* A PROGRAM TO READ TEXT FROM sample.txt AND DISPLAY ON A MONITOR */ #include <stdio.h> main() { FILE *fp; char c; fp = fopen(“sample.txt”, “r”); if (fp == NULL) printf(“The file cannot be openedn”); else while ((c = getc(fp) != EOF) putchar(c); fclose(fp); } 74 2110313 Operating Systems and System Programs (1/2010)
  • 75. Tutor Session - 1 EndChulalongkorn University Question ? … Answer 75 2110313 Operating Systems and System Programs (1/2010)