0% found this document useful (0 votes)
13 views107 pages

Unit - 5

The document provides an overview of functions and file handling in C programming, explaining the structure, advantages, and types of functions. It details how to declare, define, and call functions, as well as the concepts of call by value and call by reference. Additionally, it discusses predefined and user-defined functions, along with examples to illustrate their usage.

Uploaded by

ramcharan5487f
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views107 pages

Unit - 5

The document provides an overview of functions and file handling in C programming, explaining the structure, advantages, and types of functions. It details how to declare, define, and call functions, as well as the concepts of call by value and call by reference. Additionally, it discusses predefined and user-defined functions, along with examples to illustrate their usage.

Uploaded by

ramcharan5487f
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 107

UNIT V

Functions & File Handling


FUNCTIONS
⚫ A function is a group of statements that together perform a task.
Every C program has at least one function, which is main().
⚫ In C, we can divide a large program into the basic building blocks
known as function.
⚫ A function is a block of code which only runs when it is called.
⚫ You can pass data, known as parameters, into a function.
⚫ Functions are used to perform certain actions, and they are
important for reusing code: Define the code once, and use it many
times.
⚫ 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.
Advantage of functions in C:
⚫ By using functions, we can avoid rewriting same logic/code again
and again in a program.
⚫ We can call C functions any number of times in a program and
from any place in a program.
⚫ We can track a large C program easily
when it is divided into
multiple functions.
⚫ Reusability is the main achievement of C functions.
⚫ However, Function calling is always a overhead in a C program.
Functions in C
⚫A function is a set of statements that take inputs, do some specific
computation and produces output.
⚫The idea is to put some commonly or repeatedly done task together
and make a function so that instead of writing the same code
again and again for different inputs, we can call the function.
⚫The general form of a function is:
return_type function_name([ arg1_type arg1_name, ... ]) { code }

