Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

FUNCTIONS

In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program.

Advantage of functions in C

There are the following advantages of C functions.

o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call C functions any number of times in a program and from any place in a
program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.

Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.

User defined functions

User defined function can be divided into 3 aspects


1. Function Declaration
2. Function Definition
3. Function Calls

Function declaration:-
A function must be declared globally in a c program to tell the compiler about the function name,
function parameters, and return type.

C - PROGRAMMING UNIT-5[R-23] Page 1


Syntax:-
return_type name_of_the_function (parameter_1, parameter_2);

The parameter name is not mandatory while declaring functions. We can also declare the
function without using the name of the data variables.

Example:-
int sum(int a, int b);
int sum(int , int);

Function Definition
The function definition consists of actual statements which are executed when the function is
called (i.e. when the program control comes to the function). It is the most important aspect to
which the control comes when the function is called. Here, we must notice that only one value
can be returned from the function.
Syntax:-
return_type function_name( parameter list )
{
body of the function
}

A function definition in C programming consists of a function header and a function body. Here
are all the parts of a function −
 Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
 Function Body − The function body contains a collection of statements that define what
the function does.

Example:-
int max(int num1, int num2)
{
/* local variable declaration */
int result;

C - PROGRAMMING UNIT-5[R-23] Page 2


if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

Function call
Function can be called from anywhere in the program. The parameter list must not differ in
function calling and function declaration. We must pass the same number of functions as it is
declared in the function declaration.
Syntax:-
function_name (argument_list);

Example:-
sum=add(10,20);

Actual and Formal Parameters


In C programming language, parameters are variables that are used to pass values or references
between functions. There are two types of parameters: actual and formal parameters.

Actual Parameters:
Actual parameters are the values that are passed to a function when it is called. They are also
known as arguments. These values can be constants, variables, expressions, or even other
function calls. When a function is called, the actual parameters are evaluated, and their values are
copied into the corresponding formal parameters of the called function. Actual parameters are
enclosed in parentheses and separated by commas.
Example:-
int result = add(2, 3);
In this function call, 2 and 3 are the actual parameters, and they are passed to the function add,
which takes two formal parameters.

Formal Parameters:
Formal parameters are the variables declared in the function header that are used to receive the
values of the actual parameters passed during function calls. They are also known as function
parameters. Formal parameters are used to define the function signature and to specify the type
and number of arguments that a function can accept. Formal parameters are declared in the
function declaration or definition.

Example:-
int add(int a, int b);

C - PROGRAMMING UNIT-5[R-23] Page 3


In this function declaration, a and b are the formal parameters. They are used to receive the
values of the actual parameters passed during function calls.

Program:-
#include<stdio.h>
void sum(int, int);
main()
{
int a,b;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}

Output:-
Going to calculate the sum of two numbers:
Enter two numbers:2
3
The sum is 5

Program:-
#include <stdio.h>
int max_Num(int i, int j)
{
if (i > j)
return i;
else
return j;
}
main()
{
int x,y,m;
printf("Enter x value:");
scanf("%d",&x);
printf("Enter y value:");

C - PROGRAMMING UNIT-5[R-23] Page 4


scanf("%d",&y);
m = max_Num(x, y);
printf("The bigger number is %d", m);
}

Output:-
Enter x value: 20
Enter y value: 45
The bigger number is 45

Return Types and Arguments


Functions can be called either with or without arguments and might return values. They may or
might not return values to the calling functions.
1. Function with no arguments and no return value
2. Function with no arguments and with return value
3. Function with argument and with no return value
4. Function with arguments and with return value

1. Function with no arguments and no return value


In this method the main function does not pass any arguments and function does not return any
values.
Program:-
#include<stdio.h>
void sum();
main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("addtion of two numbers is :%d",a+b);
}
Output:-
Going to calculate the sum of two numbers:
Enter two numbers2 3
addtion of two numbers is :5

C - PROGRAMMING UNIT-5[R-23] Page 5


