Composed for Composed for SE 115 C programming SE 115 C programming Faculty of Engineering & Faculty of Engineering & Computer Sciences Computer Sciences Izmir University of Economics Izmir University of Economics Assoc. Prof. Dr. Süleyman Kondakci [email protected]http://homes.ieu.edu.tr/skondakci
A general coverage of the C language is presented. These slides are useful for students attending C courses at universities and other institutions as well as others following C tutorials or learning the language by themselves. Comments are welcome for creating better future. Faculty of Eng. & Computer Sciences of IEU, Izmir-Turkey, Assoc. Prof. Dr. S. Kondakci
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Composed for Composed for
SE 115 C programmingSE 115 C programmingFaculty of Engineering & Faculty of Engineering &
Computer Sciences Computer Sciences
Izmir University of EconomicsIzmir University of Economics
z = (x == 0); /*** logical operator; re sult --> 0 or 1 ***/
z = (x = 0); /*** assignment operator; result --> ***/
z = (x == 1);
z = (x = 15);
z = (x != 2);
z = (x < 10);
z = (x <= 50);
z = ((x=y) < 10); /*** performs assignment, comp ares with 10 ***/
z = (x==5 && y<15);
z = (x==5 && y>5 && w==10);
z = (x==5 || y>5 && w==10);
z = (T && T && F && x && x); /*** ==> F; ***/
z = (F || T || x || x); /*** ==> T; ***/
/*** value of x doesn't matter ***/
Input to & Output From Program Input to & Output From Program
Input: scanf ("format specifier", variable)
Output: printf ("format specifier", variable)
Format specifiers
%c = as a character
%d = as a decimal integer
%e = as a floating-point number in scientififc notation
%f = as a floating-point number
%g = in the e-format or f-format, whichever is shor ter
%s = as a string of characters
Small Sample ProgramsSmall Sample Programs
/*hello.c - traditional zeroth program*/#include <stdio.h>
int main(){
printf( " Hello world!\n");return 0;
}
Hello world!
On the screen
Escape SequencesEscape Sequences
\a bell
\t horizontal tab
\' single quote
\n newline
\r carriage return
\b backspace
\v vertical tab
\" double quote
\? question mark
\f formfeed
\\ backslash
\ooo octal number
\xhhhexadecimal number
Escaped characters produce visual and audible effects
The Output Function (printf)The Output Function (printf)
Character
Argument Type; Printed As
d, I int ; decimal number
o int ; unsigned octal number (without a leading zero)
x, Xint ; unsigned hexadecimal number (without a leading Ox or OX, usingabcdef or ABCDEFfor 10,...,15)
u int ; unsigned decimal number
c int ; single character
schar; print characters from the string until a '\0' or the number of charachters given by the precision
f double; [-]m.dddddd, where the number of d's is given by the precision (default is 6)
e, Edouble; [-]m.dddddde ±xxor [-]m.ddddddE ±xxwhere the number of d's is given by the precision (default is 6)
g, Gdouble; use %e or %E if the exponent is less than -4 or greater than or equal to the precision; otherwise use %f; trailing zeros and a trailing decimal point are not printed
p void * ; pointer (implementation-dependent representation)
% no argument is converted; print a %
The Input Function (scanf)The Input Function (scanf)
Character
Input Data; Argument Type
d decimal integer; int *
Iinteger; int * ; the integer may be in octal (leading 0) or hexadecimal (leading 0x or 0X)
o octal intger (with or without leading zero); int *
u unsigned decimal integer; unsigned int *
x hexadecimal number (with or without a leading 0x or 0X); int *
ccharacters; char *. The next input characters (default 1) are placed at the indicated spot. The normal skip over white space is suppressed; to read the next non-white space character, use %1s
scharacter string (not quoted); char * ; pointing to an array of characters large enough for the string and a terminating `\0' that will be added
e, f, gfloating-point number with optional sign, optional decimal point, and optional exponent; float *
% literal %; no assignment is made
A Very Tiny ProgramA Very Tiny Program
/*fahr.c (several versions) - convert Fahrenheit to Celsius. Originally not mine, SK*/
int main(){int fahr = 42, cels;cels = 5*(fahr-32)/9;printf("%d degrees Fahrenheit is %d degrees
Celsius\n", fahr, cels);return 0;}
C ProgrammingC Programming
The if StatementThe if Statement
if( expression 1)
statement 1;
else if ( expression 2)
statement 2;
else statement 3
The if statement has two forms:1) Plain if:
Nested if StatementNested if Statement
if (expression) {if (expression) {if (expression) {if (expression) {
if (expression) {if (expression) {if (expression) {if (expression) {
statements statements statements statements
if (expression) { if (expression) { if (expression) { if (expression) {
statementsstatementsstatementsstatements
}}}}
}}}}
} else {} else {} else {} else {
statementsstatementsstatementsstatements
}}}}
2) Nested if:
The The ?? :: decision decision operatoroperatorss
expression1?expression2: expression3
Same as
if(expression1) expression2
else expression3
Example: Example: The The ?? and and :: operatoroperatorss
X = 12;
y = (x < 5) ? 5 : 10;
Gives the same result as this
if (x < 5) y = 5;
else
y = 10;
C Language Blocks and StylingC Language Blocks and Styling
{
Statements
}
{
{
... {
}
}
}
inner block
outer block
single block
Multiple nested block structure
Example: Single BlockExample: Single Block
for (i=0; i<=10; i++) {
printf("index is: %d", i);
}
if (a == b && a <= c || c >0)
printf("Aha!! \a\a");
You can aslo write like this:
if (a == b && a <= c || c >0)
{
printf("Aha!!\a\a");
}
Or
if (a == b && a <= c || c >0) printf("Aha!!\a\a");
Example: Example: forfor and and whilewhile LoopsLoops
#include <stdio.h>
#include <stdlib.h>
int main(){
int i;
for(i = 0; i <= 10; i++){
printf("%d\n", i);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(){
int i;
i = 0;
while(i <= 10){
printf("%d\n", i);
i++;
}
return 0;
}
Example: Example: dodo--whilewhile LoopLoop
#include <stdio.h>
#include <stdlib.h>
int main(){
int i; i = 0;
/* check */
do {
printf("%d\n", i);
/* increment i */
i++;
} while(i <= 10);
return 0;
}
The The switchswitch StatementStatement
expressionexpressionexpressionexpression = some_value= some_value= some_value= some_value; /* can be the result of another ; /* can be the result of another ; /* can be the result of another ; /* can be the result of another
expression or a user defined value. */expression or a user defined value. */expression or a user defined value. */expression or a user defined value. */
some_valuesome_valuesome_valuesome_value can be can be can be can be const1, const2,..., const100const1, const2,..., const100const1, const2,..., const100const1, const2,..., const100 or elseor elseor elseor else
Example: Example: switchswitch vs vs ifif StatementStatement
#include <stdio.h>#include <stdlib.h>
int main(){int i; for(i = 0; i <= 3; i++){
switch(i){case 1: printf("1 \n");
break;case 2: printf("2 \n");
break;case 3: printf("3 \n");
break;default:
printf("default\n");break;
}}
return 0;}
#include <stdio.h>#include <stdlib.h>
int main(){int i;
for(i = 0; i <= 3; i++){if (i == 1) printf("1 \n");else if (i == 2) printf("2 \n");else if (== 3) printf("3 \n");else printf("default\n");
}return 0;
}
The The breakbreak statemet: Get out of the loop!statemet: Get out of the loop!
#include <stdio.h>
#include <stdlib.h>
int main(){
int i;
for(i = 0; i < 100000000; i++){
printf("Press s to stop");
if(getchar() == 's')
break;
printf("%d\n", i);
}
return 0;
}
The The continuecontinue Statement: Skip some partsStatement: Skip some parts
#include <stdio.h>
int main(){
int i;
for(i = -10; i < 10; i++){
if(i == 0 || i==6 || i == 9 )
// do not display 0, 6, and 9, continue with others
continue;
printf("%d \n", i);
// Other statements .....
}
return 0;
}
C ProgrammingC Programming
Functions Functions -- why and how ?why and how ?
•• If a program is too If a program is too
longlong
•• Modularization Modularization ––
easier to easier to
•• codecode
•• debugdebug
•• Code reuseCode reuse
•• Passing Passing
arguments to arguments to
functionsfunctions
–– By valueBy value
–– By referenceBy reference
•• Returning values Returning values
from functionsfrom functions
–– By valueBy value
–– By referenceBy reference
Definition and Usage of FunctionsDefinition and Usage of Functions
#include <stdio.h>#include <stdlib.h>/** function prototype declarations start here**/int add(int a, int b);int GetPosinteger(void); // or just int GetPosinteg er(); /** End of function prototype declarations **/int main(){
int x, y, z;x = GetPosinteger();y = GetPosinteger();printf("%d + %d = %d\n", x, y, add(x,y));return 0;
}int add(int a, int b){
return a+b;}int GetPosinteger(void){
int a;do
{printf("Enter a positive integer: ");scanf("%d", &a);
} while (a <= 0);return a;
}
FunctionsFunctions are subprograms!are subprograms!
The syntax for declaring a function:return-type function-name (argument declarations){
local variable declarationsStatements
}
Signature (or prototype) of a function:return-type function-name (argument list)
VoidVoid in in voidvoid out or out or return valuereturn value
void print_message( void ) // Inputs are void!
{
// Here void means no input parameter and no return value
printf("hello"); // No return
}
int add(int a, int b) // We have two int inputs a & b
{
int sum;
sum = a + b;
return sum; // This is the output (return value)
}
Functions – Call by Value
#include <stdio.h>int sum(int a, int b);
/* function prototype at start of file */
void main(void){int total = sum(4,5); /* call to the function */
printf("The sum of 4 and 5 is %d", total);}
int sum(int a, int b){ /* the function itself - arguments passed by value*/
return (a+b); /* return by value */}
Functions- Call by Reference (later!!)
#include <stdio.h>/* function prototype at start of the code */int sum(int *pa, int *pb); // Pointer references as input
void main(void){int a=4, b=5;int *ptr = &b; int total;total = sum(&a,ptr); /* call to the function */printf("The sum of 4 and 5 is %d", total);
}
int sum(int *pa, int *pb){ /* the function definition here- arguments passed by reference */return (*pa+*pb); /* return by ref */
}
C ProgrammingC Programming
Making Making MenusMenus for Usersfor Users
void menu (){
printf("The following options\n");printf("R ==> Register a book\n ");printf("D ==> Display data about all books\ n "); printf("F ==> Find and show a book\n "); printf("Enter [R,D,F] or [Q] to Quit: ");
}
Using functions with Using functions with MenuMenu
void main(void){
char opt;menu();opt=getchar();
do {switch (opt) {
case 'r'| R': Register(); break;case 'f'|'F': Find(); break; case 'd'|'D': Show_data(); break;case 'd'|'D': break();default: menu(); opt=getchar();break;
/* Some global constant definitions, if required ... *//* Some global constant definitions, if required ... *//* Some global constant definitions, if required ... *//* Some global constant definitions, if required ... */
/* Start of function /* Start of function /* Start of function /* Start of function defsdefsdefsdefs */*/*/*/
// End of function // End of function // End of function // End of function DefsDefsDefsDefs
/* End of function /* End of function /* End of function /* End of function DefsDefsDefsDefs */*/*/*/
/* Start of main(), Action definitions *//* Start of main(), Action definitions *//* Start of main(), Action definitions *//* Start of main(), Action definitions */
int int int int main() {main() {main() {main() {
/* Some local variable and constant /* Some local variable and constant /* Some local variable and constant /* Some local variable and constant defsdefsdefsdefs */*/*/*/
short int opt;short int opt;short int opt;short int opt;
case 6: exit(); /* exit the loop, hence the program */case 6: exit(); /* exit the loop, hence the program */case 6: exit(); /* exit the loop, hence the program */case 6: exit(); /* exit the loop, hence the program */
}}}}
} while(1);} while(1);} while(1);} while(1); /* End of while *//* End of while *//* End of while *//* End of while */
return 0;return 0;return 0;return 0;
} /* End of main() */} /* End of main() */} /* End of main() */} /* End of main() */
C ProgrammingC Programming
RecursionRecursion
Recursion = a function calls itself as a function for unknown times. We call this recursive call
Summary of Conditional OperatorsSummary of Conditional Operators
int x=0, y=10, w=20, z, T=1, F=0;
z = (x == 0); /*** logical operator; re sult --> 0 or 1 ***/
z = (x = 0); /*** assignment operator; result --> ***/
z = (x == 1);
z = (x = 15);
z = (x != 2);
z = (x < 10);
z = (x <= 50);
z = ((x=y) < 10); /*** performs assignment, comp ares with 10 ***/
z = (x==5 && y<15);
z = (x==5 && y>5 && w==10);
z = (x==5 || y>5 && w==10);
z = (T && T && F && x && x); /*** ==> F; ***/
z = (F || T || x || x); /*** ==> T; ***/
/*** for && and !!, order is specified, stops when result is known, ***/
/*** value of x doesn't matter ***/
Summary of the Summary of the C C OperationsOperations
• Operators same as in C++ and Java:
• Arithmetic• int i = i+1; i++; i--; i *= 2;
• +, -, *, /, %,
• Relational and Logical• <, >, <=, >=, ==, !=
• &&, ||, &, |, !
• Syntax same as in C++ and Java:• if ( ) { } else { }
• while ( ) { }
• do { } while ( );
• for(i=1; i <= 100; i++) { }
• switch ( ) {case 1: … }
• continue; break;
Arrays & PointersArrays & Pointers
One-Dimensional Arrays
#include <stdio.h>
void main(void){
int number[12]; /* 12 cells, one cell per element */int index, sum = 0;
/* Always initialize arrays before use! */for (index = 0; index < 12; index++) {
// cells are numbered from 0 to 11 not from 1 to 12 !number[index] = index;
}
for (index = 0; index < 12; index = index + 1) {sum += number[index]; /* sum array elements */
}
return;}
Array Initialization
int a[10] = { 1,2,3,4,5,6,7,8,9,10 }; int b[10] = {0}; İnitialize all elements to zeroCharacter arrays that hold strings allow shorthand initializations, like
PointerPointers!!!! s!!!! • Pointer= variable containing address of another variable
int x = 5; /* data variable */
int y = 7; /* data variable */
int *ptr = &x; /* & = address operator */
1200
ptr
5
x
x = 5(&x) 1000
y = 7
1000
(&y) 1004
(&ptr) 1200
1200
ptr
10
x
x = 10(&x) 1000
y = 7
ptr = &x = 1000
(&y) 1004
(&ptr) 1200
7
y
7
y
*ptr = 10;
Pointers - 1
float f; /* data variable */
float *f_addr; /* pointer variable */
f_addr = &f; /* & = address operator */
? ?
f f_addr
4300 4304
?
any float
any address
? 4300
f f_addr
4300 4304
Pointers - 2
*f_addr = 3.2; /* indirection operator */
float g=*f_addr; /* indirection:g is now 3.2 */
f = 1.3;
f f_addr
4300 4304
3.2 4300
f f_addr
4300 4304
1.3 4300
Arrays and PointersArrays and Pointers
An array name by itsels is an address or pointer value!An array name by itsels is an address or pointer value!
#define N 100#define N 100
int a[N], i, *p, *q, sum = 0;int a[N], i, *p, *q, sum = 0;
p = a; /* is equivalent to p = &a[0] */; p = a; /* is equivalent to p = &a[0] */;
p = a + 1; /* is equivalent to p = &a[1] */;p = a + 1; /* is equivalent to p = &a[1] */;
int a[i] /* is equivalent to *(a + i) */;int a[i] /* is equivalent to *(a + i) */;
Here *(a + i) is the dereferencing of the expressin a + i that pHere *(a + i) is the dereferencing of the expressin a + i that points i elements positions oints i elements positions past in apast in a
p = a; /* points to the base of array a */p = a; /* points to the base of array a */
q = p + 1; /* equivalent to q =&a[1] */q = p + 1; /* equivalent to q =&a[1] */
for (p = a; p <&a[N]; ++p) sum += *p;for (p = a; p <&a[N]; ++p) sum += *p;
for (i = 0; i < N; ++i) sum += *(a + i);for (i = 0; i < N; ++i) sum += *(a + i);
Pointer ArithmeticPointer Arithmetic
int main(int argc, char* argv[]){double a[2], *p, *q;
p = a; /* points to the base of array a */q = p + 1; /* equivalent to q =&a[1] */printf("=============================\n");printf(" p = %d", p); printf("\n q = %d", q );printf("\n q - p = %d", q - p); printf("\n q - p = %d\n", (int) q - (int) p);printf(" &a[0] = %d", &a[0] ); printf("\n &a[1] = %d &a[1] );
}
#include <stdio.h>
void main(void) {int j;int *ptr;
ptr=&j; /* initialize ptr before using it *//* *ptr=4 does NOT initialize ptr */
*ptr=4; /* j <- 4 assign 4 to j*/
j=*ptr; /* j <- ??? Ask students*/}
Pointer Example
Pointers: SummaryPointers: Summary
int a = 10, b = 2, *p;
p = &a; // p is assigned address of a
b = *p; // b is assigned the value pointed by p
b = *p; is equivalent to b = a;
•An array name is an address or a pointer valueAn array name is an address or a pointer valueAn array name is an address or a pointer valueAn array name is an address or a pointer value
•Arrays and pointers can be subscripted:Arrays and pointers can be subscripted:Arrays and pointers can be subscripted:Arrays and pointers can be subscripted:
int A[10], *p; int i = 0; A[0]=23; p=A;
int b = A[i]; is equivalent to int b = *(A + 0);
int c = p[i]; is equivalent to int c = *(p + i);
p = A; is equivalent to p = &A[0];
p = A + 1; is equivalent to p = &A[1];
Pointers: SummaryPointers: SummaryAll will equally sum the array ellements:All will equally sum the array ellements:All will equally sum the array ellements:All will equally sum the array ellements:
1)1)1)1)
for (p = a; p <&a[N]; ++p)
sum += *p;
2)
for (i = 0; i < N; ++i)
sum += *(a + i);
3)
p = a;
for (i = 0; i < N; ++i)
sum += p[i];
CallCall--byby--valuevalueWhenever variables are passed as arguments to a function, their Whenever variables are passed as arguments to a function, their Whenever variables are passed as arguments to a function, their Whenever variables are passed as arguments to a function, their
values are copied to the function parameters:values are copied to the function parameters:values are copied to the function parameters:values are copied to the function parameters:
Pointers are passed as arguments to a function, their addresses Pointers are passed as arguments to a function, their addresses Pointers are passed as arguments to a function, their addresses Pointers are passed as arguments to a function, their addresses are are are are
assigned to the function parameters defined as pointers:assigned to the function parameters defined as pointers:assigned to the function parameters defined as pointers:assigned to the function parameters defined as pointers:
int main(){
int a=20; int b=30;
swap (&a, &b)
printf("%d %d: ", a, b);
return 0;
}
void swap(int *x, int *y) {
int tmp;
tmp = *x; // get value pointed by x.
*x = *y; // assign value pointed by y to x
*y = tmp;
}
Why pointer arguments?!
#include <stdio.h>
void swap(int, int);
int main() {int num1 = 5, num2 = 10;swap(num1, num2);printf("num1 = %d and num2 = %d\n", num1, num2);return 0;
}
void swap(int n1, int n2) { /* passed by value */int temp;
temp = n1;n1 = n2;n2 = temp;
}
Why pointer arguments? This is why
#include <stdio.h>
void swap(int *, int *);
int main() {int num1 = 5, num2 = 10;swap(&num1, &num2);printf("num1 = %d and num2 = %d\n", num1, num2);return 0;
}
void swap(int *n1, int *n2) { /* passed and returne d by reference */
int temp;
temp = *n1;*n1 = *n2;*n2 = temp;
}
Arrays as Function Arguments
#include <stdio.h>
void init_array(int array[], int size) ;
void main(void) {int list[5];
init_array(list, 5);for (i = 0; i < 5; i++)
printf("next:%d", array[i]);}
void init_array(int array[], int size) { /* why siz e ? *//* arrays ALWAYS passed by reference */
int i;for (i = 0; i < size; i++)
array[i] = 0; }
int month[12]; /* month is a pointer to base address 430*/
month[3] = 7; /* month address + 3 * int elements=> int at address (430+3*4) is now 7 */
ptr = month + 2; /* ptr points to month[2], => ptr is now (430+2 * int elements)= 438 */
ptr[5] = 12; /* ptr address + 5 int elements
=> int at address (434+5*4) is now 12.Thus, month[7] is now 12 */
for (ctr = 0; ctr < argc; ctr = ctr + 1) {printf("Argument #%d is -> |%s|\n", ctr, argv[ctr]);
} /* ex., argv[0] == the name of the program */}
Pointer Example -argc and argv parameters
PointerPointerss to functionto function
•• Advantage ? more flexibilityAdvantage ? more flexibility
int func(); /*function returning integer*/ int *func(); /*function returning pointer to intege r*/ int (*func)(); /*pointer to function returning inte ger*/ int *(*func)(); /*pointer to func returning ptr to in t*/
Pointer to function - Example
#include <stdio.h>
void myproc (int d);void mycaller(void (* f)(int), int param);
void main(void) { myproc(10); /* call myproc with parameter 10*/mycaller(myproc, 10); /* and do the same again ! */
}
void mycaller(void (* f)(int), int param){(*f)(param); /* call function *f with param */
}
void myproc (int d){. . . /* do something with d */
}
C ProgrammingC Programming
#include <stdio.h>
struct birthday{int month;int day;int year;
};
int main() {struct birthday mybday;mybday.day=1; mybday.month=1; mybday.year=1977;printf("I was born on %d/%d/%d", birth.day,
birth.month, birth.year);return 0;
}
Container Data types: Container Data types: StructuresStructures
JANUARY, /* like #define JANUARY 0 */JANUARY, /* like #define JANUARY 0 */FEBRUARY, /* like #define FEBRUARY 1 */FEBRUARY, /* like #define FEBRUARY 1 */MARCH /* MARCH /* like like #define #define MARCHMARCH22 */*/APRILAPRIL /* /* like like #define #define APRILAPRIL 22 */*/
};};
/* JANUARY is the same as month.JANUARY */
/* alternatively, …. */
enumenum month{month{JANUARYJANUARY == 1, /* like #define JANUARY 1 */1, /* like #define JANUARY 1 */FEBRUARYFEBRUARY= 2= 2 , /* like #define FEBRUARY 2 */, /* like #define FEBRUARY 2 */MARCH MARCH /* /* …… */*/
};};
typedef int numbers;
typdef float kesirli;numbers a_number; /* same as int a_number; */
kesirli fi = 3.14typedef struct person Person;typedef struct person *PrsPtr;// struct person me;Person me; /* same as struct person me; * /PrsPtr you;typedef struct person *Personptr;
Personptr ptrtome; /* same as struct person *ptrto me;*/
typdeftypdef : : Synonym for a data typeSynonym for a data type
•• Easier to rememberEasier to remember
•• For creating cFor creating clean lean and tidy and tidy codecodess
Memory layout of programsMemory layout of programs
Header info
Code
Data - Heap
0
100
400
560
1010
1200
Dynamic memory
Local memory+ function callstack
all normal vars
all malloc()s
Data - stack
#include <stdio.h>
void main(void) {int *int * ptrptr ;;
/* allocate space to hold an int */ptr = malloc(sizeof(int));
/* Put something into the space */** ptrptr =4; =4;
free(ptrfree(ptr ););/* free up the allocated space */
char *w[10]; /* Space for 10 words: pointer array */char word[12]w[i] = calloc(strlen(word) + 1, sizeof(char));/* allocate space to hold a word (string) */ }
Dynamic Memory allocation
•• Explicit allocation and deExplicit allocation and de--allocationallocation
Advanced StructuresAdvanced Structures
#include <stdio.h>
struct birthday{int month;int day;int year;
};
int main() {struct birthday mybday; /* Create structure */mybday.day=1; mybday.month=1; mybday.year=1977;printf("I was born on %d/%d/%d", birth.day,
birth.month, birth.year);return 0;
}
StructuresStructures: Summary: Summary
Array of Structuresstructstruct person{person{
char name[41];char name[41];int age;int age;float height;float height;structstruct { /* embedded structure{ /* embedded structure (( ii çç ii ççe)e) */*/
int month;int month;int day;int day;int year;int year;
} birth;} birth;};};
struct person me;me.birth.year=1977;………
struct person class[2]; /* array of info about everyone in class */
/* pass struct to functions by value */void display_year_1(struct birthday void display_year_1(struct birthday mybdaymybday ) {) {
printf("Iprintf("I was born in %was born in % dd\\ nn", ", mybday.yearmybday.year ););}} /* /* -- inefficient: why ? */inefficient: why ? */. . . .
/* pass struct to functions by reference */void display_year_2(struct birthday *void display_year_2(struct birthday * pmybdaypmybday ) {) {
printf("Iprintf("I was born in %was born in % dd\\ nn", ", pmybdaypmybday -- >year);>year);/* warning ! /* warning ! ‘‘ -- >>’’ , not , not ‘‘ .. ’’ , after a , after a structstruct pointer*/ pointer*/
2)2) Do operations on the FileDo operations on the File
3)3) Close the fileClose the file
Files in C Files in C
•• In C, each file is simply a sequential In C, each file is simply a sequential stream of bytes. C imposes no structure stream of bytes. C imposes no structure on a file.on a file.
•• A file must first be opened properly A file must first be opened properly before it can be accessed for reading or before it can be accessed for reading or writing. When a file is opened, a writing. When a file is opened, a file file handlehandle is associated with the file.is associated with the file.
•• Successfully opening a file returns a Successfully opening a file returns a pointer to (i.e., the address of) a pointer to (i.e., the address of) a file file structurestructure,, which contains a file which contains a file descriptor and a file control block.descriptor and a file control block.
Files in C Files in C
•• The statement: The statement:
FILE *fptr1, *fptr2 ;FILE *fptr1, *fptr2 ;
declares that declares that fptr1fptr1 and and fptr2fptr2 are pointer are pointer variables of type variables of type FILEFILE. They will be . They will be assigned the address of a file descriptor, assigned the address of a file descriptor, that is, an area of memory that will be that is, an area of memory that will be associated with an input or output associated with an input or output stream. stream.
•• Whenever you are to read from or write Whenever you are to read from or write to the file, you must first open the file to the file, you must first open the file and assign the address of its file and assign the address of its file descriptor (or structure) to the file descriptor (or structure) to the file pointer variable. pointer variable.
would open the file would open the file resultsresults for output for output (writing). (writing).
•• Once the files are open, they stay open Once the files are open, they stay open until you close them or end the program until you close them or end the program (which will close all files.) (which will close all files.)
Testing for Successful OpenTesting for Successful Open
•• If the file was not able to be opened, If the file was not able to be opened, then the value returned by the then the value returned by the fopen fopen routine is NULL.routine is NULL.
•• For example, let's assume that the file For example, let's assume that the file mydatamydata does not exist. Then:does not exist. Then:
the the fscanffscanf function would read values function would read values
from the file "pointed" to by from the file "pointed" to by fptr1fptr1 and and
assign those values to assign those values to aa and and bb..
End of FileEnd of File
•• The endThe end--ofof--file indicator informs the file indicator informs the program when there are no more data (no program when there are no more data (no more bytes) to be processed.more bytes) to be processed.
•• There are a number of ways to test for the There are a number of ways to test for the endend--ofof--file condition. One is to use the file condition. One is to use the feoffeoffunction which returns a function which returns a truetrue or or falsefalsecondition:condition:
•• The last aThe last assignmentssignment requires us to read requires us to read several lines of some information from a file several lines of some information from a file and write it out to the screen and to a file. and write it out to the screen and to a file. (Sounds repetitive, doesn't it?)(Sounds repetitive, doesn't it?)
•• Simple repetitive tasks are easily performed Simple repetitive tasks are easily performed with a "with a "forfor" " or "or "whilewhile" " loop. loop. For example:For example: