0% found this document useful (0 votes)
17 views35 pages

Ip - Unit 5

The document provides an overview of functions and file handling in C programming, detailing function declaration, definition, types, and aspects such as return values and parameter passing methods (call by value and call by reference). It explains the advantages of using functions for code reusability and modularity, and includes examples of different types of user-defined functions. Additionally, it covers library functions and the importance of including header files for accessing standard library functions.
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)
17 views35 pages

Ip - Unit 5

The document provides an overview of functions and file handling in C programming, detailing function declaration, definition, types, and aspects such as return values and parameter passing methods (call by value and call by reference). It explains the advantages of using functions for code reusability and modularity, and includes examples of different types of user-defined functions. Additionally, it covers library functions and the importance of including header files for accessing standard library functions.
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/ 35

UNIT V Functions & File Handling

Introduction to Functions, Function Declaration and Definition, Function call Return Types and
Arguments, modifying parameters inside functions using pointers, arrays as parameters. Scope and
Lifetime of Variables, Basics of File Handling

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. In other words, we can
say that the collection of functions creates a program. The function is also known as procedure
or subroutine in other programming languages.

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.

Function Aspects

There are three aspects of a C function.

o 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.
o 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.
o Function definition It contains the actual statements which are to be executed. 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 fromthe function.

SNo C function aspects Syntax

1 Function declaration return_type function_name (argument list);

2 Function call function_name (argument_list)

3 Function definition return_type function_name (argument list)


{
function body;
}
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
manytimes. It reduces the complexity of a big program and optimizes the code.

Return Value

A C function may or may not return a value from the function. If you don't have to return any value from
thefunction, use void for the return type.

Let's see a simple example of C function that doesn't return any value from the function.

Example without return value

void hello()
{
printf("hello c");
}

If you want to return any value from the function, you need to use any data type such as int, long, char, etc.
Thereturn type depends on the value to be returned from the function.

Let's see a simple example of C function that returns int value from the function.

Example with return

value:int get()
{
return 10;
}

In the above example, we have to return 10 as a value, so the return type is int. If you want to return floating-
pointvalue (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of the method.

1. float get(){
2. return
10.2;3. }

Now, you need to call the function, to get the value of the function.
Different aspects of function calling/Types of user defined functions:
A function may or may not accept any argument. It may or may not return any value. Based on these facts, There
are four different aspects of function calls.

o function without arguments and without return value


o function without arguments and with return value
o function with arguments and without return value
o function with arguments and with return value

Example for Function without argument and return value

Example 1

1. #include<stdio.h>
2. void printName();
3. void main ()
4. {
5. printf("Hello ");
6. printName();
7. }
8. void printName()
9. {
10. printf("welcome");
11. }

Output

Hello welcome

Example 2

#include<stdio.h>
void sum();
void 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("The sum is %d",a+b);
}

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example for Function without argument and with return value


Example 1

#include<stdio.h>
1. int sum();
2. void main()
3. {
4. int result;
5. printf("\nGoing to calculate the sum of two numbers:");
6. result = sum();
7. printf("%d",result);
8. }
9. int sum()
10. {
11. int a,b;
12. printf("\nEnter two numbers");
13. scanf("%d %d",&a,&b);
14. return a+b;
15. }

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example 2: program to calculate the area of the square

1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. printf("Going to calculate the area of the square\n");
6. float area = square();
7. printf("The area of the square: %f\n",area);
8. }
9. int square()
10. {
11. float side;
12. printf("Enter the length of the side in meters: ");
13. scanf("%f",&side);
14. return side * side;
15. }

Output

Going to calculate the area of the square


Enter the length of the side in meters: 10
The area of the square: 100.000000

Example for Function with argument and without return value


Example 1:

1. #include<stdio.h>
2. void sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10. }
11. void sum(int a, int b)
12. {
13. printf("\nThe sum is %d",a+b);
14. }

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example 2: program to calculate the average of five numbers