2. Function with no arguments and with return value
In this method the main function does not pass any arguments but function return the values.

Program :-
#include<stdio.h>
int fact();
main()
{
int result;
printf("\nGoing to calculate the factorial of given numbers:");
result=fact();
printf("Factorial of given number=%d",result);
}
int fact()
{
int a,i,fact=1;
printf("\nEnter the numbers");
scanf("%d",&a);
for(i=1;i<=a;i++)
fact=fact*i;
return fact;
}

Output:-
Going to calculate the factorial of given numbers:
Enter the numbers5
Factorial of given number=120

3. Function with argument and with no return value

In this method the main function pass arguments but function does not return the values.
Program:-
#include<stdio.h>
void swap(int,int);
main()
{
int a,b;
printf("\nEnter the first number:");
scanf("%d",&a);
printf("\nEnter the second number:");

C - PROGRAMMING UNIT-5[R-23] Page 6


scanf("%d",&b);
printf("\nBefore Swapping a=:%d\t b=%d",a,b);
swap(a,b);
}
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf("\nAfter Swapping a=%d\t b=%d",x,y);
}
Output:-
Enter the first number:23
Enter the second number:45
Before Swapping a=:23 b=45
After Swapping a=45 b=23

4. Function with arguments and with return value


In this method the main function pass arguments and the function return the values.

#include<stdio.h>
int big(int,int);
main()
{
int a,b;
printf("\nGoing to calculate the biggest of given numbers:");
printf("\nEnter the first number:");
scanf("%d",&a);
printf("\nEnter the second number:");
scanf("%d",&b);
printf("\nBig is :%d",big(a,b));
}
int big(int x,int y)
{
if(x>y)
return x;
else
return y;
}

C - PROGRAMMING UNIT-5[R-23] Page 7


Output:-
Going to calculate the biggest of given numbers:
Enter the first number: 23
Enter the second number: 44
Big is: 44

Calling a Function

When a program calls a function, the program control is transferred to the called function. A
called function performs a defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns the program control back to the main
program. To call a function, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned value.
There are two methods to pass the data into the function in C language, i.e., call by value and call
by reference.

Call by value
In call by value method, the value of the actual parameters is copied into the formal parameters.
In other words, we can say that the value of the variable is used in the function call in the call by
value method. In call by value method, we cannot modify the value of the actual parameter by
the formal parameter.
In call by value, different memory is allocated for actual and formal parameters since the value
of the actual parameter is copied into the formal parameter. The actual parameter is the argument
which is used in the function call whereas formal parameter is the argument which is used in the
function definition.

Program: Swapping the values of the two variables


#include<stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int a, int b)
{
int temp;

C - PROGRAMMING UNIT-5[R-23] Page 8


temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b);
}

Output:-
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by reference
In call by reference, the address of the variable is passed into the function call as the actual
parameter. The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
In call by reference, the memory allocation is similar for both formal parameters and actual
parameters. All the operations in the function are performed on the value stored at the address of
the actual parameters, and the modified value gets stored at the same address.

Program:-
#include <stdio.h>
int swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(&a,&b);
printf("After swapping values a = %d, b = %d\n",a,b);
}
int swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
}

Output:-
Before swapping the values in main a = 10, b = 20
After swapping values a = 20, b = 10

C - PROGRAMMING UNIT-5[R-23] Page 9


Difference between call by value and call by reference

No. Call by value Call by reference

1 A copy of the value is passed into the An address of value is passed into the
function function

2 A change made inside the function is Changes made inside the function
limited to the function only. The values validate outside of the function also. The
of the actual parameters do not change values of the actual parameters do
by changing the formal parameters. change by changing the formal
parameters.

3 Actual and formal arguments are created Actual and formal arguments are created
at the different memory location at the same memory location

Function returning pointer


A function can also return a pointer to a data item of any type. Following is the function
declaration syntax that will return pointer.

Syntax:-
returnType *functionName(param list);