Example:
Below is a simple C/C++ program to demonstrate functions.
/* An example function that takes two parameters 'x' and 'y‘ as input
and returns max of two input numbers*/
int max(int x, int y)
{
if (x > y) return x; else
return y;
}
/* main function that doesn't receive any parameter and
returns integer */
int main(void)
{
int a = 10, b = 20;

// Calling above function to find max of 'a' and 'b' int m = max(a, b);

printf("m is %d", m); return 0;


}
Function Aspects:
⚫There are three aspects of a C function.
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.
⚫Putting parameter names in function declaration is optional in the
function but it is necessary to put them in
definition. Below is the an example of function
declaration,
(parameter names are notdeclarations.
there in below
declarations)
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. 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 from the function.
Defining a Function:
⚫The general form of a function definition in C programming
language is as follows.
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.
⚫ A function is a block of code that performs a specific task.
⚫ C allows you to define functions according to your need. These
functions are known as user-defined functions. For example: Max
is a name of the function defined by the user.
Example:
⚫Given below is the source code for a function called max(). This
function takes two parameters num1 and num2 and returns the
maximum value between the two.
/* function returning the max between two numbers */ int max(int
num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2) result = num1;
else
result = num2; return result;
}
Function Declarations
⚫A function declaration tells the compiler about a function name and
how to call the function. The actual body of the function can
be defined separately.
⚫A function declaration has the following parts
return_type function_name( parameter list );
⚫For the above defined function max(), the function declaration is as
follows
int max(int num1, int num2);
⚫Parameter names are not important in function
declaration only
their type is required, so the following is also a valid declaration.
int max(int, int);
⚫ Function declaration is required when you define a function in one
source file and you call that function in another file. In such case,
you should declare the function at the top of the file calling the
function.
Calling a Function
⚫ While creating a C function, you give a definition of what the
function has to do. To use a function, you will have to call that
function to perform the defined task.
⚫ 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. For example
#include<stdio.h> #include<math.h>
/* function declaration */
void max(int num1, int num2); int main
() {
/* local variable definition */
int a = 100; int b = 200;
/* calling a function to get max value */
max(a,b); return 0;
}
/* function returning the max between two numbers
*/ void max(int num1, int num2)
{
if(num1>num2)
{
printf("%d is big",num1);
}
else
{
printf("%d is big",num2);
}
}
Output: 200 is big
#include<stdio.h> #include<math.h>
/* function declaration */
int max(int num1, int num2); int main ()
{
/* local variable definition */
int a = 100; int b = 200;
/* calling a function to get max value */
printf("%d is max",max(a,b)); return 0;
}
/* function returning the max between two numbers
*/ int max(int num1, int num2)
{
if(num1>num2)
{
return num1;
}
else
{
return num2;
}
}
Output: 200 is max
⚫ Functions are broadly classified into two types, which are
as
follows −
⚫ Predefined functions
⚫ User defined functions
Predefined (or) library functions
⚫ These functions are already defined in the system libraries.
⚫ Programmer will reuse the already presentcode in
the system
libraries to write error free code.
⚫ But to use the library functions, user must be aware of syntax of the
function.
Example −
⚫ sqrt() function is available in math.h library and its usage is
y= sqrt (x)
x number must be positive eg: y = sqrt (25)
then ‘y’ = 5
⚫printf ( ) present in stdio.h library.
⚫clrscr ( ) present in conio.h library.
Example
⚫Given below is the C program on predefined function sqrt, printf,
conio −
#include<stdio.h> #include<conio.h> #include<math.h> main ( ){
int x,y; clrscr ( );
printf ("enter a positive number");
scanf (" %d", &x) y = sqrt(x);
printf("squareroot = %d", y);
getch();
}
Output
Enter a positive number 25 Squareroot = 5
⚫Consider some more predefined functions −
⚫cbrt(x) :cube root of x
⚫ log(x) : natural logarithm of x base e
⚫ ceils(x): round x to smaller integer not less than x
⚫ pow(x,y): x raised to power y………
Example
⚫ Following is a C program using the predefined functions
− #include<stdio.h>
#include<math.h>
main ( ){
int x,y,z,n,k,p,r,q;
printf ("enter x and n values:"); scanf (" %d%d", &x,&n)
y=cbrt(x);
z=exp(x);
k=log(x); p=ceil(x); q=pow(x,n);
printf("cuberoot = %d", y);
printf("exponent value = %d",z);
printf("logarithmic value = %d",
k); printf("ceil value = %d", p);
printf("power = %d", q);
getch();
}
Output
enter x and n values:9 2
cuberoot = 2
exponent value = 8103 logarithmic value = 2 ceil value = 9
power = 81
Few Points to Note regarding functions in C:
1)main() in C program is also a function.
2)Each C program must have at least one function, which is main().
3)There is no limit on number of functions; A C program can have
any number of functions.
4)A function can call itself and it is known as “Recursion“.
⚫ C Functions Terminologies that you must remember
return type: Data type of returned value. It can be void also, in
such case function doesn’t return any value.
⚫ Note: for example, if function return type is char, then function
should return a value of char type and while calling this function
the main() function should have a variable of char data type to store
the returned value.
Create a Function
⚫ To create (often referred to as declare) your own function, specify
the name of the function, followed by parentheses () and curly
brackets {}:
Syntax
void myFunction() {
// code to be executed
}
⚫ myFunction() is the name of the function
⚫ void means that the function does not have a return value.
⚫ Inside the function (the body), add code that
defines what the function should do.
Call a Function
⚫ Declared functions are not executed immediately. They are "saved
for later use", and will be executed when they are called.
⚫ To call a function, write the function's
name followed by two
parentheses () and a semicolon ;
⚫ In the following example, myFunction() is used to print a text (the
action), when it is called:
Example
Inside main, call myFunction():
// Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"


