0% found this document useful (0 votes)
41 views31 pages

UNIT 5 Functions FilesHandling

This document provides an introduction to functions in C programming, detailing their structure, declaration, definition, and calling conventions. It explains the importance of the main function, function prototypes, and various types of functions based on arguments and return values. Additionally, it covers passing arrays to functions, modifying parameters using pointers, recursion, and the concept of scope.

Uploaded by

pavancharan576
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)
41 views31 pages

UNIT 5 Functions FilesHandling

This document provides an introduction to functions in C programming, detailing their structure, declaration, definition, and calling conventions. It explains the importance of the main function, function prototypes, and various types of functions based on arguments and return values. Additionally, it covers passing arrays to functions, modifying parameters using pointers, recursion, and the concept of scope.

Uploaded by

pavancharan576
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

INTRODUCTION TO PROGRAMMING

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

General Format of ‘C’ Functions


type function_name(parameters declaration)
{
local variable declaration;
statement 1;
statement 2;
statement 3;
.
.
statement n;
return(expression);
}

FUNCTIONS DECLARATION AND FUNCTIONS DEFINITION AND


FUCNTION CALL
A function must be declared and defined. When the function is
created we need to consider both the function itself and how it interfaces
with many other functions. This includes passing of data to the function and
returning value back from the function. A function is called with function
name and passing any data to it in the parentheses. The calling and
passing data to a function is shown below.
functionName(data passed to function);

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

printf(“enter the first and second number”);


scanf(“%d%d”, &f, &s);
findmax(f,s);
return 0;
}
void findmax(int x, int y)
{
int m;
if(x > y)
m=x;
else
m=y;
printf(“%d”, m);
}
In the above program, findmax() function is called the called program
and the main() function is called the calling function. For every function we
need to have eh following:
 Function prototype
 Function call
 function definition

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);

from the above declaration the function findmax()expects two integer


values to be sent when the function is called and returns no value. Function
prototype may be placed within the function or outside the function. If
placed inside the function then it will be available to only main function. If it
is placed outside the main function then it will be available to all the

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
3
INTRODUCTION TO PROGRAMMING

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.

Function Call(calling a function)


Calling a function is an easy operation. The requirement is the name
of the function and the data passed to the function in the parenthesis. The
data enclosed in the parenthesis of call statement is called arguments or
actual arguments or actual parameters.

The data passed is generally numbers but sometimes it cannot be


numbers also. It can be an expression, then first we have to solve the
expression and the value obtained is passed to function.
findmax(f, s);

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.

Function Header Line


The function we write must begin with a function header line. Each
function is defined once but can be used by any function in the program.
Every C function consists of two parts, function header and function body.

The purpose of the function header is to identify the data type


returned, name and number, type and order of values expected by the
function. The purpose of function body is to operate on data passed and
return atmost one value back to the calling function.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
4
INTRODUCTION TO PROGRAMMING

The function header line for the findmax() function is as [Link]


format of the function is as shown below.
void findmax(int x, int y)

function header line function header


{
Variable declaration;
Any other C statements; function body
}
firstnum
A value

secnum
A value
findmax(firstnum, secnum);

send value to findmax() send value to findmax()

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(firstnum,secnum); ---- this statement calls findmax()

findmax()

The parameter x the parameter y

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
5
INTRODUCTION TO PROGRAMMING

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);
}

TYPES OF FUNCTIONS (RETURN TYPES AND ARGUMENTS)


A function depending on whether arguments are present are not are
whether a value is returned or not, may belong to one of the following:

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
6
INTRODUCTION TO PROGRAMMING

1. Void functions without parameters or Functions with no


arguments and no return values.
2. Functions with parameters / Function with argument and no
return values.
3. Non void with parameters / Function with arguments and
return values.
4. Non void without parameters / Functions with no arguments
and return values

/* Functions with No Arguments and No Return Values */


#include<stdio.h>
void sum();
int main(void)
{
sum();
return 0;
}
void sum()
{
int a, b;
printf(“enter the values of a,b”);
scanf(“%d%d”, &a, &b);
printf(“%d”, a+b);
}

/* Functions with arguments and no return values*/


#include<stdio.h>
void sum(int, int);
int main(void)
{
int a, b;
printf(“enter the values of a,b”);
scanf(“%d%d”, &a, &b);

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
7
INTRODUCTION TO PROGRAMMING

sum(a,b);
return 0;
}
void sum(int x, int y)
{
printf(“%d”, x+y);
}

/* Function With Arguments and Return Values*/