Where, returnType is the type of the pointer that will be returned by the function functionName.
And param list is the list of parameters of the function which is optional.

Example:-
int *getMax(int *, int *);

program:-
#include <stdio.h>
int *getMax(int *, int *);
main()
{
int x;
int y;

C - PROGRAMMING UNIT-5[R-23] Page 10


int *max = NULL;
printf("Enter X value:");
scanf("%d",&x);
printf("Enter Y value:");
scanf("%d",&y);
max = getMax(&x, &y);
printf("Max value: %d\n", *max);
}

int *getMax(int *m, int *n)


{
if (*m > *n) {
return m;
}
else
{
return n;
}
}

Output:-
Enter X value:23
Enter Y value:45
Max value: 45

Pass Array to Functions

The whole array cannot be passed as an argument to a function. However, you can pass a
pointer to an array without an index by specifying the array’s name. Arrays in C are always
passed to the function as pointers pointing to the first element of the array.
There are 3 ways to declare the function which is intended to receive an array as an argument.

Syntax:-
First way:
return_type function(type arrayname[])
Declaring blank subscript notation [] is the widely used technique.
Second way:
return_type function(type arrayname[SIZE])
Optionally, we can define size in subscript notation [].

C - PROGRAMMING UNIT-5[R-23] Page 11


Third way:
return_type function(type *arrayname)
You can also use the concept of a pointer.

Example:-
int minarray(int arr[],int size);

program:-
#include<stdio.h>
int minarray(int arr[],int size)
{
int min=arr[0];
int i=0;
for(i=1;i<size;i++)
{
if(min>arr[i])
{
min=arr[i];
}
}
return min;
}

main()
{
int i,n,min;
int number[20];
printf("Enter the size of the matrix:");
scanf("%d",&n);
printf("\nEnter the arrayy elements:");
for(i=0;i<n;i++)
scanf("%d",&number[i]);
min=minarray(number,n);
printf("minimum number is %d \n",min);
}
Output:-
Enter the size of the matrix:5
Enter the arrayy elements:23
1
44

C - PROGRAMMING UNIT-5[R-23] Page 12


677
3
minimum number is 1

DYNAMIC MEMORY ALLOCATION

The concept of dynamic memory allocation in c language enables the C programmer to allocate
memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of
stdlib.h header file.

1. malloc()
2. calloc()
3. realloc()
4. free()

malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single
large block of memory with the specified size. It returns a pointer of type void which can be
cast into a pointer of any form. It doesn’t initialize memory at execution time so that it has
initialized each block with the default garbage value initially.

Syntax:-
ptr = (cast-type*) malloc(byte-size)

Example:-
int *ptr=(int*)malloc(5*sizeof(int));

Program:-
#include<stdio.h>
#include<stdlib.h>
main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}

C - PROGRAMMING UNIT-5[R-23] Page 13


printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
}

Output:-
Enter number of elements: 5
Enter elements of array: 1
2
3
44
5
Sum=55

calloc() method

“calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified


number of blocks of memory of the specified type. It is very much similar to malloc() but has
two different points and these are:
1. It initializes each block with a default value ‘0’.
2. It has two parameters or arguments as compare to malloc().

Syntax
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.