1. #include<stdio.h>
2. void average(int, int, int, int, int);
3. void main()
4. {
5. int a,b,c,d,e;
6. printf("\nGoing to calculate the average of five numbers:");
7. printf("\nEnter five numbers:");
8. scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12. {
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16. }

Output

Going to calculate the average of five numbers:


Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000

Example for Function with argument and with return value


Example:

1. #include<stdio.h>
2. int sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }

Output
Going to calculate the sum of two numbers:
Enter two numbers:10
20
The sum is : 30

Example 2: Program to check whether a number is even or odd

1. #include<stdio.h>
2. int even_odd(int);
3. void main()
4. {
5. int n,flag=0;
6. printf("\nGoing to check whether a number is even or odd");
7. printf("\nEnter the number: ");
8. scanf("%d",&n);
9. flag = even_odd(n);
10. if(flag == 0)
11. {
12. printf("\nThe number is odd");
13. }
14. else
15. {
16. printf("\nThe number is even");
17. }
18. }
19. int even_odd(int n)
20. {
21. if(n%2 == 0)
22. {
23. return 1;
24. }
25. else
26. {
27. return 0;
28. }
29. }

Output

Going to check whether a number is even or odd


Enter the number: 100
The number is even

Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common place called the library.
Such functions are used to perform some specific operations. For example, printf is a library function used to print
on the console. The library functions are created by the designers of compilers. All C standard library functions are
defined inside the different header files saved with the extension .h.

We need to include these header files in our program to make use of the library functions defined in such header
files. For example, To use the library functions such as printf/scanf we need to include stdio.h in our program which
is a header file that contains all the library functions regarding standard input/output.

The list of mostly used header files is given in the following table.

S.No Header file Description

1 stdio.h This is a standard input/output header file. It contains all the library functio
regarding standard input/output.

2 conio.h This is a console input/output header file.

3 string.h It contains all string related library functions like gets(), puts(),etc.

4 stdlib.h This header file contains all the general library functions like malloc
calloc(), exit(), etc.

5 math.h This header file contains all the math operations related functions like sqrt
pow(), etc.

6 time.h This header file contains all the time-related functions.

7 ctype.h This header file contains all character handling functions.

8 stdarg.h Variable argument functions are defined in this header file.

9 signal.h All the signal handling functions are defined in this header file.

10 setjmp.h This file contains all the jump functions.

11 locale.h This file contains locale functions.

12 errno.h This file contains error handling functions.

13 assert.h This file contains diagnostics functions.

Call by value and Call by reference in C


There are two methods to pass the data into the function in C language, i.e., call by value and call by reference.
Let's understand call by value and call by reference in c language one by one.

Call by value in C:
o 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.
o In call by value method, we can not modify the value of the actual parameter by the formal parameter.
o 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.
o 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.

Let's try to understand the concept of call by value in c language by the example given below:

1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by Value Example: Swapping the values of the two variables


1. #include <stdio.h>
2. void swap(int , int); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main
8. swap(a,b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do not change by
changing the formal parameters in call by value, a = 10, b = 20
10. }
11. void swap (int a, int b)
12. {
13. int temp;
14. temp = a;
15. a=b;
16. b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b = 10
18. }
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 C
o In call by reference, the address of the variable is passed into the function call as the actual parameter.
o The value of the actual parameters can be modified by changing the formal parameters since the address of the
actual parameters is passed.
o 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.

Consider the following example for the call by reference.

1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two variables
1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do change in call
by reference, a = 10, b = 20
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20, b = 10
18. }
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 = 20, b = 10

Difference between call by value and call by reference in c

S.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 Changes made inside the function is Changes made inside the function validate
limited to the function only. The values of outside of the function also. The values of
the actual parameters do not change by the actual parameters do change by
changing the formal parameters. changing the formal parameters.

3 Actual and formal arguments are created at Actual and formal arguments are created at
the different memory location the same memory location
Recursion in C
Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller
problem. Any function which calls itself is called recursive function, and such function calls are called recursive
calls. Recursion involves several numbers of recursive calls. However, it is important to impose a termination
condition of recursion. Recursion code is shorter than iterative code however it is difficult to understand.

Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be defined in terms of
similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal problems.