#include <stdio.h>
int sum(int, int);
int main(void)
{
int a, b,c;
printf(“enter the values of a,b”);
scanf(“%d%d”, &a, &b);
c=sum(a,b);
printf(“%d”, c);
return 0;
}
int sum(int x, int y)
{
return(x+y);
}

/* Functions with No Arguments and Return Values */


#include<stdio.h>
int sum();
int main(void)
{
int c;
c=sum();
printf(“%d”, c);

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
8
INTRODUCTION TO PROGRAMMING

return 0;
}
int sum()
{
int a, b;
printf(“enter the values of a,b”);
scanf(“%d%d”, &a, &b);
return(a+b);
}

PASSING ARRAYS TO FUNCTIONS (ARRAYS AS PARAMETERS)


1. Passing individual array elements to a function
Array elements can be passed to a function by calling the function:
 By value i.e. by passing values of array elements to the function.
 By reference i.e. passing addresses of array elements to the function.
/*Program for call by value*/
#include<stdio.h>
int main(void)
{
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);
}
/*Program for call by reference */
#include<stdio.h>
int main(void)
{

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
9
INTRODUCTION TO PROGRAMMING

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++;
}
}

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
10
INTRODUCTION TO PROGRAMMING

MODIFYING PARAMETERS INSIDE FUNCTIONS USING POINTERS


In this method the address of the actual arguments in the calling
function are copied into formal arguments of the called function. This means
that using the formal arguments in the called function we can make
changes in the actual arguments of the calling function.
#include<stdio.h>
main ()
{
int x, y;
printf (“enter the first value i.e. x is :”);
scanf (“%d”, &x);
printf (“enter the second value i.e. y is :”);
scanf (“%d”, &y);
swap(x, y);
printf (“in the main program:\n”);
printf (“x =%d\n”, x);
printf (“y=%d\n”, y);
}
swap (int *a, int *b)
{
int t;
printf (“in the swap function:\n “);
printf (“x=a=%d\n “,*a);
printf (“y =b=%d\n”,*b);
t=*a;
*a=*b;
*b=t;
printf (“after interchanging: \n”);
printf (“x=a=%d\n”,*a);
printf (“y=b=%d\n”,*b);
}

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
11
INTRODUCTION TO PROGRAMMING

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 …..

Therefore the definition can be written as


0! = 1
n! = n * (n-1)! for n > = 1

the recursive function in C for factorial function is


if n=0
factorial=1;
else
facotial=n*factorial(n-1);

program for factorial


#include<stdio.h>
int factorial(int);
int main(void)
{
int n, fact;
clrscr();
printf(“enter the value of n”);

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
12
INTRODUCTION TO PROGRAMMING

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);
}

Program for GCD of two numbers using recursion