⚫A function can be called multiple
times. void myFunction() {
printf("I just got executed!");
}
int main() { myFunction();
myFunction(); myFunction();
return 0;
}
// I just got executed!
// I just got executed!
// I just got executed!
Function Arguments
⚫In C, a function specifies the modes of parameter passing to it.
⚫There are two ways to specify function calls: call by value and call
by reference in C.
⚫In call by value the function parameters gets the copy of actual
parameters which means changes made in function parameters did
not reflect in actual parameters.
⚫In call by reference function parameter gets reference of actual
parameter which means they points to similar storage space and
changes made in function parameters will reflect in actual
parameters.
Introduction
⚫Suppose you have a file and someone want the information present
in file.
⚫So to protect from alteration in original file you give a copy of your
file to them and if you want the changes done by someone else
in your file then you have to give them your original file.
⚫In C also if we want the changes done by function to reflect in the
original parameters also then we passed the parameter by
reference and if we don't want the changes in original parameter
then we passes the parameters by value.
Call by Value in C
⚫Calling a function by value will cause the program to copy the
contents of an object passed into a function.
⚫To implement this in C, a function declaration has the following
form:
⚫[return type] functionName([type][parameter name],...).
⚫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 can not 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.
#include <stdio.h>
void swap(int x, int y)
{
int temp = x;
x = y;
y = temp;
}
int main()
{
int x = 10;
int y = 11;
printf("Values before swap: x = %d, y = %d\n", x,y);
swap(x,y);
printf("Values after swap: x = %d, y = %d", x,y);
}
Output:
Values before swap: x = 10, y = 11 Values after swap:
x = 10, y = 11
⚫ We can observe that even when we change the content of x and y in
the scope of the swap function, these changes does not
reflect on x and y variables defined in the scope of main.
⚫ This is because we call swap() by value and it will get separate
memory for x and y so the changes made in swap() will not reflect
in main().
Call by Reference in C
⚫ Calling a function by reference will give function parameter the
address of original parameter due to which they will point to same
memory location.
⚫ Any changes made in function parameter will also reflect in
original parameters.
⚫ To implement this in C, a function declaration has the following
form:
⚫ [return type] functionName([type]* [parameter name],...).
⚫ 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.
#include <stdio.h>
void swap(int *x, int *y){ int temp = *x;
*x = *y;
*y = temp;
}
int main(){ int x = 10; int y = 11;
printf("Values before swap: x = %d, y = %d\n", x,y);
swap(&x,&y);
printf("Values after swap: x = %d, y = %d", x,y);
}
Output:
Values before swap: x = 10, y = 11 Values after swap: x = 11, y = 10
⚫We can observe in function parameters instead of using int x, int y
we used int *x, int *y and in function call instead of giving x, y
we give &x, &y this methodology is call by reference as we used
pointers as function parameter which will get original parameters
address instead of their value.
⚫& operator is used to give address of the variables and * is used to
access the memory location that pointer is pointing.
⚫As the function variable is pointing to same memory location as
original parameter the changes made in swap() reflect in
main() which we could see in the above output.
User defined functions
⚫A function is a block of code that can be used to perform a specific
action.
⚫C allows programmers to write their own functions, also known
as user-defined functions.
⚫A user-defined function can perform specific
actions defined by
users based on given inputs and deliver the required output.
⚫A user-defined function has three main components that
are function declarations, function definition and function call.
⚫Further functions can be called by call by value or call by
reference.
⚫Functions need to be written once and can be called as many times
as required inside the program, which increases
reusability in code and makes code more readable and easy
to test, debug, and maintain the code.
Calling User-defined Functions
⚫To transfer the control to a user-defined function, we need to call
the function.
⚫A function can be called using a function name followed by round
brackets. We can pass arguments to function inside brackets if any.
⚫ As shown in the figure, when a function call is made (sum(10,5) in
this case) the control of the program shift from the calling
function (main()) to the called function (sum()).
⚫ The control reaches back to the calling function when the called
function terminates.
⚫ If the called function has any return value that it gets returned and
can be accessed in the calling function like in the above figure, the
sum of two integers is stored in a variable ans in function main().
Example of User-defined function
⚫ Here is an example to calculate area of Rectangle . We have created
user-defined function getRectangleArea() to perform this task.
Types of User-defined Functions in C
⚫Now that we understand how user-defined functions are written in
C let us understand four different approaches which can be
used to define and use a function in our code.
⚫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.
⚫Function with no arguments and no return values
⚫Function with no arguments and one return value
⚫Function with arguments and no return values
⚫Function with arguments and one return value
Function with no arguments and no return values
⚫Function with no argument means the called function does not
receive any data from calling function.
⚫Function with no return value means calling function does not
receive any data from the called function. So there is no data
transfer between calling and called function.
function declaration:
void function();
function call: function(); function definition: void function()
{
statements;
}
In the above program, area(); function calculates area and no
arguments are passed to this function. The return type of this function
is void and hence return nothing.
Function with no arguments and one return value
⚫As said earlier function with no arguments means called function
does not receive any data from calling function and function
with one return value means one result will be sent back to the
caller from the function.
function declaration:
int function ( );
function call: function ( ); function definition:
int function( )
{
statements; return a;
}
In this function int area(); no arguments are passed but it returns an
integer value square_area.
Function with arguments and no return values
⚫Here function will accept data from the calling function as there are
arguments, however, since there is no return type nothing will be
returned to the program. So it’s a one-way type
calling communication.
function declaration:
void function ( int );
function call:
function( a ); function
definition:
void function( int a )
{
statements;
}
In this function, the integer value entered by the user in square_side
variable is passed to area(); .The called function has void as a return
type as a result, it does not return value.
Function with arguments and one return value
⚫Function with arguments and one return value means both the
calling function and called function will receive data from
each other. It’s like a dual communication.
function declaration: int function ( int ); function call:
function ( a );
function definition:
int function( int a )
{
statements;
return a;
}
C Recursion
⚫A function that calls itself is known as a recursive function. And,
this technique is known as recursion.
⚫This technique provides a way to break
complicated problems
down into simple problems which are easier to solve.
⚫Recursion involves several numbers of recursive calls. However, it
is important to impose a termination condition of recursion.
⚫Recursion may be a bit difficult to
understand. The best way to figure out how it works is to
experiment with it.
⚫How recursion
works? void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
⚫ The recursion continues until some condition is met to prevent it.
⚫ To prevent infinite recursion, if...else statement (or similar
approach) can be used where one branch makes the recursive call,
and other doesn't.
Recursion Example
⚫ Adding two numbers together is easy to do, but adding a range of
numbers is more complicated.
⚫ In the following example, recursion is used to add a range of
numbers together by breaking it down into the simple task
of adding two numbers:
int sum(int k);
int main() {
int result = sum(10); printf("%d", result); return 0; }
int sum(int k) { if (k > 0)
{
return k + sum(k - 1);
}
else
{
return 0;
}
}
⚫When the sum() function is called, it adds parameter k to the sum of
all numbers smaller than k and returns the result. When k
becomes 0, the function just returns 0. When running, the
program follows these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
.
.
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
⚫Since the function does not call itself
when k is 0, the program
stops there and returns the result.
⚫Example: Sum of Natural Numbers Using Recursion #include
<stdio.h>
int sum(int n); int main() {
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number); result = sum(number);
printf("sum = %d", result); return 0;
}
int sum(int num)
{
if (num!=0)
return num + sum(num-1); // sum() function calls
itself
else
return num; }
⚫ Initially, the sum() is called from the main() function with number
passed as an argument.
⚫ Suppose, the value of n inside sum() is 3 initially. During the next
function call, 2 is passed to the sum() function. This process
continues until n is equal to 0.
⚫ When n is equal to 0, the if condition fails and the else part is
executed returning the sum of integers ultimately to the main()
function.
Passing Arrays as Function Arguments in C
⚫If you want to pass a single-dimension array as an argument in a
function.
⚫You would have to declare a formal parameter in one of following
three ways and all three declaration methods produce
similar results.
⚫Each method tells the compiler that an integer pointer is going to be
received. you can pass multi-dimensional arrays
Similarly, formal as
parameters.
Way-1
Formal parameters as a pointer −
void myFunction(int *param) {
.
.}
Way-2
Formal parameters as a sized array −
void myFunction(int param[10]) {
.
.
.
}
Way-3
Formal parameters as an unsized array −
void myFunction(int param[]) {
.
.
.}
Example
⚫Now, consider the following function, which takes an array as an
argument along with another argument and based on the
passed arguments, it returns the average of the numbers passed
through the array as follows.
#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size); int main () {
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50}; double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf( "Average value is: %f ", avg );
return 0;
}
double getAverage(int arr[], int size) {
int i;
double avg;
double sum = 0;
for (i = 0; i < size; ++i)
{ sum=sum+arr[i];
}
avg = sum / size; return avg;
}
⚫ When the above code is compiled together and executed, it
produces the following result.
Average value is: 214.400000
⚫ As you can see, the length of the array doesn't matter as far as the
function is concerned because C performs no bounds checking for
formal parameters.
Scope and Lifetime of Variables
⚫ Variables in C Programming are a container to hold the value of a
data type.
⚫ They help the compiler to create memory
space for the type of
Variable. Each variable has a unique name.
⚫ The variable name is similar to the name of a person.
⚫ Each individual has some name to recognize him.
⚫ The only purpose of the variable name is to make it
human- readable; the compiler does not use a variable name.
⚫ The variables in C programming have a scope
that defines their
accessibility and lifetime.
What is the Scope and Lifetime of a Variable
⚫The scope is the variable region in which it can be used. Beyond
that area, you cannot use a variable.
⚫The local and global are two scopes for C variables. The local scope
is limited to the code or function in which the variable is
declared.
⚫Global scope is the entire program. Global variables can be used
anywhere throughout the program.
⚫Lifetime is the life or alive state of a variable in the memory.
⚫It is the time for which a variable can hold its memory. The lifetime
of a variable is static and automatic. The static lifetime
variable remains active till the end of the program.
⚫An automatic lifetime variable or global variable activates when
they are called else they vanish when the function executes.
Types of Variables in C programming
⚫The variables in C programming can be divided into different types
based on their scope and storage classes.
⚫Types of Variables on the Basis of Scope
⚫Local Variables
Types of Variables on the Basis of Scope
⚫The variable that is declared in a function or code is called a local
variable.
⚫The scope of Local variables is within the defined function only.
⚫You cannot use a local variable outside the function (in which it is
declared).
#include <stdio.h> void person()
{
// Local Variables of the function
int age = 20;
float height = 5.6;
printf("age is %d \n", age);
printf("height is %f", height);
}
int main()
{
person();
return 0; }
Global Variables
⚫The scope of the global variable is the entire program. They are not
defined inside any function and can be used in any function.

