0% found this document useful (0 votes)
98 views80 pages

C Programming: Conducted by Sarwar Morshed Senior Lecturer, CSE

This document summarizes a lecture on structured programming in C. It covers blocks, conditional statements like if/else and switch/case, loops like while, do/while and for, and flow control statements like break, continue, and goto. It also discusses standard input/output functions like printf, scanf, putchar and getchar. Finally, it covers arrays, strings, character arrays and formatted input/output.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views80 pages

C Programming: Conducted by Sarwar Morshed Senior Lecturer, CSE

This document summarizes a lecture on structured programming in C. It covers blocks, conditional statements like if/else and switch/case, loops like while, do/while and for, and flow control statements like break, continue, and goto. It also discusses standard input/output functions like printf, scanf, putchar and getchar. Finally, it covers arrays, strings, character arrays and formatted input/output.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

C Programming

Lecture 4

Conducted by
Sarwar Morshed
Senior Lecturer, CSE
2013-04-12

Structured Programming in C

Blocks
Blocks combine multiple statements into a single unit.
Can be used when a single statement is expected.
Creates a local scope (variables declared inside are local to the block).
Blocks can be nested.

int x=0;
{
int y=0; / both x and y visible /
}
/ only x visible /

2013-04-12

Structured Programming in C

Review
Control flow
I/O
Standard I/O
String I/O
File I/O

2013-04-12

Structured Programming in C

Conditional blocks
if ... else..else if is used for conditional branching of
execution
if ( cond )
{
/ code executed if cond is true /
}
else
{
/ code executed if cond is false /
}
2013-04-12

Structured Programming in C

Conditional blocks
if ... else..else if is used for conditional branching of
execution
if ( cond ) {
/ code executed if cond is true /
}
else
{
/ code executed if cond is false /
}
2013-04-12

Structured Programming in C

Conditional blocks
switch..case is used to test multiple conditions (more efficient than if
else ladders).

switch...case is used for constant and straight forward


conditions
Switch...case considers only integer or character variable as
input
Switch...cases for value of variable
Compares variable to each case in order
When match found, starts executing inner code until break;
reached

2013-04-12

Structured Programming in C

Example
switch ( opt ) {
case A :
/ execute if opt == A /
break ;
case B :
case C :
/ execute if opt == B || opt == C /
default :
}
2013-04-12

Structured Programming in C

Difference between if...else &


switch...case statement
If...else allows complex expression in
conditions
switch...case is used for constant and straight
forward conditions
Switch...case considers only integer or
character variable as input
Switch...cases for value of variable

2013-04-12

Structured Programming in C

Iterative blocks
while loop tests condition before execution of
the block.
do..while loop tests condition after execution
of the block.
for loop provides initialization, testing and
iteration together.

2013-04-12

Structured Programming in C

Review
Control flow
I/O
Standard I/O
String I/O
File I/O

2013-04-12

Structured Programming in C

10

break keyword
Sometimes want to terminate a loop early
break; exits innermost loop or switch statement to exit early
consider the modification of the do...while example
char c;
Do{
/* loop body */
Puts(keep going? (y/n) );
C= getchar();
If(c != y)
break;
/*other processing*/
} while (/*other conditions*/)
2013-04-12

Structured Programming in C

11

continue keyword
Use to skip an iteration
continue; skips rest of innermost looop body, jumping to loop
condition
Example:
# define min(a,b) ((a)<(b)?(a):b))
int gcd(int a, int b){
int i, ret=1, minval=min(a,b);
for(i=2;i<=minval;i++){
if(a%i) /* i not divisor of a*/
continue;
if(b%i==0) /*i is divisor of both a & b*/
ret = i;
}
}
2013-04-12

Structured Programming in C

12

goto

goto allows you to jump unconditionally to arbitrary part of your code (within the

same function).
the location is identified using a label.
a label is a named location in the code. It has the same form as a variable followed
by a :
start :
{
if ( cond )
goto outside ;
/ some code /
goto start ;
}
outside :
/ outside block /

2013-04-12

Structured Programming in C