#include<stdio.h>
int main(void)
{
int m,n,gc;
clrscr();
printf(“enter the values of m & n”);
scanf(“%d%d”, &m,&n);
gc=gcd(m,n));
printf(“the gcd of two number is %d”,gc);
return 0;
}
gcd(int x, int y)
{
int r;
r=x-(x/y*y);
if(r=0)
return(y);

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
13
INTRODUCTION TO PROGRAMMING

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.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
14
INTRODUCTION TO PROGRAMMING

 In the above diagram, the function fun is global definition that is


visible everywhere in the program

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

Object storage attributes


 Storage class specifiers control three attributes of an object’s storage
shown below:

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

Storage Class Specifiers


 There are four storage classes with four specifiers: auto, register,
static, extern
 The diagram for storage class specifiers is shown below

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
16
INTRODUCTION TO PROGRAMMING

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

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
17
INTRODUCTION TO PROGRAMMING

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.

Static Variable with Block Scope


 The static variable has two scopes: block and file
 When variable is declared in the block, static defines the extent of the
variable.
 It has the following properties
Scope: block
Extent: static
Linkage: internal
 It can be initialized where it is defined or left uninitialized.
 If initialized, it takes the initialized value other if not initialized its
value is zero since static variable needs an initialized value.
 The keyword static needed be explicitly coded
 A static variable will be initialized only once but it can have any
number of declarations.
 For example
#include<stdio.h>
int main()
{
for(int i=0;i<=3;i++)
{
static int x=1;
x++;
printf(“value of x is %d”, x);
}
return 0;
}

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
18
INTRODUCTION TO PROGRAMMING

Static Variable with File Scope


 When variable is declared in the global area, static defines the extent
of the variable.
 It has the following properties
Scope: file
Extent: static
Linkage: internal
 It can be initialized where it is defined or left uninitialized.
 If initialized, it takes the initialized value other if not initialized its
value is zero since static variable needs an initialized value.
 The keyword static needed be explicitly coded
 If same variable is declared inside the block then we get an error
 For example
#include<stdio.h>
static int x=1;
int main()
{
for(int i=0;i<=3;i++)
{
x++;
printf(“value of x is %d”, x);
}
return 0;
}

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

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
19
INTRODUCTION TO PROGRAMMING

 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,

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
20
INTRODUCTION TO PROGRAMMING

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.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
21
INTRODUCTION TO PROGRAMMING

DEFINING AND OPENING A FILE


If we want to store data in a file in the secondary memory, we must
specify certain things about the file, to the operating system. They include
1. Filename
2. Data structure
3. Purpose

Filename is a string of characters that make up a valid filename. Data


structure of a file is defined as FILE in the library of standard I/O function
definition. Therefore all files should be declared as type before they are used.
FILE is a defined data type. When we open a file we must specify what we
want to do with the file. For example we may write data to the file or read
the already existing data.

The General Format for Declaring And Opening A File


FILE *fp;
fp = fopen(“filename”,mode);

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.

Many recent compilers include additional modes of operations they are:


 r+ The existing file is opened to the beginning for both reading &
writing.
 w+ same as w except both for reading & writing.
 a+ Same as a except both for reading & writing.

Closing A File: A file must be closed as soon as all operations on it have


been completed. We have to close a file is when we want to reopen the same
file in a different mode. The I/O library supports the functions to do this
fclose (file_pointer)
Ex:
FILE *x1,*x2;
x1 = fopen(“salary”,r);
x2 = fopen(“employee”,w);
………
………
………
fclose (x1);
fclose (x2);

INPUT/OUTPUT OPERATIONS ON FILES


getc and putc functions: The simplest file I/O functions are getc and putc.
These are similar to getchar and putchar functions and handle one
character at a time. Assume that a file is opened with mode W and file
pointer fp then the statement is:
putc(c, fp);

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
23
INTRODUCTION TO PROGRAMMING

Writes the character contained in the character variable c to the file


associated with file pointer,fp. Similarly getc is used to read a character
from a file that has been opened in read mode, the statement is
c= getc(fp);

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);
}

The getw and putw Functions


The getw and putw are integer oriented functions. they are similar the
getc and putc functions, are used to read and write integer values. These
functions would be useful when we deal with only integer data. The general
form is:

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
24
INTRODUCTION TO PROGRAMMING

putw (integer, fp);


getw (fp);
Ex:
/*A file name DATA contains a series of integer numbers. Code a
program to read these numbers and then write all the odd numbers to
the file to be called ODD and all even numbers to a file to be called
EVEN.*/
#include<stdio.h>
main ( )
{
file *f1,*f2,*f3;
int num, i;
clrscr ( );
printf (“contents of data file:\n”);
f1=fopen (“data”,”w”);
for (i=1;i<=30;i ++)
{
scanf (“%d”, &num);
if (num==-1)
break;
else
putw (num, f1);
}
fclose (f1);
f1=fopen (“data”,”r”);
f2=fopen (“odd”,”w”);
f3=fopen (“even”,”w”);
while (num==getw (f1))! =eof)
{
if (num%2= =0)
putw (num, f3);
else
putw (num, f2);
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
25
INTRODUCTION TO PROGRAMMING

}
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);
}

fprintf and fscanf Functions


So far we have seen functions which can handle only one character or
integer at a time. Most of the compilers support two other functions namely
fprintf and fscanf functions that can handle a group of mixed data
simultaneously.

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);

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
26
INTRODUCTION TO PROGRAMMING

STATUS ENQUIRY FUNCTIONS


The feof function: This function can be used to test for an end of file
condition. It takes a file pointer as an argument and returns a non-zero
integer value id all of the data from the specified file has been read and
returns zero otherwise.
if(feof (fp)
printf(“end of file”);

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”);

RANDOM ACCESS ON FILES


ftell Function: This function is useful in saving the current position of a
file, which can be used later in the program. It takes the following form:
n = ftell ( fp);

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.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
27
INTRODUCTION TO PROGRAMMING

fseek Function: It is used to move the file position to a desired location


within the file It takes the following form:
fseek (file pointer, offset, position);

Here ‘file pointer’ is a pointer to the file, ‘offset’ is a number or variable


of type ‘long’, and position is an integer variable. The offset specifies the
positions (bytes) to be moved from the location specified by position.
Value Meaning
0 beginning of the file
1 current position
2 end of the file

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”);

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
28
INTRODUCTION TO PROGRAMMING

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”);

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
29
INTRODUCTION TO PROGRAMMING

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;
}

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
31

You might also like