Example:
Ptr = (float*) calloc(5,sizeof(float);
The above statement allocates contiguous space in memory for 5 elements of type float.
Program:-
#include <stdio.h>
#include <stdlib.h>
main()
{

C - PROGRAMMING UNIT-5[R-23] Page 14


struct student
{
char rollNumber[3];
char name[64];
};
struct student *sptr;
struct student *tmp;
int i = 0;
int numberOfStudents = 3;
sptr = (struct student *) calloc (numberOfStudents, sizeof(struct student));
for(i = 0, tmp = sptr; i < numberOfStudents; i++, tmp++) {
printf("Enter detail of student #%d\n", (i+1));
printf("Enter Roll Number: ");
scanf("%s", tmp->rollNumber);
printf("Enter Name: ");
scanf("%s", tmp->name);
}
printf("\n\nFollowing are the student details:\n");
for(i = 0, tmp = sptr; i < numberOfStudents; i++, tmp++) {
printf("Detail of student #%d\n", (i+1));
printf("Roll Number: %s\n", tmp->rollNumber);
printf("Name: %s\n", tmp->name);
}
free(sptr);
}

Output:-
Enter detail of student #1
Enter Roll Number: 101
Enter Name: srikar
Enter detail of student #2
Enter Roll Number: 102
Enter Name: nani
Enter detail of student #3
Enter Roll Number: 103
Enter Name: sasi

C - PROGRAMMING UNIT-5[R-23] Page 15


Following are the student details:
Detail of student #1
Roll Number: 101
Name: srikar
Detail of student #2
Roll Number: 102
Name: nani
Detail of student #3
Roll Number: 103
Name: sasi

realloc() :-
“realloc” or “re-allocation” method in C is used to dynamically change the memory
allocation of a previously allocated memory. In other words, if the memory previously
allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically
re-allocate memory. Re-allocation of memory maintains the already present value and new
blocks will be initialized with the default garbage value.

Syntax:-
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.

Program:-
#include <stdio.h>
#include <stdlib.h>
main()
{
int *ptr = (int*) malloc(3 * sizeof(int));
ptr[0] = 1;
ptr[1] = 2;
ptr[2] = 3;
ptr = (int*) realloc(ptr, 5 * sizeof(int)); // resize the memory block to hold 5 integers
ptr[3] = 4;
ptr[4] = 5;
for (int i = 0; i< 5; i++)
{
printf("%d ", ptr[i]);
}
free(ptr);
}

C - PROGRAMMING UNIT-5[R-23] Page 16


Output:-
12345

free()
free method in C is used to dynamically de-allocate the memory. The memory allocated using
functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is
used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of
memory by freeing it.

Syntax
free(ptr);

COMMAND LINE ARGUMENTS

It is possible to pass some values from the command line to your C programs when they are
executed. These values are called command line arguments and many times they are important
for your program especially when you want to control your program from outside instead of hard
coding those values inside the code.
The command line arguments are handled using main() function arguments where argc refers to
the number of arguments passed, and argv[] is a pointer array which points to each argument
passed to the program.

Syntax:-
int main(int argc, char *argv[])
{
/* ... */
}
Here,
 argc (ARGument Count) is an integer variable that stores the number of command-line
arguments passed by the user including the name of the program. So if we pass a value to a
program, the value of argc would be 2 (one for argument and one for program name)
 The value of argc should be non-negative.
 argv (ARGument Vector) is an array of character pointers listing all the arguments.
 If argc is greater than zero, the array elements from argv[0] to argv[argc-1] will contain
pointers to strings.
 argv[0] is the name of the program , After that till argv[argc-1] every element is command
-line arguments.

C - PROGRAMMING UNIT-5[R-23] Page 17


Program:-
#include<stdio.h>
int main(int argc,char *argv[])
{
printf("argc =%d",argc);
printf("\n argv[0] =%s",argv[0]);
}
E:\nani>re.exe
argc =1
argv[0] =re.exe
E:\nani>

Program:-
#include<stdio.h>
int main(int argc,char *argv[])
{
int i,avg,count=0;
int sum=0;
int c=argc;
printf("Name of the student=%s",argv[1]);
for(i=2;i<c;i++)
{
sum+=atoi(argv[i]);
count++;
}
avg=sum/count;
printf("\n Sum=%d",sum);
printf("\n Average=%d",avg);
}

Output:-

E:\nani>re.exe srikar 10 20 30 40
Name of the student=srikar
Sum=100
Average=25
E:\nani>

C - PROGRAMMING UNIT-5[R-23] Page 18


STORAGE CLASSES
Storage classes in C are used to determine the lifetime, visibility, memory location, and initial
value of a variable. There are four types of storage classes.
o Automatic
o External
o Static
o Register

Storage Storage Default Scope Lifetime


Classes Place Value

auto RAM Garbage Local Within function


Value

extern RAM Zero Global Till the end of the main program Maybe
declared anywhere in the program

static RAM Zero Local Till the end of the main program, Retains
value between multiple functions call

register Register Garbage Local Within the function


Value

Automatic
Automatic variables are allocated memory automatically at runtime. The visibility of the
automatic variables is limited to the block in which they are defined. The scope of the automatic
variables is limited to the block in which they are defined. The automatic variables are initialized
to garbage by default. The memory assigned to automatic variables gets freed upon exiting from
the block. The keyword used for defining automatic variables is auto. Every local variable is
automatic in C by default.

Example :-
#include <stdio.h>
int main()
{
int a = 10,i;
printf("%d ",++a);
{
int a = 20;

C - PROGRAMMING UNIT-5[R-23] Page 19


for (i=0;i<3;i++)
{
printf("\n%d ",a); // 20 will be printed 3 times since it is the local value of a
}
}
printf("\n%d ",a); // 11 will be printed since the scope of a = 20 is ended.
}

Output:-
11
20
20
20
11

External
The external storage class is used to tell the compiler that the variable defined as extern is
declared with an external linkage elsewhere in the program. The variables declared as extern are
not allocated any memory. It is only declaration and intended to specify that the variable is
declared elsewhere in the program. The default initial value of external integral type is 0
otherwise null.
If a variable is declared as external then the compiler searches for that variable to be initialized
somewhere in the program which may be extern or static. If it is not, then the compiler will show
an error.

Program:-
#include <stdio.h>
int main()
{
extern int a; // Compiler will search here for a variable a defined and initialized somewhere in the
//pogram or not.
printf("a=%d",a);
}
int a = 20;

Output:-
a=20

C - PROGRAMMING UNIT-5[R-23] Page 20


Static
The variables defined as static specifier can hold their value between the multiple function calls.
Static local variables are visible only to the function or the block in which they are defined. A
same static variable can be declared many times but can be assigned at only one time. Default
initial value of the static integral variable is 0 otherwise null. The keyword used to define static
variable is static.

Program:-
#include<stdio.h>
void sum()
{
static int a = 10;
static int b = 24;
printf("%d %d \n",a,b);
a++;
b++;
}
void main()
{
int i;
for(i = 0; i< 3; i++)
{
sum(); // The static variables holds their value between multiple function calls.
}
}

Output:-
10 24
11 25
12 26

Register
The register storage class is used to define local variables that should be stored in a register
instead of RAM. This means that the variable has a maximum size equal to the register size
(usually one word) and can't have the unary '&' operator applied to it (as it does not have a
memory location). We cannot dereference the register variables, i.e., we cannot use &operator
for the register variable. The access time of the register variables is faster than the automatic
variables. The initial default value of the register local variables is 0.