13

Spaghetti code
Dijkstra. Go To Statement Considered Harmful.
Communications of the ACM 11(3),1968
Excess use of goto creates sphagetti code.
Using goto makes code harder to read and debug.
Any code that uses goto can be written without using one.

2013-04-12

Structured Programming in C

14

Language like C++ and Java provide exception mechanism to


recover from errors. In C, goto provides a convenient way to
exit from nested blocks.
for()
{
for(...)
{
if(err_cond)
goto error;
/*skiptwo blocks*/
}
}

2013-04-12

Structured Programming in C

15

Review
Control flow
I/O
Standard I/O
String I/O
File I/O

2013-04-12

Structured Programming in C

16

Standard input and output


int putchar(int)
putchar(c) puts the character c on the standard
output.
it returns the character printed or EOF on error.
int getchar()
returns the next character from standard input.
it returns EOF on error.

2013-04-12

Structured Programming in C

17

Example of putchar()
/* putchar example: printing the alphabet */
#include <stdio.h>
int main ()
{
char c;
for (c = 'A' ; c <= 'Z' ; c++)
putchar (c);
return 0;
}
This program writes ABCDEFGHIJKLMNOPQRSTUVWXYZ to the standard
output.
2013-04-12
Structured Programming in C

18

Exmple of getchar()
/* getchar example : typewriter */
#include <stdio.h>
int main ()
{
char c;
puts ("Enter text. Include a dot ('.') in a sentence to exit:");
do {
c=getchar();
putchar (c);
} while (c != '.');
return 0;
}
A simple typewriter. Every sentence is echoed once ENTER has been pressed
until a dot (.) is included in Structured
the text.
2013-04-12
Programming in C
19

Standard output:formatted
int printf (char format[],arg1,arg2 ,...)
printf() can be used for formatted output.
It takes in a variable number of arguments.
It returns the number of characters printed.
The format can contain literal strings as well as
format specifiers (starts with %).
Examples:
printf ( "hello world\n" );
printf ( "%d\n" ,10); / format: %d (integer),argument:10 /
printf ( "Prices:%d and %d\n" ,10 ,20);

2013-04-12

Structured Programming in C

20

The format specification has the following components %[flags][width ][.


precision][length]<type>

2013-04-12

Type

Meaning

Example

d,i

integer

printf ("%d",10); /prints 10/

x,X

integer(hex)

intf ("%x",10); /print 0xa/

unsigned integer

printf ("%u",10); /prints 10/

character

printf ("%c",A); /prints A/

string

printf ("%s","hello"); /prints hello/

float

printf ("%f",2.3); / prints 2.3/

double

printf ("%d",2.3); / prints 2.3/

e,E

foat(exp)

1e3,1.2E3,1E3

literal %

printf ("%d %%",10); /prints 10%/


Structured Programming in C

21

Arrays
Array: is a list of similar variables.
Declaration: data_type variablename[size];
int a[10];
double a[10];
char a[10];
Callsification of Array:
One dimensional array: int a[10];
Two dimensiona array: int a[10][5];
Three dimensional array is essentially an array of two-dimensional
arrays: int a[4][5][3];
Array elements start from 0 position.
Initialization of array:
int a[3] = {4, 2, 8};
c[0] c[1] c[2]
A
B
C
char c[3] = {A, B, C};
c Programming
2013-04-12
Structured
in C

22

Example
Get values into an array and print them
int main()
{
int a[5], i;
printf(Enter 5 integer values);
/*inserting array elements from key board*/
for(i=0; i<5;i++){
scanf(%d, &a[i]);
}
/*print the inserted values from array */
for(i=0; i<5;i++){
printf(%d , a[i]);
}
return 0;
}
2013-04-12

Structured Programming in C

23

Two dimensional array