Generally, iterative solutions are more efficient than recursion since function call is always overhead. Any problem
that can be solved recursively, can also be solved iteratively. However, some problems are best suited to be solved
by the recursion, for example, tower of Hanoi, Fibonacci series, factorial finding, etc.
In the following example, recursion is used to calculate the factorial of a number.

1. #include <stdio.h>
2. int fact (int);
3. int main()
4. {
5. int n,f;
6. printf("Enter the number whose factorial you want to calculate?");
7. scanf("%d",&n);
8. f = fact(n);
9. printf("factorial = %d",f);
10. }
11. int fact(int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if ( n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return n*fact(n-1);
24. }
25. }
Output
Enter the number whose factorial you want to calculate?5
factorial = 120

We can understand the above program of the recursive method call by the figure given below:
Recursive Function:
A recursive function performs the tasks by dividing it into the subtasks. There is a termination condition defined
in the function which is satisfied by some specific subtask. After this, the recursion stops and the final result is
returnedfrom the function.

The case at which the function doesn't recur is called the base case whereas the instances where the function
keeps calling itself to perform a subtask, is called the recursive case. All the recursive functions can be written
using thisformat.

Pseudocode for writing any recursive function is given below.

1. if
(test_for_base)2. {
3. return
some_value;4. }
5. else if
(test_for_another_base)6. {
7. return
some_another_value;8. }
9. else
10. {
11. // Statements;
12. recursive call;
13. }

Example of recursion in C

Let's see an example to find the nth term of the Fibonacci series.

1. #include<stdio.h>
2. int fibonacci(int);
3. void main
()4. {
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10. }
11. int fibonacci (int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if (n == 1)
18. {
19. return 1;
20. }
21. else
22. { return fibonacci(n-1)+fibonacci(n-2);
23. }
24. }
Output
Enter the value of n?12
144

Memory allocation of Recursive method:


Each recursive call creates a new copy of that method in the memory. Once some data is returned by the method,
the copy is removed from the memory. Since all the variables and other stuff declared inside function get stored in
the stack, therefore a separate stack is maintained at each recursive call. Once the value is returned from the
corresponding function, the stack gets destroyed. Recursion involves so much complexity in resolving and tracking
the values at each recursive call. Therefore we need to maintain the stack and track the values of the variables
defined in the stack.

Let us consider the following example to understand the memory allocation of the recursive functions.

1. int display (int n)


2. {
3. if(n == 0)
4. return 0; // terminating condition
5. else
6. {
7. printf("%d",n);
8. return display(n-1); // recursive call9.
}
10. }

Explanation
Let us examine this recursive function for n = 4. First, all the stacks are maintained which prints the corresponding
value of n until n becomes 0, Once the termination condition is reached, the stacks get destroyed one by one by
returning 0 to its calling stack. Consider the following image for more information regarding the stack trace for the
recursive functions.
Scope and Life Time of Variable
Storage Classes in C
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program
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 in C

o Automatic
o External
o Static
o Register

Storage Stora Default Scope Lifetime


Classes ge Value
Place
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/Global Till the end of the main program,
Retains value between multiple
functions call

Register Register Garbage Local Within the function


Value

Automatic
o Automatic variables are allocated memory automatically at runtime.
o 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.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.

Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a; //auto
5. char b;
6. float c;
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c.
8. return 0;
9. }

Output:

garbage garbage garbage


Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int a = 10,i;
5. printf("%d ",++a);
6. {
7. int a = 20;
8. for (i=0;i<3;i++)
9. {
10. printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
11. }
12. }
13. printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
14. }

Output:

11 20 20 20 11

Static

o The variables defined as static specifier can hold their value between the multiple function calls.
o Static local variables are visible only to the function or the block in which they are defined.
o A same static variable can be declared many times but can be assigned at only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has declared.
o The keyword used to define static variable is static.
Example 1
1. #include<stdio.h>
2. static char c;
3. static int i;
4. static float f;
5. static char s[100];
6. void main ()
7. {
8. printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
9. }

Output:

0 0 0.000000 (null)
Example 2
1. #include<stdio.h>
2. void sum()
3. {
4. static int a = 10;
5. static int b = 24;
6. printf("%d %d \n",a,b);
7. a++;
8. b++;
9. }
10. void main()
11. {
12. int i;
13. for(i = 0; i< 3; i++)
14. {
15. sum(); // The static variables holds their value between multiple function calls.
16. }
17. }