C - PROGRAMMING UNIT-5[R-23] Page 21


Program:-
#include <stdio.h>
int main()
{
register int a = 10;
printf("a=%d",a);
}

Output:-
a=10

FILE

A File is a collection of data stored in the secondary memory. A file refers to a source in which a
program stores the information/data in the form of bytes of sequence on a disk permanently.
Files are used for storing information that can be processed by the programs. Files are not only
used for storing the data, programs are also stored in files.

Features of using files:


 Reusability: The data stored in the file can be accessed, updated, and deleted anywhere
and anytime providing high reusability.
 Portability: Without losing any data, files can be transferred to another in the computer
system. The risk of flawed coding is minimized with this feature.
 Efficient: A large amount of input may be required for some programs. File handling
allows you to easily access a part of a file using few instructions which saves a lot of time
and reduces the chance of errors.
 Storage Capacity: Files allow you to store a large amount of data without having to worry
about storing everything simultaneously in a program.

Types of Files
A file can be classified into two types based on the way the file stores the data. They are as
follows:
 Text Files
 Binary Files

1.Text Files
A text file contains data in the form of ASCII characters and is generally used to store a
stream of characters.
 Each line in a text file ends with a new line character (‘\n’).
 It can be read or written by any text editor.

C - PROGRAMMING UNIT-5[R-23] Page 22


 They are generally stored with .txt file extension.
 Text files can also be used to store the source code.