#include <stdio.h>
// Declaring global variable
int a = 23;
void function1()
{
// Function using global variable a printf("The number is %d \n", a);
}
void function2()
{
// Function using global variable a
printf("The number is %d \n", a);
}
int main() {
// Calling functions function1();
function2();
return 0; }
Output:
The number is 23
The number is 23
Static Variable
⚫The static variable is defined using the static keyword.
⚫Its scope depends on the area of its declaration.
⚫If a static variable is defined within a function, it is a local variable.
If declared outside the function, its scope is global.
⚫A static variable statically allocated memory to the variable and its
lifetime is throughout the program. It holds its value whenever
a program is called.
⚫The default value of the static variable is 0.

#include <stdio.h>
void value()
{
int a = 10; // Local variable
static int b = 20; // Static variable
a = a + 10;
b = b + 10;
printf("The value of local variable: %d \n", a);
printf("The value of Static variable: %d \n", b);
}
int main() { value();
printf("Calling function 2nd time \n");
value();
printf("Calling function 3rd time \n"); value();
return 0; }
Output:
The value of local variable: 20 The value of Static variable: 30
Calling function 2nd time
The value of local variable: 20 The value of Static variable: 40
Calling function 3rd time
The value of local variable: 20 The value of Static variable: 50 Auto
Variable
⚫All variables declared in C programming are automatic by default.
⚫You can use the auto keyword to declare the automatic variable.
⚫ An automatic variable is a local variable whose lifetime is within
the code only.
⚫ Its default value is garbage.