int main()
{
int a[3][3], b[3][3], c[3][3], i, j;
printf(Enter 5 integer values);
/*inserting 1st array elements from key board*/
for(i=0; i<3;i++){
for(j=0; j<3;j++){
scanf(%d, &a[i][j]);
}
}
/*inserting 1st array elements from key board*/
for(i=0; i<3;i++){
for(j=0; j<3;j++){
scanf(%d, &b[i][j]);
}
2013-04-12 }
Structured Programming in C

24

/*add two matrix and display the result */


for(i=0; i<3;i++){
for(j=0; j<3;j++){
c[i][j] = a[i][j] + b[i][j];
printff(%d, c[i][j]);
}
}
return 0;
}

2013-04-12

Structured Programming in C

25

character arrays & String


What is string?
A string is a null-terminated (last character == \0) character array. In
C, a null is zero.
strings are represented as an array of characters
C does not restrict the length of the string. The end of the string is
specified using \0.
For instance, "hello" is represented using the array {h,e,l,l,o,\0}.
Declaration examples:
char str []="hello";/compiler takes care of size/
char str[10]="hello";/make sure the array is large enough/
char str []={ h,e,l,l,o,\0};
Note: use \" if you want the string to contain ".
2013-04-12

Structured Programming in C

26

String Example
int main()
{
char str[80];
int i;
printf(Enter a string (less than 80));
gets(str);
for(i=0;str[i]!=\0;i++)
printf(%c,str[i]);
return 0;
}

2013-04-12

Structured Programming in C

27

character arrays
Comparing strings: the header file <string.h> provides the function
int strcmp(char s[],char t []) that compares two strings in
dictionary order (lower case letters come after capital case).
the function returns a value <0 if s comes before t
the function return a value 0 if s is the same as t
the function return a value >0 if s comes after t
strcmp is case sensitive
Examples
strcmp("A","a")/<0/
strcmp("IRONMAN","BATMAN")/>0/
strcmp("aA","aA")/==0/
strcmp("aA","a")/>0/
2013-04-12

Structured Programming in C

28

example
#include<string.h>
#include<stdio.h>
#define MAX_STRING_LENGTH 100
int main() {
/* this program reads word by word and increments a counter each time until
the string "exit" is entered */
char S[MAX_STRING_LENGTH];
int count; count = 0;
do {
printf("string:\t");
scanf("%s",S);
if (strcmp(S,"exit") != 0)
++count;
} while (strcmp(S,"exit") != 0);
printf("word count:\t%d\n", count);
}
2013-04-12

Structured Programming in C

29

Formatted input
int scanf(char format ,...) is the input analog of printf.
scanf reads characters from standard input, interpreting them
according to format specification
Similar to printf , scanf also takes variable number ofarguments.
The format specification is the same as that for printf
When multiple items are to be read, each item is assumed to be
separated by white space.
It returns the number of items read or EOF.
Important: scanf ignores white spaces.
Important: Arguments have to be address of variables (pointers).

2013-04-12

Structured Programming in C

30

clarify the difference between


"\0" and '\0' and 0
\0 indicates an empty string
\0 indicates to a single character 0 (zero)
0 indicates to a single character 0 (zero) which
is identical to second one

2013-04-12

Structured Programming in C

31

String Functions
strlen(): to find length of the strings.
strlen(string); this will return 5.
strcmp(string1, string2): to compare the string. It returns 0
both strings are similar, returns less than 0, if string 1 is less
than string2, and returns greater than 0, if string1 is greater
than string2.
strcat(): to concatenate two strings. For example:
strcat(str1, str2);
will concatenate str2 to end of str1 if there is enough room.
strcpy(): to copy one string to another.
strcpy(str1, str2); this will copy str2 to str1.

2013-04-12

Structured Programming in C

32

Example with string functions


int main()
{
char str1[80], str2[80];
int stringlength;
printf(Enetr the 1st string: );
gets(str1);
printf(Enetr the 2nd string: );
gets(str2);
/*to find length of the strings*/
printf(%s is %d character long\n, str1, strlen(str1));
printf(%s is %d character long\n, str2, strlen(str2));
/*compare the string*/
stringlength = strcmp(str1, str2);
if(!stringlength) printf(strings are equal\n);
else if(stringlength<0) printf(%s is less than %s\n, str1, str2);
2013-04-12

Structured Programming in C

33

Example with string functions


else printf(%s is greater than %s\n, str1, str2);
/*concatenate str2 to end of str1 if there is enough room*/
If(strlen(str1)+strlen(str2) <80){
strcat(str1, str2);
printf(%s\n,str1);
}
/*copy str2 to str1*/
strcpy(str1, str2);
printf(%s %s\n, str1, str2);
return 0;
}