2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They
contain data that is stored in a similar manner to how it is stored in the main memory.
 The binary files can be created only from within a program and their contents can only be
read by a program.
 More secure as they are not easily readable.
 They are generally stored with .bin file extension.

File Operations

File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program. The following operations can be performed on a file.

1. Opening a file
2. Writing to a file
3. Reading from file
4. Closing a file

File Pointer
A file pointer is a reference to a particular position in the opened file. It is used in file handling
to perform all file operations such as read, write, close, etc. We use the FILE macro to declare
the file pointer variable. The FILE macro is defined inside <stdio.h> header file.
Syntax:-
FILE* pointer_name;

Example:-
FILE *ptr;

Opening File
We must open a file before it can be create, read, write, or update. The fopen() function is used
to open a file.

Syntax:-
FILE *file_pointer ;
File_pointer = fopen(“file name”, “mode”);

C - PROGRAMMING UNIT-5[R-23] Page 23


The fopen() function accepts two parameters:

o The file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored.
o The mode in which the file is to be opened. It is a string.

We can use one of the following modes in the fopen() function.

Mode Description

r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

The fopen function works in the following way.


o Firstly, It searches the file to be opened.
o Then, it loads the file from the disk and place it into the buffer. The buffer is used to
provide efficiency for the read operations.
o It sets up a character pointer which points to the first character of the file.

Example:-
FILE *p1;
p1 =fopen(“data”, “r”);

C - PROGRAMMING UNIT-5[R-23] Page 24


Closing File
The fclose() function is used to close a file. The file must be closed after performing all the
operations on it.

Syntax:-
fclose(file_pointer);

Example:-
fclose(ptr);

program:-
#include <stdio.h>
#include <stdlib.h>
main()
{
// file pointer
FILE* fptr;
// creating file using fopen() access mode "w"
fptr = fopen("file1.txt", "w");
// checking if the file is created
if (fptr == NULL) {
printf("The file is not opened. The program will "
"exit now");
exit(0);
}
else {
printf("The file is created Successfully.");
}
}

Output:-
The file is created Successfully.

Writing to a file
fputc()
The fputc() function is used to write a single character into file. It outputs a character to a stream.
Syntax:-
fputc(character, filepointer);

Example:-
fputc(‘a’,ptr);

C - PROGRAMMING UNIT-5[R-23] Page 25


fputs()
The fputs() function writes a line of characters into file. It outputs string to a stream.

Syntax:
fputs(string, file pointer);

Example:-
fputs("hello c programming",fp);

fprintf()
The fprintf() function is used to write set of characters into file. It sends formatted output to a
stream.
Syntax:-
fprintf(file pointer, “control string”, list) ;
Where file pointer associated with a file that has been opened for writing. The control string and
strings.

Example:-
fprintf(fp,”%s,%d,%f ”,name,age,height);

Reading from file:-

getc():-
getc() is used to read a character from a file that has been opened in read mode.

Syntax:-
Variable = getc(file ponter);

Example:-
c = getc(fp);
Where fp is file pointer.

gets():-
gets() is used to read a string from a file that has been opened in read mode.

Syntax:-
Variable = gets(file ponter);

Example:-
c = gets(fp);

C - PROGRAMMING UNIT-5[R-23] Page 26


fscanf():
The fscanf() function is used to read set of characters from file. It reads a word from the file and
returns EOF at the end of file.ward Skip 10s

Syntax:-
fscanf(file pointer, “control string”, list) ;
Where file pointer associated with a file that has been opened for writing. The control string and
strings.

Example:-
fscanf(fp,”%s,%d,%f ”,&name, &age, &height);