#include <stdio.h> void value() {


int a = 10; //local variable
auto int b = 20; //automatic variable printf("The value of local
variable: %d \n", a);
printf("The value of automatic variable: %d \n", b); }
int main() {
value(); //calling function
return 0; }
Output:
The value of local variable:
10
The value of automatic variable: 20
File Handling in C
⚫File handling in C refers to the task of storing data in the form of
input or output produced by running C programs in data
files, namely, a text file or a binary file.
What is a File in C?
⚫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).
⚫The content available on a file isn’t volatile like the compiler
memory in C.
⚫ But the program can perform various operations, such as creating,
opening, reading a file, or even manipulating the data present inside
the file. This process is known as file handling in C.
Why Do We Need File Handling in C?
⚫ There are times when the output generated out of a program after its
compilation and running do not serve our intended purpose.
⚫ In such cases, we might want to check the program’s output various
times.
⚫ Now, compiling and running the very same program multiple times
becomes a tedious task for any programmer. It is exactly where
file handling becomes useful.
⚫ Let us look at a few reasons why file handling makes programming
easier for all:
⚫ Reusability: File handling allows us to preserve the
information/data generated after we run the program.
⚫ Saves Time: Some programs might require a large amount of input
from their users. In such cases, file handling allows you to easily
access a part of a code using individual commands.
⚫ Commendable storage capacity: When storing data in files, you
can leave behind the worry of storing all the info in bulk in any
program.
⚫ Portability: The contents available in any file can be transferred to
another one without any data loss in the computer system. This
saves a lot of effort and minimises the risk of flawed coding.
Types of Files in a C Program
⚫ When referring to file handling, we refer to files in the form of data
files. Now, these data files are available in 2 distinct forms in the
C language, namely:
⚫ Text Files
⚫ Binary Files
Text Files
⚫The text files are the most basic/simplest types of files that a user
can create in a C program.
⚫We create the text files using an extension .txt with the help of a
simple text editor. In general, we can use notepads for the creation
of .txt files. These files store info internally in ASCII character
format, but when we open these files, the content/text opens in a
human-readable form.
⚫Text files are, thus, very easy to access as well as use. But there’s
one major disadvantage; it lacks security. Since a .txt file can
be accessed easily, information isn’t very secure in it. Added to
this, text files consume a very large space in storage.
⚫To solve these problems, we have a different type of file in C
programs, known as binary files
Binary Files
⚫The binary files store info and data in the binary format of 0’s and
1’s (the binary number system).
⚫Thus, the files occupy comparatively lesser space in the storage. In
simpler words, the binary files store data and info the same
way a computer holds the info in its memory. Thus, it can be
accessed very easily as compared to a text file.
⚫The binary files are created with the extension .bin in a program,
and it overcomes the drawback of the text files in a program since
humans can’t read it; only machines can.
⚫Thus, the information becomes much more secure. Thus, binary
files are safest in terms of storing data files in a C program.
⚫ 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.
⚫ Creation of the new file
⚫ Opening an existing file
⚫ Reading from the file
⚫ Writing to the file
⚫ Deleting the file
Functions for file handling
⚫ There are many functions in the C library to open, read, write,
search and close the file. A list of file functions are given below.
No Function Description
.
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file
Opening or create a File: fopen()
⚫Whenever you want to work with a file, the first step is to create a
file. A file is nothing but space in a memory where data is stored.
⚫To create a file in a ‘C’ program following syntax is used,
FILE *fp;
fp = fopen ("file_name", "mode");
⚫In the above syntax, the file is a data structure which is defined in
the standard library. fopen is a standard function which is used
to open a file.
⚫If the file is not present on the system, then it is created and then
opened.
⚫ If a file is already present on the system, then it is directly opened
using this function.
⚫ fp is a file pointer which points to the type file.
⚫ Whenever you open or create a file, you have to specify what you
are going to do with the file.
⚫ A file in ‘C’ programming can be created or
opened for
reading/writing purposes.
⚫ A mode is used to specify whether you want to open a file for any
of the below-given purposes.
⚫ Following are the different types of modes
in ‘C’ programming which can be used while working with a file.
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
File Mode Description
Open a file for reading. If a file is in reading mode, then
r
no data is deleted if a file is already present on a system.
Open a file for writing. If a file is in writing mode, then a
new file is created if a file doesn’t exist at all. If a file is
w already present on a system, then all the data inside the
file is truncated, and it is opened for writing
purposes.
Open a file in append mode. If a file is in append mode,
a then the file is opened. The content within the file
doesn’t change.
r+ open for reading and writing from beginning
w+ open for reading and writing, overwriting a file
a+ open for reading and writing, appending to file
⚫ Inthegiven syntax, the filename and the mode are specified
as
strings hence they must always be enclosed within double quotes.