2013-04-12

Structured Programming in C

34

Storage class in c
The following are four types of storage class
available in C language.

2013-04-12

auto
register
extern
static

Structured Programming in C

35

extern keyword
Need to inform other source files about
functions/global variables
For functions: put function prototypes in a header
file
For variables: re-declare the global variable using the
extern keyword in header file
Extern informs compiler that the variable is defined
somewhere else
Enables access/modifying of global variable from
other sources.
2013-04-12

Structured Programming in C

36

Static variables
static variables are those variables whose life time remains
equal to the life time of the program.
static keyword has two meanings, depending on where the
static variable is declared
Outside a function, static variables/functions only visible
within that file, not globally (cannot be externed)
Inside a function, static variables:
are still local to that function
are initialized only during program initialization
do not get reinitialized with each function call

static int somePersistentVar = 0;


2013-04-12

Structured Programming in C

37

Pointer
A pointer is a variable that holds the memory address of
another object.
Example: If a variable called p contains the address of another
variable called q, p is said to point to q. Therefore if the
address of q is 100 then adress of p would be 100.
Declaration: data_type *variable_name;
int *p;
# In C there are two pointer operators:
&: The & operator returns the address of the variable it
preceds.
*: The * operator returns the value stored at the address it
preceds.
2013-04-12

Structured Programming in C

38

Pointer
int main()
{
int *p,q;
q =199; /*assign q 199*/
p = &q; /*assign p the address of q*/
printf(%d, *p); /*displays qs value using pointer*/
return 0;
}
Pointer Restrictions:
1. Only four arithmetic operators can be applied with pointer: +,
++, -, --.
2. Add and subtract operation with pointer for integer values
only
2013-04-12

Structured Programming in C

39

Pointer
Example: if p contains the address 200, after following statement
p++;
Adress of p will be 202.
# Difference between these statements: *p++ ; and (*p)++;
Answer: 1st statement first increament p and then obtains the
value at the new location. In the second statement, the value
pointed at the location will be increamented.
Assume p is integer. If p address of p is 1000 and value assigned
this address is 7, then for the first statement address of p will be
1002 and value will be 7. In second case, address of p will be
same 100, but value will be 8.
2013-04-12

Structured Programming in C

40

Use pointer with array


int main()
{
int a[10] = {10, 20, 30, 40, 50, 60};
int *p;
p=a; /*assign p the address of a*/
/*prints the 1st, 2nd and 3rd elements of array*/
printf(%d %d %d, *p, *(p+1), *(p+2));
/*same elements will be printed*/
printf(%d %d %d, a[0], a[1], a[2]);
return 0;
}

2013-04-12

Structured Programming in C

41

Use pointer with array


int main()
{
char str[] = this is a pointer example;
char *p;
int i;
p=str; /*assign p the address of a*/
/*loop until null is found*/
for(i=0; p[i]; i++)
printf(%c, p[i]);
return 0;
}

2013-04-12

Structured Programming in C

42

Use pointer with array


int main()
{
char str[] = this is a pointer example;
char *p;
int i;
p=str; /*assign p the address of a*/
/*loop until null is found*/
for(i=0; p[i]; i++)
printf(%c, p[i]);
return 0;
}

2013-04-12

Structured Programming in C

43

Define functions and its purposes.