program:-
#include<stdio.h>
#include<stdlib.h>
main()
{
char name[30];
int i,score,n;
FILE *f1;
f1=fopen("marks.txt","w");
printf("Enter the students details:");
printf("\n Enter the name:");
scanf("%s",name);
printf("Enter the score:");
scanf("%d",&score);
fprintf(f1,"\n%s",name);
fprintf(f1,"\t%d",score);
printf("\n");
fclose(f1);
f1=fopen("marks.txt","r");
fscanf(f1,"%s%d",&name,&score);
printf("\nstudent details are:");
printf("\n Name=%s",name);
printf("\tScore=%d",score);
fclose(f1);
}

C - PROGRAMMING UNIT-5[R-23] Page 27


Output:-
Enter the students details:
Enter the name:srikar
Enter the score:89
student details are:
Name=srikar Score=89

Program:-
#include<stdio.h>
#include<stdlib.h>
main()
{
char name[30];
int i,score,n;
FILE *f1;
f1=fopen("marks.txt","w");
printf("Enter the no of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the name:");
scanf("%s",name);
printf("Enter the score:");
scanf("%d",&score);
fprintf(f1,"\n%s",name);
fprintf(f1,"\t%d",score);
printf("\n");
}
fclose(f1);
f1=fopen("marks.txt","r");
while(fscanf(f1,"%s%d",&name,&score)!=EOF)
{
printf("\n Name=%s",name);
printf("\tScore=%d",score);
}
fclose(f1);
}

C - PROGRAMMING UNIT-5[R-23] Page 28


Output:-
Enter the no of students:2
Enter the name:srikar
Enter the score:57
Enter the name:nani
Enter the score:89

Name=srikar Score=57
Name=nani Score=89

Random Access file


In C language, a random access file allows us to read or write any data in our disc file without
reading or writing every piece of data before it. We can quickly search for data, edit it, or even
delete it in a random-access file. We can open and close random access files in C using the same
opening mode as sequential files, but we need a few new functions to access files randomly.
Functions in random access file:
Thus, the following three functions assist in accessing the random access file in C:
1. ftell()
2. fseek()
3. rewind()

1. ftell():
It is a standard C library function used to get the current position of the file pointer in a random
access file. The function takes a file pointer as its argument and returns the current position of
the file pointer, representing the number of bytes from the beginning of the file.

Syntax:-
pos=ftell(FILE *fp)
Where pos contain the current position or the number of bytes read, and fp is a file pointer.

Program:-
#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen("marks.txt","r");
if(!fp)
{
printf("Error: File cannot be opened\n") ;
return 0;

C - PROGRAMMING UNIT-5[R-23] Page 29


}
printf("Position pointer in the beginning : %ld\n",ftell(fp));

char ch;
while(fread(&ch,sizeof(ch),1,fp)==1)
{
printf("%c",ch);
}

printf("\nSize of file in bytes is : %ld\n",ftell(fp));


printf("Current pointer Position : %ld\n",ftell(fp));
fclose(fp);
return 0;
}

Output:-
Position pointer in the beginning : 0
srikar 57
nani 89
Size of file in bytes is : 20
Current pointer Position : 20

2. fseek():
The fseek() function is a standard library function in the C programming language. It is used to
set the file position indicator to a specified position in a file, allowing the program to read or
write data from that position.

Syntax:-
int fseek(FILE *fp, long offset, int whence);

Offset is the number of bytes to offset from the specified position, and whence is the origin from
which to measure the offset. The function returns zero if the operation is successful, and a
nonzero value if an error occurs.
The whence argument can be one of the following constants:
 SEEK_SET: The offset is relative to the beginning of the file.
 SEEK_CUR: The offset is relative to the current position in the file.
 SEEK_END: The offset is relative to the end of the file.

C - PROGRAMMING UNIT-5[R-23] Page 30


