UNIT 5 Functions FilesHandling
UNIT 5 Functions FilesHandling
UNIT – 5
FUNCTIONS AND FILES HANDLING
FUNCTIONS
INTRODUCTION TO FUNCTIONS
‘C’ programs are compound of a set of functions.
The functions are normally used to divide a large program into smaller
programs which are easier to handle.
Each function normally performs a specific task.
Every program must contain one function named as main where the
program always begins execution. The main program may call other
functions within it may call still other functions.
When a function is called program execution control is
transferred to the first statement of the called function.
The function is completed when it executes the last statement in the
function or it executes a return function statement after a function
returns to the calling function.
FUNCTIONS IN C
A program in C contains several functions and one function must be
main() function
The program execution starts from main() function and ends at the
ending brace of main().
It is an independent module that performs a specific task
“A function is defined as a self contained block of statements
which are used to perform a specific task”
A function definition is also known as function implementation that
includes the following.
1. Function name
2. Function type
3. List of parameters
4. Local variable declarations
5. Function statements
6. A return statement
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
1
INTRODUCTION TO PROGRAMMING
All the six elements are grouped into two parts. They are:
Function header
Function body
To see the process of sending and receiving data, let us consider two
functions main(), findmax().
#include<stdio.h>
int main(void)
{
void findmax(int , int);
int f, s;
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
2
INTRODUCTION TO PROGRAMMING
Function Prototype
Before the function is called it must be declared. The declaration
statement for the function is called function prototype. It declared the data
type of the value that will be returned directly from the function.
void findmax(int, int);
functions in the file. The general format for the function prototype is as
follows:
returntype functionName(list of arguments data types);
The use of function prototypes allows compiler to check for data type
errors. If the function prototype specified is different to the specified type
then an error message is displayed. It ensures the conversion of all
arguments passed to function when it is called to their declared argument
data types in the prototype.
in the above syntax, the function name is findmax and two values are
passed to the function. As we pass the values to the function thus this
method is called pass by value or call by value method.
secnum
A value
findmax(firstnum, secnum);
The argument names in the header line are called formal parameters
or formal arguments. Thus the arguments x and y are used to store the
firstnum and secnum values.
findmax()
The function name and all parameters in the header line for findmax()
function are choosen by the programmer. All the parameters are separated
by commas. After the function header, now let us see the function body. It
contains an opening brace and a closing brace. All the statements between
them belong to function body.
{
Variable declarations;
C statements;
}
#include<stdio.h>
int main(void)
{
void findmax(int , int);
int firstnum, secnum;
printf(“enter the first and second number”);
scanf(“%d%d”, &f, &s);
findmax(firstnum,secnum);
return 0;
}
void findmax(int x, int y)
{
int m;
if(x >= y)
m=x;
else
m=y;
printf(“%d”, m);
}
sum(a,b);
return 0;
}
void sum(int x, int y)
{
printf(“%d”, x+y);
}
return 0;
}
int sum()
{
int a, b;
printf(“enter the values of a,b”);
scanf(“%d%d”, &a, &b);
return(a+b);
}
int i;
int a[5]={33, 44, 55, 66, 77};
for (i=0; i<5; i++)
write (&a[i]);
return 0;
}
write (int *n)
{
printf (“%d\n”, n);
}
2. Passing an Entire Array to a Function
Let us now see how to pass the entire array to a function rather
individual elements.
#include<stdio.h>
int main(void)
{
int a [] = {32, 43, 54, 65, 78};
display (&a [0], 5);
return 0;
}
display (int *i, int x)
{
int j;
for (j=0; j<5;j++)
{
printf (“address=%u”, i);
printf (“element=%d\n”,*i);
i++;
}
}
RECURSION
The function called by itself is called self recursive functions or
recursive function or direct recursion and this process often referred as
recursion. A function can call second function which in turn calls the first
function is called mutual recursion or indirect recursion.
Mathematical Recursion
The problems solved using an algebraic formula shows recursion
explicitly. For example, factorial of a given number n denoted as n! where n
is a positive integer.
0! = 1
1! = 1 * 1 = 1 * 0!
2! = 2 * 1 = 2 * 1!
3! = 3 * 2 * 1 = 3 * 2!
4! = 4 * 3 * 2 * 1 = 4 * 3! and so on …..
scanf(“%d”, &n);
fact=factorial(n);
printf(“%d”, fact);
return 0;
}
int factorial(int x)
{
int f;
if(x==1)
return(1);
else
f=x*factorial(x-1);
return(f);
}
else
gcd(y,r);
return;
}
SCOPE
Scope refers to the region where the object is defined. It simply says
about visibility of the object. Scope refers to where the variable is
defined.
To explain about scope let us consider the following example
There are different types of scopes you can observe
Global Scope
It is also known as file scope.
Any object or variable defined in the global area of the program is
visible to all the functions from its declaration to till end of the
program.
The variables declared in this area are called global variables.
Local Scope
It is known as block scope
Any object or variable defined inside the function is visible to only that
function where it has is definition.
The variables declared in this function are called local variables.
In the above diagram, the function main has variables declared and
nested block also has varaible declared. Their scope is local that is
visible only to that function.
STORAGE CLASSES
“Storage Class specifies where the variable value is to be stored
that is either in memory or register”
Storage Classes
The storage class specifiers are auto, register, static, extern
Scope
It defines visibility of an object or variable.
We have two types of scope: block scope and file scope
Block Scope
If the object is defined within the block it is said to have block scope.
Since it is visible only inside the block where is defined.
These variables are said to be local variables.
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
15
INTRODUCTION TO PROGRAMMING
File Scope
Any object with file scope has visibility throughout the program
Such variables are said to global variables
If any variable is redefined with the same name inside the function
then local variable gets scope and hides the file scope variable.
Extent
The extent of object defines the duration for which the computer
allocates memory for it.
There are three types of extents: automatic, static, dynamic
Automatic Extent
An object with automatic extent is created each time it is declared and
destroyed each time it is exited.
Static Extent
A variable with static extent is created when program is loaded for
execution and it is destroyed when the execution stops.
Linkage
It refers to linking all the modules into single module.
It is of two types: internal, external
Internal Linkage
It is visible to only the module where it is declare and other modules
cannot refer this object
External Linkage
It is declared in one module but visible to all modules but it is
declared with special keyword extern
Auto Variables
A variable with auto specification has:
Scope: block
Extent: automatic
Linkage: internal
The variable is declared in a block. Each time the declaration is found
it is re-created.
It uses the keyword auto before the type of the variable
It is visible only to the block where is defined.
It can be initialized where it is defined or left uninitialized.
If initialized, it takes the initialized value other if not initialized it value
is undefined or unpredictable.
The keyword need not be explicitly coded
For example
#include<stdio.h>
int main()
{
for(int i=0;i<=3;i++)
{
int x=1;
x++;
printf(“value of x is %d”, x);
}
return 0;
}
Register Variables
It is similar to auto storage class with one difference.
The declaration should have register keyword as shown below
register int x;
Register access is faster than memory access
The efficiency is good when compared with memory access.
The problem is register variable address is not available to the user
It will not allow implicit conversions in mixed mode arithmetic.
External Variables
They are used with separate compilations.
A variable declared with extern storage class has the following
properties
Scope: file
Extent: static
Linkage: External
An extern variable must be declared in all files that reference it, but
defined in one of them.
They are generally declared at global level.
For example,
FILES HANDLING
FILE
A file is an external collection of related data treated as a unit.
The purpose of a file is to keep a record of data.
We need to store data permanently since data present in the main
memory is lost when the compute is shut down.
Files are stored in secondary storage device like disk and tapes.
When the computer reads the data it is moved from external device to
memory and memory to external device.
The movement of data uses a special work area called buffer.
A buffer is a temporary storage area that holds data for a short period
of time
A buffer synchronize physical devices with program needs
The data is read from the file until it reaches end of file marker.
The operating system should have a set of rules to name a file.
A program reads or writes files need to know different information
about the file like filename, position, etc.
It has predefined file structure present in stdio.h header file and its
type is FILE.
“A file is a place on the disk where a group of related data is
stored”.
FILE OPERATIONS
1. Naming a file
2. Opening a file
3. Reading data from a file
4. Writing data to the file
5. Closing a file
There are two distinct ways to perform the file operations in C. The
first one is known as the low level I/O and uses UNIX system calls. The
second method is referred to as the high level I/O operations and uses
functions in C’s standard I/O library.
The first statement declares the variable fp as a pointer to the data type
FILE. The second statement opens the file, named file name and assigns an
identifier to the FILE type pointer fp. This pointer which contains all the
information about the file is subsequently used as a communication link
between the system and the program. The second statement also specifies
the purpose of opening this file. The mode does this job. Mode can be one of
the following:
r opening the file for reading only.
w opening the file for writing only
a opening the file for appending (or adding) data to it.
Both the filename and mode are specified as string. They should be
enclosed in double quotation marks. When trying to open the file of the
following things may happen:
1. When the mode is writing a file with the specified name is created if
the file does not exist. The contents are deleted if the file already exist.
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
22
INTRODUCTION TO PROGRAMMING
2. When the purpose is appending the file is opened with the current
contents safe. A file with the specified name is created if the file does
not exist.
3. If the purpose is reading and if it exists then the file is opened with
the current contents safe. Otherwise an error occurs.
The file pointer moves by one character position for every operation of
getc or putc. The getc will return an end-of-file marker EOF, when end of the
file has been reached. Therefore the reading should be terminated when
EOF is encountered.
#include<stdio.h>
#include<conio.h>
int main(void)
{
FILE *f1;
char c;
clrscr ( );
printf (“data into \n\n”);
f1=fopen (“input”,”w”);
while ((c=getchar ()! =eof)
putc(c, f1);
fclose (f1);
printf (“\n data output\n\n”);
f1=fopen (“input”,”r”);
while ((c=getc (f1))! =eof)
printf (“%c”, c);
fclose (f1);
}
}
fclose (f1);
fclose (f2);
fclose (f3);
f2=fopen (“odd”,”r”);
f3=fopen (“even”,”r”);
printf (“\n\n contents oof odd file:\n\n”);
while ((num=getw (f2))! =eof)
printf (“%4d”, num);
printf (“\n\ncontents of even file:\n\n”);
while ((num=getw (f3))! =eof)
printf (“%4d”, num);
fclose (f2);
fclose (f3);
}
The functions fprintf and fscanf perform I/O operations that are
identical to the familiar printf and scanf functions .The first argument of
these function is a filepointer which specifies file to be used.
The General Form
fprintf (fp,”control string”, list);
The list may include variables, constants and strings.
fprintf(fp, “%d%f%c”, a, b, c);
The General Form
fscanf (fp,”control string”, list);
fscanf (f1,”%d%f”, &age, &sal);
This statement gives the end of data when encountered end of file
condition.
The ferror Function: It is also takes a file pointer its argument and returns
a non-zero integer if an error has been detected upto that point during
processing it returns zero otherwise.
Ex:
if(ferror (fp)!=0)
printf(“file could not be open”);
Where ‘n’ gives the relative offset (in bytes) of the current position.
This means that ‘n’ bytes have already read.
rewind Function: It takes a file pointer and resets the position to the start
of the (in bytes). The statement is:
rewind (fp);
n = ftell(fp);
It will assign ‘o’ to n’ because the file position has been set to the start
of the file by rewinded. i.e., the first byte in the file is numbered as ‘o’
second as ‘1’ and a so on.
The Offset may be ‘+’ve meaning moved forwards, or ‘-‘ ve meaning moved
backwards.
Ex:
Fseek(Fp,Ol,0) goto Beginning
Fseek(fp,m,0) move (n+1)th byte in the file
Fseek (fp,m,1) goto forward by ‘m’ bytes
Fseek (fp,-m,1) goto backward by ‘m’ bytes from the current position
Fseek (fp ,-m,2) goto backward by ‘m’ bytes from the end.
1. Write a program to copy the contents of one file into another file
#include<stdio.h>
#include<conio.h>
int main(void)
{
FILE *fs,*ft;
char ch;
clrscr();
fs=fopen(“[Link]”, “r”);
if(fs==NULL)
{
printf(“[Link] file cannot be opened”);
exit(0);
}
ft=fopen(“[Link]”, “w”);
if(ft==NULL)
{
printf(“[Link] file cannot be opened”);
fclose(fs);
exit(0);
}
while(1)
{
ch=getc(fs);
if(ch==EOF)
break;
else
putc(ch,ft);
}
fclose(fs);
fclose(ft);
printf(“the file copy operation performed successfully”);
return 0;
}
2. Write a program to read the list of integers from two different files
and merge and store them in a single file/third file
#include<stdio.h>
#include<conio.h>
int main(void)
{
FILE *fs,*ft;
int c;
clrscr();
fs=fopen(“[Link]”, “r”);
if(fs==NULL)
{
printf(“[Link] file cannot be opened”);
exit(0);
}
ft=fopen(“[Link]”, “w”);
if(ft==NULL)
{
printf(“[Link] file cannot be opened”);
fclose(fs);
exit(0);
}
for(; fscanf(fs, “%d”, &c)!=EOF ;)
fprintf(ft, “%d”, (c));
fclose(fs);
fclose(ft);
fs=fopen(“[Link]”, “r”);
if(fs==NULL)
{
printf(“[Link] file cannot be opened”);
exit(0);
}
ft=fopen(“[Link]”, “r+”);
if(ft==NULL)
{
printf(“[Link] file cannot be opened”);
fclose(fs);
exit(0);
}
fseek(ft,0L,2);
for(; fscanf(fs, “%d”, &c)!=EOF ;)
fprintf(ft, “%d”, (c));
fclose(fs);
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
30
INTRODUCTION TO PROGRAMMING
fclose(ft);
printf(“Files merged successfully now you can open [Link] file to
check the contents”);
return 0;
}