A function is a module or block of program code which deals
with a particular task. Making functions is a way of isolating
one block of code from other independent blocks of code.
Functions serve two purposes. They allow a programmer to
say: `this piece of code does a specific job which stands by
itself and should not be mixed up with anything else', and
they make a block of code reusable since a function can be
reused in many different contexts without repeating parts of
the program text.

2013-04-12

Structured Programming in C

44

Function prototyping
type function-name(type parameter-name1, type parametername2,...., type parameter-nameN);
Three atributes to be considered during function declaration:
Return type of the function
Number of parameter
Types of the parameters

2013-04-12

Structured Programming in C

45

Compute gcd using function


Compute the gcd using Eucladian algorithm:
int main(){
int a, b;
scanf(%d %d, &a, &b);
gcd(a,b);
}
int gcd(int a, int b) {
while(b) {
int temp=b;
b=a%b;
a=temp;
}
return a;
}
2013-04-12

Structured Programming in C

46

Variable scope
scope- the region in which a variable is valid
Many cases, it corresponds to block with variables
declaration
Variables declared outside of a function have global
scope
Variables declaraed within a function have local
scope
Function definition have also scope

2013-04-12

Structured Programming in C

47

An example
What is the scope of each variable in this example? int nmax = 20;
/ The main() function /
int main ( int argc , char argv) / entry point /
{
int a=0, b=1, c, n;
printf ( "%3d: %d\n" ,1 ,a );
printf ( "%3d: %d\n" ,2 ,b );
for (n =3; n<= nmax; n++) {
c=a+b; a=b; b=c;
printf ( "%3d: %d\n" ,n, c );
}
return 0; / success /
}
2013-04-12

Structured Programming in C

48

Returning multiple values

Extended Euclidean algorithm returns gcd, and two other


state variables, x and y
Functions only return (up to) one value
Solution: use global variables
Declare variables for other outputs outside the function
variables declared outside of a function block are globals
persist throughout life of program
can be accessed/modified in any function

2013-04-12

Structured Programming in C

49

Call by Value & Call by reference


A sub routine can be passed arguements in two ways:
Call by Value: This method copies the value of an arguement into formal
parameter of subroutine. In this method, changes made to a parameter of
the subroutine have no effect on the argument used to call it.
Call by reference: In this method, address of the arguement is copied into
parameter. In this case, changes made to a parameter of the subroutine
will affect the arguement used to call it.
Int main()
{
int num1, num2;
num1 = 100;
num2 = 200;
printf(num1: %d num2: %d\n, num1, num2);
swap(&num1, &num2);
printf(num1: %d num2: %d\n, num1, num2);
return 0;

}
2013-04-12

Structured Programming in C

50

void swap(int *i, int *j)


{
int temp;
temp= *i;
*i = *j;
*j = temp;
}

2013-04-12

Structured Programming in C

51

Recursive function
Recursion: Recursion is the process by which something is
defined in terms of itself. In computing, recursion means
when function can call itself.

Example:
Int main()
{
int fact, value;
printf(Enter an integer value);
scanf(%d, &value);
fact=factorial(value);
printf(factorial of this value is: %d, fact);
}
2013-04-12

Structured Programming in C

52

Recusive function
int factorial(int value)
{
int result;
result=value*factorial(value-1);
return result;
}
Another example:
int main()
{
recurse(0);
return 0;
}
2013-04-12

Structured Programming in C

53

void recurse(int i)
{
if(i<10){
recurse(i+1); /*recursive call*/
printf(%d,i);
}
}
Result: 9 8 7 6 5 4 3 2 1 0

2013-04-12

Structured Programming in C

54

Mutual Recursion
Mutual recursion occurs when one function calls another,
which in turn calls the first.
Example:
int main()
{
f1(30);
return 0;
}
void f1(int a)
{
if(a) f2(a-1);
printf(%d, a);
}
2013-04-12

Structured Programming in C

55

More functions
tolower() and touppe()
int main(){
char str[80]; int i;
printf(Enter a string: );
gets(str);
for(i=0;str[i];i++)
str[i]=toupper(str[i]);
printf(%s\n, str); /*uppercase string*/
for(i=0;str[i];i++)
str[i]=tolower(str[i]);
printf(%s\n, str); /*lower case string*/
return 0;
2013-04-12
Structured Programming in C
}

56

File
The C I/O system supplies a consistent interface to the
programmer, independent of the actual I/O device being
used. To accomplish this, C provides a level of abstraction
between the programmer and hardware. This abstraction is
called a stream. The actual device providing I/O is called a file.
Files are used to store datas in the secondary memory(eg:hard disk, floppy, flash disk etc).
There are various file operations that can be done in C like
Creating a file, deleting a file, renaming a file, opening a file to
read/write/append datas etc.

2013-04-12

Structured Programming in C

57

Syntax for declaring a file pointer in C


Before doing any operations on a file, we have to declare a file pointer
first.
FILE *file_pointer;
Example :- FILE *fp;
Where,
FILE = keyword
*fp = user defined file pointer variable.
Once the file pointer is declared next step is to create/open a file.
Creating / opening a file in C
fopen() is used to open a specified file from disk, if it exist. If it doesnt
exist a new file will be created and opened for further file operations.

2013-04-12

Structured Programming in C

58

Syntax for fopen()


fp=fopen(file_name with extension,mode);
Where,
fp= user defined file pointer variable.
filename= name of the file with file type as extension.
mode= mode in which the file is to be opened.
Example :To Read r, To Write - w, To Append a
To Read & Write w+, To Read and write r+
To Read Write with append a+
In w+ mode the contents in existing file is destroyed and then
can perform read/write operations.
In r+ mode just read and write operations can be performed.
2013-04-12

Structured Programming in C

59

Syntax for fopen()


In a+ mode we can perform read and write operations with
appending contents. So no existing datas in a file are
destroyed.
Example :fp=fopen(data.txt,a+);
After a file is opened, we have to perform read or wrote
operations into it.

2013-04-12

Structured Programming in C

60

Writing to a file in C
fprintf()
fprintf() is used to write datas to a file from
memory.
Syntax for fprintf()
fprintf(file pointer,control string,variables);
Example:fprintf(fp,%s,name);

2013-04-12

Structured Programming in C

61

Reading from a file in C


fscanf() is used to read data from a file to the
memory.
Syntax for fscanf()
fscanf(file pointer,control string,variables);
Example
fscanf(fp,%s,name);

2013-04-12

Structured Programming in C

62

Closing a file in C

fclose() is used to close a file in C.


Syntax for fclose()
fclose(fp);
Where, fp= user-defined file pointer.

2013-04-12

Structured Programming in C

63

Some File Functions


rewind()
The C library function void rewind(FILE *stream) sets the file
position to the beginning of the file of the given stream.
Following is the declaration for rewind() function.
void rewind(FILE *stream);
Parameters
stream -- This is the pointer to a FILE object that identifies the
stream.
Return Value
This function does not return any value.

2013-04-12

Structured Programming in C

64

Some File Functions


fgetc(FILE *fp)
Declaration:
int fgetc(FILE *fp);
fgetc() reads the next byte from the file described by the fp as an
unsigned character and returns as an integer. If error occurs,
fgetc() returns EOF (end of file).
fputc(FILE *fp)
Declaration:
int fputc(int ch, FILE *fp);
fputc() function writes the byte contained in the low order byte
of ch to the file associated with fp as an unsigned char. fputc()
returns the character written
if successful or EOF if error occurs.
2013-04-12
Structured Programming in C
65

Some File Functions


feof(FILE *fp)
Declaration:
int feof(FILE *fp);
feof() returns nonzero if the file associated with fp has reached
the end of the file. Otherwise, it returns zero. This function works
for both binary and text file.
ferror(FILE *fp)
Declaration:
int ferror(FILE *fp);
ferror() function nonzero if the file associated with fp has
experienced an error.
2013-04-12

Structured Programming in C

66

Reading and Writing to a file in C


#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c[60];
int no,n;
fp=fopen("data2.txt","a+");
printf("Enter the Employee Name and No : ");
scanf("%s %d",c,&no);
fprintf(fp,"\n\n%s\n%d",c,no);
rewind(fp);
printf("Enter the Employee No : ");
scanf("%d",&n);
2013-04-12

Structured Programming in C

67

Reading and Writing to a file in C


while(!feof (fp))
{
fscanf(fp,"%s %d",c,&no);
if(no==n)
{
printf("\n%s \n %d",c,no);
}
}
fclose(fp);
getch();
}
Output:
Enter the Employee name and No: Mr. X 1203
Enter the Employee No: 1203
Mr. X
1203
2013-04-12
Structured Programming in C

68

Writing Character by Character to a file


#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
fp=fopen("data.txt","w");
printf("Enter datas to save inside the file 'data.txt' and press '~' to
stop writing \n");
while(c!='~')
{
c=getche();
fputc(c,fp);
}
fclose(fp);
}

2013-04-12

Structured Programming in C

69

Reading Character by Character from a file


#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
fp=fopen("data.txt","r");
rewind(fp);
while(!feof (fp))
{
printf("%c",getc(fp));
}
fclose(fp);
getch();
}
2013-04-12

Structured Programming in C

70

Random Access To File


Examples shown in the above have either written or read a
file sequentially from its beginning to its end. But if it is
requried a file to access randomly, you can use the following
function: fseek()
Declaration:
int fseek(FILE *fp, long offset, int origin);
where fp is associated with the file being accessed. The value of
offset determines the number of bytes from origin to make
the new current position. Origin must be one of these macros:
SEEK_SET : seek from the start of file
SEEK_CUR : seek from the current location
SEEK_END: seek from the end of file
* A macro is a fragment of code which has been given a name. Whenever the name is
used, it is replaced by the contents of the macro. There are two kinds of macros.
They differ mostly in what they look like when they are used. Object-like macros
2013-04-12
Structured
Programming inmacros
C
resemble data objects when used,
function-like
resemble function calls. 71

Fseek example
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is tutorialspoint.com", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Langauge", fp);
fclose(fp);
return(0);
}
Let us compile and run the above program, this will create a file file.txt
with the following content. Initially program creates file and writes This is
tutorialspoint.com but later we reset the write pointer at 7th position
from the beginning and use puts() statement which over-write the file
with the following content:
2013-04-12 This is C ProgrammingStructured
Programming in C
72
Langauge

Structure
A structure is an aggregate data type that is composed of two or
more related variables called members. Each member of
structure can have its own type, which may differ from the
types of other members.
Defining structure: To define a structure, you must use the
struct statement. The struct statement defines a new data type,
with more than one member for your program. The format of
the struct statement is this:
struct [structure tag]
{
member definition;
member definition;
...
member definition;
} [one or more structure variables];
2013-04-12

Structured Programming in C

73

Structure
The structure tag is optional and each member definition is a
normal variable definition, such as int i; or float f; or any other
valid variable definition. At the end of the structure's definition,
before the final semicolon, you can specify one or more
structure variables but it is optional. Here is the way you would
declare the Book structure:
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
2013-04-12

Structured Programming in C

74

Accessing Structure Members


To access any member of a structure, we use the member
access operator (.). The member access operator is coded as a
period between the structure variable name and the structure
member that we wish to access. You would use struct
keyword to define variables of structure type. Following is the
example to explain usage of structure:

2013-04-12

Structured Programming in C

75

Accessing Structure (Example 1)


#include <stdio.h>
struct s_type{
int i;
char ch;
double d;
char str[80];
} s;
int main()
{
printf(Enter an integer: );
scanf(%d:, &s.i);
printf(Enter an character: );
2013-04-12

Structured Programming in C

76

Accessing Structure (Example 1)


scanf(%c:, &s.ch);
printf(Enter an floating point value: );
scanf(%lf:, &s.d);
printf(Enter an string: );
scanf(%s:, &s.str);
printf(%d %c %f %s, s.i, s.ch, s.d, s.str);
return 0;
}
2013-04-12

Structured Programming in C

77

Accessing Structure (Example 2)


#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
2013-04-12

Structured Programming in C

78

Accessing Structure (Example 2)


strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
2013-04-12

Structured Programming in C

79

Accessing Structure (Example 2)


/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);
return 0;
}

2013-04-12

Structured Programming in C

80

You might also like