Output:

10 24
11 25
12 26

Register
o The variables defined as the register is allocated the memory into the CPU registers depending upon the size of the
memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for the register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU register. However, it is compiler?s
choice whether or not; the variables can be stored in the register.
o We can store pointers into the register, i.e., a register can store the address of a variable.
o Static variables can not be stored into the register since we can not use more than one storage specifier for the same
variable.

Example 1
1. #include <stdio.h>
2. int main()
3. {
4. register int a; // variable a is allocated memory in the CPU register. The initial default value of a is 0.
5. printf("%d",a);
6. }

Output:

0
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. register int a = 0;
5. printf("%u",&a); // This will give a compile time error since we can not access the address of a register variable.
6. }

Output:

main.c:5:5: error: address of register variable ?a? requested


printf("%u",&a);
^~~~~~

External
o 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.
o 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.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the external variable within any block
or method.
o An external variable can be declared many times but can be initialized at only once.
o 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.

Example 1
1. #include <stdio.h>
2. int main()
3. {
4. extern int a;
5. printf("%d",a);
6. }
Output

main.c:(.text+0x6): undefined reference to `a'


collect2: error: ld returned 1 exit status
Example 2
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a; // variable a is defined globally, the memory will not be allocated to a
6. printf("%d",a);
7. } Output
0
Example 3
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a = 0; // this will show a compiler error since we can not use extern and initializer at same time
6. printf("%d",a);
7. }

Output

compile time error


main.c: In function ?main?:
main.c:5:16: error: ?a? has both ?extern? and initializer
extern int a = 0;
Example 4
1. #include <stdio.h>
2. int main()
3. {
4. extern int a; // Compiler will search here for a variable a defined and initialized somewhere in the pogram or not.
5. printf("%d",a);
6. }
7. int a = 20;

Output

20
Example 5
1. extern int a;
2. int a = 10;
3. #include <stdio.h>
4. int main()
5. {
6. printf("%d",a);
7. }
8. int a = 20; // compiler will show an error at this line
Output

compile time error

Memory Allocation in C Programs


The C language supports two kinds of memory allocation through the variables in C programs:

• Static allocation is what happens when you declare a static or global variable. Each static or global variable
defines one block of space, of a fixed size. The space is allocated once, when your program is started (part of the
exec operation), and is never freed.
• Automatic allocation happens when you declare an automatic variable, such as a function argument or a local
variable. The space for an automatic variable is allocated when the compound statement containing the declaration
is entered, and is freed when that compound statement is exited.

In GNU C, the size of the automatic storage can be an expression that varies. In other C implementations, it must
be a constant.

A third important kind of memory allocation, dynamic allocation, is not supported by C variables but is available
via GNU C Library functions.

• Dynamic Memory Allocation


Dynamic memory allocation is a technique in which programs determine as they are running where to store some
information. You need dynamic allocation when the amount of memory you need, or how long you continue to
need it, depends on factors that are not known before the program runs.
For example, you may need a block to store a line read from an input file; since there is no limit to how long a line
can be, you must allocate the memory dynamically and make it dynamically larger as you read more of the line.
Dynamic memory allocation in C:
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()
Let's understand the difference between static memory allocation and dynamic memory allocation.
static memory allocation dynamic memory allocation
memory is allocated at compile time. memory is allocated at run time.
memory can't be increased while executing program. memory can be increased while executing program.
used in array. used in linked list.
Now let's have a quick look at the methods used for dynamic memory allocation.
malloc() allocates single block of requested memory.
calloc() allocates multiple block of requested memory.

realloc() reallocates the memory occupied by malloc() or calloc() functions.

free() frees the dynamically allocated memory.


malloc() function in C:

The malloc() function allocates single block of requested memory.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

1. ptr=(cast-type*)malloc(byte-size)

Let's see the example of malloc() function.

1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }

Output

Enter elements of array: 3


Enter elements of array: 10
10
10
Sum=30

calloc() function in C:
The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.


It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

1. ptr=(cast-type*)calloc(number, byte-size)

Let's see the example of calloc() function.

1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. } Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C:
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it
changes the memory size.

Let's see the syntax of realloc() function.

1. ptr=realloc(ptr, new-size)

free() function in C:
The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it
will consume memory until program exit.
Let's see the syntax of free() function.

1. free(ptr)

Reading complex pointers:


There are several things which must be taken into the consideration while reading the complex pointers in C. Lets
see the precedence and associativity of the operators which are used regarding pointers.

Operator Precedence Associativity

(), [] 1 Left to right

*, identifier 2 Right to left

Data type 3 -

Here,we must notice that,

o (): This operator is a bracket operator used to declare and define the function.
o []: This operator is an array subscript operator
o * : This operator is a pointer operator.
o Identifier: It is the name of the pointer. The priority will always be assigned to this.
o Data type: Data type is the type of the variable to which the pointer is intended to point. It also includes the modifier
like signed int, long, etc).

C Function Pointer:
As we know that we can create a pointer of any data type such as int, char, float, we can also create a pointer pointing
to a function. The code of a function always resides in memory, which means that the function has some address.
We can get the address of memory by using the function pointer.

Let's see a simple example.

1. #include <stdio.h>

2. int main()
3. {
4. printf("Address of main() function is %p",main);
5. return 0;
6. }

The above code prints the address of main() function.

Output
In the above output, we observe that the main() function has some address. Therefore, we conclude that every
function has some address.

Declaration of a function pointer:


Till now, we have seen that the functions have addresses, so we can create pointers that can contain these addresses,
and hence can point them.

Syntax of function pointer

1. return type (*ptr_name)(type1, type2…);

For example:

1. int (*ip) (int);

In the above declaration, *ip is a pointer that points to a function which returns an int value and accepts an integer
value as an argument.

1. float (*fp) (float);

In the above declaration, *fp is a pointer that points to a function that returns a float value and accepts a float value
as an argument.

We can observe that the declaration of a function is similar to the declaration of a function pointer except that the
pointer is preceded by a '*'. So, in the above declaration, fp is declared as a function rather than a pointer.

Till now, we have learnt how to declare the function pointer. Our next step is to assign the address of a function to
the function pointer.

1. float (*fp) (int , int); // Declaration of a function pointer.


2.float func( int , int ); // Declaration of function.
3.fp = func; // Assigning address of func to the fp pointer.

In the above declaration, 'fp' pointer contains the address of the 'func' function.

Note: Declaration of a function is necessary before assigning the address of a function to the function pointer.

Calling a function through a function pointer:


We already know how to call a function in the usual way. Now, we will see how to call a function using a function
pointer.

Suppose we declare a function as given below:

1. float func(int , int); // Declaration of a function.

Calling an above function using a usual way is given below:


1. result = func(a , b); // Calling a function using usual ways.

Calling a function using a function pointer is given below:

1. result = (*fp)( a , b); // Calling a function using function pointer.

Or

1. result = fp(a , b); // Calling a function using function pointer, and indirection operator can be removed.

The effect of calling a function by its name or function pointer is the same. If we are using the function pointer, we
can omit the indirection operator as we did in the second case. Still, we use the indirection operator as it makes it
clear to the user that we are using a function pointer.

Let's understand the function pointer through an example

1. #include <stdio.h>
2. int add(int,int);
3. int main()
4. {
5. int a,b;
6. int (*ip)(int,int);
7. int result;
8. printf("Enter the values of a and b : ");
9. scanf("%d %d",&a,&b);
10. ip=add;
11. result=(*ip)(a,b);
12. printf("Value after addition is : %d",result);
13. return 0;
14. }
15. int add(int a,int b)
16. {
17. int c=a+b;
18. return c;
19. }

Output
File Handling:
So far the operations using the C program are done on a prompt/terminal which is not stored
anywhere. The output is deleted when the program is closed. But in the software industry, most
programs are written to store the information fetched from the program. The use of file
handling is exactly what the situation calls for.
In order to understand why file handling is important, let us look at a few 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 in C
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.
• 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.
C File Operations
C file operations refer to the different possible operations that we can perform on a file in C
such as:
1. Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
2. Opening an existing file – fopen()
3. Reading from file – fscanf() or fgets()
4. Writing to a file – fprintf() or fputs()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()
The highlighted text mentions the C function used to perform the file operations.
Functions for C File Operations

File Pointer in C
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 of File Pointer
FILE* pointer_name;
File Pointer is used in almost all the file operations in C.
Open a File in C
For opening a file in C, the fopen() function is used with the filename or file path along with
the required access modes.
Syntax of fopen()
FILE* fopen(const char *file_name, const char *access_mode);
Parameters
• file_name: name of the file when present in the same directory as the source file.
Otherwise, full path.
• access_mode: Specifies for what operation the file is being opened.
Return Value
• If the file is opened successfully, returns a file pointer to it.
• If the file is not opened, then returns NULL.
File opening modes in C
File opening modes or access modes specify the allowed operations on the file to be opened.
They are passed as an argument to the fopen() function. Some of the commonly used file
access modes are listed below:
Opening
Modes Description

Searches file. If the file is opened successfully fopen( ) loads it into memory
r and sets up a pointer that points to the first character in it. If the file cannot be
opened fopen( ) returns NULL.

Open for reading in binary mode. If the file does not exist, fopen( ) returns
rb
NULL.

Open for writing in text mode. If the file exists, its contents are overwritten. If
w the file doesn’t exist, a new file is created. Returns NULL, if unable to open the
file.

Open for writing in binary mode. If the file exists, its contents are overwritten.
wb
If the file does not exist, it will be created.

Searches file. If the file is opened successfully fopen( ) loads it into memory
and sets up a pointer that points to the last character in it. It opens only in the
a
append mode. If the file doesn’t exist, a new file is created. Returns NULL, if
unable to open the file.

Open for append in binary mode. Data is added to the end of the file. If the file
ab
does not exist, it will be created.

Searches file. It is opened successfully fopen( ) loads it into memory and sets
r+ up a pointer that points to the first character in it. Returns NULL, if unable to
open the file.

Open for both reading and writing in binary mode. If the file does not exist,
rb+
fopen( ) returns NULL.
Opening
Modes Description

Searches file. If the file exists, its contents are overwritten. If the file doesn’t
w+
exist a new file is created. Returns NULL, if unable to open the file.

Open for both reading and writing in binary mode. If the file exists, its contents
wb+
are overwritten. If the file does not exist, it will be created.

Searches file. If the file is opened successfully fopen( ) loads it into memory
and sets up a pointer that points to the last character in it. It opens the file in
a+
both reading and append mode. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open the file.

Open for both reading and appending in binary mode. If the file does not exist,
ab+
it will be created.

As given above, if you want to perform operations on a binary file, then you have to append
‘b’ at the last. For example, instead of “w”, you have to use “wb”, instead of “a+” you have to
use “a+b”.
Example of Opening a File
• C

// C Program to illustrate file opening


#include <stdio.h>
#include <stdlib.h>

int main()
{
// file pointer variable to store the value returned by
// fopen
FILE* fptr;

// opening the file in read mode


fptr = fopen("filename.txt", "r");

// checking if the file is opened successfully


if (fptr == NULL) {
printf("The file is not opened. The program will "
"now exit.");
exit(0);
}
return 0;
}

Output
The file is not opened. The program will now exit.
The file is not opened because it does not exist in the source directory. But the fopen() function
is also capable of creating a file if it does not exist. It is shown below
Create a File in C
The fopen() function can not only open a file but also can create a file if it does not exist
already. For that, we have to use the modes that allow the creation of a file if not found such as
w, w+, wb, wb+, a, a+, ab, and ab+.
FILE *fptr;
fptr = fopen("filename.txt", "w");
Example of Opening a File
• C

// C Program to create a file


#include <stdio.h>
#include <stdlib.h>

int main()
{
// file pointer
FILE* fptr;

// creating file using fopen() access mode "w"


fptr = fopen("file.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.");
}

return 0;
}

Output
The file is created Successfully.
Reading From a File
The file read operation in C can be performed using functions fscanf() or fgets(). Both the
functions performed the same operations as that of scanf and gets but with an additional
parameter, the file pointer. There are also other functions we can use to read from a file. Such
functions are listed below:
Function Description

fscanf() Use formatted string and variable arguments list to take input from a file.

fgets() Input the whole line from the file.

fgetc() Reads a single character from the file.

fgetw() Reads a number from a file.

fread() Reads the specified bytes of data from a binary file.

So, it depends on you if you want to read the file line by line or character by character.
Example:
FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);
The getc() and some other file reading functions return EOF (End Of File) when they reach the
end of the file while reading. EOF indicates the end of the file and its value is implementation-
defined.
Note: One thing to note here is that after reading a particular part of the file, the file pointer
will be automatically moved to the end of the last read character.
Write to a File
The file write operations can be performed by the functions fprintf() and fputs() with
similarities to read operations. C programming also provides some other functions that can be
used to write data to a file such as:
Function Description

Similar to printf(), this function use formatted string and varible arguments list
fprintf()
to print output to the file.

fputs() Prints the whole line in the file and a newline at the end.
Function Description

fputc() Prints a single character into the file.

fputw() Prints a number to the file.

fwrite() This functions write the specified amount of bytes to the binary file.

Example:
FILE *fptr ;
fptr = fopen(“fileName.txt”, “w”);
fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012);
fputc("a", fptr);
Closing a File
The fclose() function is used to close the file. After successful file operations, you must always
close a file to remove it from the memory.
Syntax of fclose()
fclose(file_pointer);
where the file_pointer is the pointer to the opened file.
Example:
FILE *fptr ;
fptr= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(fptr);
Examples of File Handing in C
Example 1: Program to Create a File, Write in it, And Close the File
• C

// C program to Open a File,


// Write in it, And Close the File
#include <stdio.h>
#include <string.h>

int main()
{

// Declare the file pointer


FILE* filePointer;

// Get the data to be written in file


char dataToBeWritten[50] = "GeeksforGeeks-A Computer "
"Science Portal for Geeks";
// Open the existing file GfgTest.c using fopen()
// in write mode using "w" attribute
filePointer = fopen("GfgTest.c", "w");

// Check if this filePointer is null


// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.c file failed to open.");
}
else {

printf("The file is now opened.\n");

// Write the dataToBeWritten into the file


if (strlen(dataToBeWritten) > 0) {

// writing in the file using fputs()


fputs(dataToBeWritten, filePointer);
fputs("\n", filePointer);
}

// Closing the file using fclose()


fclose(filePointer);

printf("Data successfully written in file "


"GfgTest.c\n");
printf("The file is now closed.");
}

return 0;
}

Output
The file is now opened.
Data successfully written in file GfgTest.c
The file is now closed.
This program will create a file named GfgTest.c in the same directory as the source file which
will contain the following text: “GeeksforGeeks-A Computer Science Portal for Geeks”.

Example 2: Program to Open a File, Read from it, And Close the File
• C
// C program to Open a File,
// Read from it, And Close the File
#include <stdio.h>
#include <string.h>

int main()
{

// Declare the file pointer


FILE* filePointer;

// Declare the variable for the data to be read from


// file
char dataToBeRead[50];

// Open the existing file GfgTest.c using fopen()


// in read mode using "r" attribute
filePointer = fopen("GfgTest.c", "r");

// Check if this filePointer is null


// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.c file failed to open.");
}
else {

printf("The file is now opened.\n");

// Read the dataToBeRead from the file


// using fgets() method
while (fgets(dataToBeRead, 50, filePointer)
!= NULL) {

// Print the dataToBeRead


printf("%s", dataToBeRead);
}

// Closing the file using fclose()


fclose(filePointer);

printf(
"Data successfully read from file GfgTest.c\n");
printf("The file is now closed.");
}
return 0;
}

Output
The file is now opened.
GeeksforGeeks-A Computer Science Portal for Geeks
Data successfully read from file GfgTest.c
The file is now closed.
This program reads the text from the file named GfgTest.c which we created in the previous
example and prints it in the console.

You might also like