Program:-
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("marks.txt","r");
if(!fp)
{
printf("Error: File cannot be opened\n");
return 0;
}
fseek(fp, 4, 0);
char ch;
while(fread(&ch,sizeof(ch),1,fp)==1)
{
printf("%c",ch);
}
fclose(fp);
return 0;
}

Output:-
ikar 57
nani 89

3. rewind():
The rewind() function is a standard library function in C programming language. It is used to set
the file position indicator to the beginning of a file, allowing the file to be read from the start
again.

Syntax :
rewind(FILE *fp);

program:-
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("marks.txt","r");
if(!fp)

C - PROGRAMMING UNIT-5[R-23] Page 31


{
printf("Error in opening file\n");
return 0;
}
printf("Position of the pointer : %ld\n",ftell(fp));
char ch;
while(fread(&ch,sizeof(ch),1,fp)==1)
{ printf("%c",ch);
}
printf("\nPosition of the pointer : %ld\n",ftell(fp));
rewind(fp);
printf("Position of the pointer after rewind: %ld\n",ftell(fp));
fclose(fp);
return 0;
}

Output:-
Position of the pointer : 0
srikar 57
nani 89
Position of the pointer : 20
Position of the pointer after rewind: 0

MACROS

A macro is a segment of code which is replaced by the value of macro. Macro is defined by
#define directive. Macros in the C programming language are a powerful tool that allows
developers to define reusable pieces of code, constants, and even function-like constructs.
Utilizing macros can lead to more efficient and readable code by replacing repetitive or complex
expressions with concise and clear identifiers.

Types of macros:

1. Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. They are similar to constants and are often used to improve code readability
and maintainability by giving meaningful names to commonly used values.

C - PROGRAMMING UNIT-5[R-23] Page 32


Example:-
#define PI 3.14
Where
#define - Preprocessor Directive
PI - Macro Name
3.14 - Macro Value

Program:-
#include<stdio.h>
// This is macro definition
#define PI 3.14
main()
{

int radius;
float area;
printf("Enter the radius:");
scanf("%d",&radius);
area = PI * (radius*radius);
printf("Area of circle is %f", area);
}

Output:-
Enter the radius:5
Area of circle is 78.500000

2. Function-like Macros
The function-like macro looks like function call. They accept arguments and can perform
complex operations, offering a convenient way to create reusable code blocks.

Example:-
#define MIN(a,b) ((a)<(b)?(a):(b))

Program:-
#include <stdio.h>
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int main()
{
int num1 = 20, num2 = 35;
printf("The maximum of %d and %d is %d\n", num1, num2, MAX(num1, num2));

C - PROGRAMMING UNIT-5[R-23] Page 33


return 0;
}

Output:-
The maximum of 20 and 35 is 35

Chain like Macros in C


When we use one macro inside another macro, then it is known as the chain-like macro.

Example:-
#define PI 3.14
#define Area(r) (PI*(r*r))

Program:-
#include <stdio.h>
//object like macro
#define PI 3.14
// function like macro
#define Area(r) (PI*(r*r))
void main()
{
int radius;
float area;
printf("Enter the radius:");
scanf("%d",&radius);
area = Area(radius);
printf("Area of circle is %f\n", area);
}

Output:-
Enter the radius:5
Area of circle is 78.500000

C - PROGRAMMING UNIT-5[R-23] Page 34


Predefined Macros
ANSI C defines many predefined macros that can be used in c program.

N Macro Description
o.

1 _DATE represents current date in "MMM DD YYYY" format.


_

2 _TIME_ represents current time in "HH:MM:SS" format.

3 _FILE_ represents current file name.

4 _LINE_ represents current line number.

5 _STDC It is defined as 1 when compiler complies with the ANSI standard.


_

Example:-
#include<stdio.h>
int main()
{
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("STDC :%d\n", __STDC__ );
return 0;
}
Output:
File :E:\nani\re.c
Date :Jan 2 2024
Time :16:21:40
Line :7
STDC :1

C - PROGRAMMING UNIT-5[R-23] Page 35

You might also like