Example:
#include <stdio.h> int main() {
FILE *fp;
fp= fopen ("data.txt", "w");
}
Output:
⚫ File is created in the same folder where you have saved your code
⚫ You can specify the path where you want to create your
file.
#include <stdio.h> int main() {
FILE *fp;
fp= fopen ("D://data.txt", "w");
}
Closing a File:
⚫The file (both text and binary) should be closed
after reading/writing.
⚫Closing a file is performed using the fclose() function. fclose(fptr);
⚫Here, fptr is a file pointer associated with the file to be closed.
Example:
FILE *fp;
fp = fopen ("data.txt", "r");
fclose (fp);
⚫The fclose function takes a file pointer as an argument. The file
associated with the file pointer is then closed with the help of fclose
function.
⚫ It returns 0 if close was successful and EOF (end of file) if there is
an error has occurred while file closing.
⚫ After closing the file, the same file pointer can also be used with
other files.
⚫ In ‘C’ programming, files are automatically close when the
program is terminated. Closing a file manually by writing
fclose function is a good programming practice.
Writing to a File
⚫ In C, when you write to a file, newline characters ‘\n’ must be
explicitly added.
⚫ The stdio library offers the necessary functions to write to a file:
⚫ fputc(char, file_pointer): It writes a character to the file pointed to
by file_pointer.
⚫ fputs(str, file_pointer): It writes a string to the file pointed to by
file_pointer.
⚫ fprintf(file_pointer, str, variable_lists): It prints a string to the file
pointed to by file_pointer. The string can optionally include
format specifiers and a list of variables variable_lists.
⚫ The program below shows how to perform writing to a file:
fputc() Function:
#include <stdio.h> int main()
{
int i;
FILE * fptr;
char str[] = "Guru99 Rocks\n";
fptr = fopen("fputc_test.txt", "w"); // "w" defines "writing
mode"
for (i = 0; str[i] != '\n'; i++) {
/* write to file using fputc() function */
fputc(str[i], fptr);
}
fclose(fptr); return 0;
}
Output:
⚫ The above program writes a single character into the
fputc_test.txt file until it reaches the next line symbol “\n” which
indicates that the sentence was successfully written. The process
is to take each character of the array and write it into the file.
⚫ In the above program, we have created and opened a file called
fputc_test.txt in a write mode and declare our string which will be
written into the file.
⚫ We do a character by character write operation using for loop and
put each character in our file until the “\n” character is encountered
then the file is closed using the fclose function.
fputs () Function:
#include <stdio.h>
int main() {
FILE * fp;
fp = fopen("fputs_test.txt", "w+");
fputs("This is Guru99 Tutorial on fputs,", fp);
fputs("We don't need to use for loop\n", fp);
fputs("Easier than fputc function\n",
fp);
fclose(fp); return (0);
}
Output:
⚫ In theabove program, we have created and opened a file
called
fputs_test.txt in a write mode.
⚫ After that we do a write operation using fputs() function by writing
three different strings
⚫ Then the file is closed using the fclose function.
Reading data from a File
⚫There are three different functions dedicated to reading data from a
file
⚫fgetc(file_pointer): It returns the next character from the file
pointed to by the file pointer. When the end of the file has
been reached, the EOF is sent back.
⚫fgets(buffer, n, file_pointer): It reads n-1 characters from the file
and stores the string in a buffer in which the NULL character
‘\0’ is appended as the last character.
⚫fscanf(file_pointer, conversion_specifiers, variable_adresses): It
is used to parse and analyze data. It reads characters from the
file and assigns the input to a list of variable pointers
variable_adresses using conversion specifiers. Keep in mind that
as with scanf, fscanf stops reading a string when space or newline is
encountered.
Interactive File Read and Write with getc and putc
⚫These are the simplest file operations. getc stands for get character,
and putc stands for put character. These two functions are
used to handle only a single character at a time.
⚫Following program demonstrates the file handling functions in ‘C’
programming:
#include <stdio.h> int main() {
FILE * fp;
char c;
printf("File Handling\n");
//open a file
fp = fopen("demo.txt", "w");
//writing operation
while ((c = getchar()) != ‘\n’) {
fputc(c, fp); }
//close file
fclose(fp);
printf("Data Entered:\n");
//reading
fp = fopen("demo.txt", "r");
while ((c = getc(fp)) != EOF) {
printf("%c", c);
}
fclose(fp);
return 0;
}
Output:
⚫ In the above program we have created and opened a file called
demo in a write mode.
⚫ After a write operation is performed, then the file is closed using
the fclose function.
⚫ We have again opened a file which now contains data in a reading
mode. A while loop will execute until the eof is found. Once the
end of file is found the operation will be terminated and data will be
displayed using printf function.
⚫ After performing a reading operation file is again closed using the
fclose function.
Summary
⚫A file is a space in a memory where data is stored.
⚫‘C’ programming provides various functions to deal with a file.
⚫A mechanism of manipulating with the files is
called as file
management.
⚫A file must be opened before performing operations on it.
⚫A file can be opened in a read, write or an append mode.
⚫getc and putc functions are used to read
and write a single character.
⚫The function fscanf() permits to read and parse data from a file
⚫We can read (using the getc function) an entire file by looping to
cover all the file until the EOF is encountered
⚫We can write to a file after creating its name, by using the
function fprintf() and it must have the newline character at
THANK
YOU

You might also like