0% found this document useful (0 votes)
2 views41 pages

Unit4- C

Unit 04 focuses on decomposition using functions in programming, covering library functions, user-defined functions, function calls, and variable scope. It emphasizes the importance of functions for code reusability, readability, and error reduction. The unit also includes examples and exercises related to string and mathematical library functions in C programming.
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)
2 views41 pages

Unit4- C

Unit 04 focuses on decomposition using functions in programming, covering library functions, user-defined functions, function calls, and variable scope. It emphasizes the importance of functions for code reusability, readability, and error reduction. The unit also includes examples and exercises related to string and mathematical library functions in C programming.
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

UNIT 04: DECOMPOSITION USING FUNCTION

 Unit 04-01: Function types: Library function (math, string)

 Unit 04-02:user defined functions : Function definition, function declaration

 Unit 04-03: arguments

 Unit 04-04: function calls and returns

 Unit 04-05: scope rules and lifetime of variables


LEARNING OBJECTIVES
After successful completion of this unit, you will be able to
 Develop program using functions
 Indentify logical and syntactical errors

04-01: FUNCTION TYPES: LIBRARY FUNCTION (MATH, STRING)

INTRODUCTION:

Fig. Function Introduction

We, humans, depend on many people, knowingly or unknowingly, for many different
[Link] being intelligent, we cannot complete all life's tasks independently. For example, A
personmay call a mechanic to repair his car, employ a gardener to prune his lawn, and depend on a
grocerystore to deliver foodstuff monthly. Similarly, A computer program (other than the simple
programsstudied in previous chapters) faces an analogous situation; it cannot complete every task by
[Link], it requires program-like entities known as functions to complete the task. This
sectiondiscusses the use of functions in a programming language.

A function can be defined as a set of statements that collectively performs some task. It
takesinputs, performs the tasks, and returns the results. A function must be declared first before
callingin the program. We can call the function several times. As we have already seen, using a
functionis similar to employing a person to carry out an assigned task. Getting along with the person
issometimes easy and challenging. For example, consider a routine operation you conduct, such
asrepairing your motorcycle every two months in the same manner as before. When the time
comes,you visit the service center and request its service. The individual does not need to
provideinstructions because the mechanic is experienced in his work. When the task is done, you do

CCCXXX: Book TitlePage 2


notneed to be informed. You expect that the mechanic will perform the standard maintenance on
thebike, and that will be all. A simple C function works identically as the mechanic. A function is
alsoknown as a method, procedure, or routine.

Advantages of using Functions

The advantages of using Functions are as follows:


1. Code reusability (Avoids repetition of codes)
2. Increases program readability
3. Divides large complex problems into simple ones.
4. Reduces the chance of errors.

TYPES OF FUNCTIONS:

Fig Types of function

The two kinds of functions provided in C programming are user-defined and library
functions(shown in Fig.4.14). Library functions are built-in functions that perform a specific task
and arepresent in standard libraries. The header files are used to include these standard
[Link] are not required to write library functions. A C program uses a variety of built-
infunctions that are present in the standard C library. For example, printf() and scanf()are defined in
the stdio.h library, while cbrt() for computing the cube of a number and pow() forthe computing
power of a number is defined in math.h library. User-defined functions arerequired to be written by

CCCXXX: Book TitlePage 3


the programmer while creating the code. These functions need to bedeclared and defined by the
programmer itself.

Fig. Types of functions

LIBRARY FUNCTION:

[Link]

C Standard library functions or simply C Library functions are inbuilt functions in C


[Link] prototype and data definitions of these functions are present in their respective
header files. To use these functions we need to include the header file in our program. For example,If
you want to use the printf() function, the header file <stdio.h> should be included.

CCCXXX: Book TitlePage 4


#include<stdio.h>
intmain()
{
printf("Catch me if you can.");
}

If you try to use printf() without including the stdio.h header file, you will get an error.

Advantages of Using C library functions:


1. They work
One of the most important reasons you should use library functions is simply because they work.
These functions have gone through multiple rigorous testing and are easy to use.

2. The functions are optimized for performance


Since, the functions are "standard library" functions, a dedicated group of developers constantly make
them better. In the process, they are able to create the most efficient code optimized for maximum
performance.

3. It saves considerable development time


Since the general functions like printing to a screen, calculating the square root, and many more are
already written. You shouldn't worry about creating them once again.

4. The functions are portable


With ever-changing real-world needs, your application is expected to work every time, everywhere.
And, these library functions help you in that they do the same thing on every computer.

Example: Square root using sqrt() function

Suppose, you want to find the square root of a number.

To compute the square root of a number, you can use the sqrt() library function. The function is
defined in the math.h header file.
#include<stdio.h>
#include<math.h>
intmain()
{
float num, root;
printf("Enter a number: ");
scanf("%f", &num);

CCCXXX: Book TitlePage 5


// Computes the square root of num and stores in root.
root = sqrt(num);

printf("Square root of %.2f = %.2f", num, root);


return0;
}

When you run the program, the output will be:

Enter a number: 12
Square root of 12.00 = 3.46

String Library functions:


The predefined functions which are designed to handle strings are available in the library “string.h”.
They are −

 strlen ()
 strcmp ()
 strcpy ()
 strncmp ()
 strncpy ()
 strrev ()
 strcat ()
 strstr ()
 strncat ()

The strlen () function


It returns the number of characters in a string.

Syntax
int strlen (string name)

Example
#include <string.h>
main (){
char a[30] = “Hello”;
int l;

CCCXXX: Book TitlePage 6


l = strlen (a);
printf (“length of the string = %d”, l);
getch ();
}

Output
length of the string = 5

Library Functions in Different Header Files:

C Header Files Description

<assert.h> Program assertion functions

<ctype.h> Character type functions

<locale.h> Localization functions

<math.h> Mathematics functions

<setjmp.h> Jump functions

<signal.h> Signal handling functions

<stdarg.h> Variable arguments handling functions

<stdio.h> Standard Input/Output functions

<stdlib.h> Standard Utility functions

CCCXXX: Book TitlePage 7


<string.h> String handling functions

<time.h> Date time functions

Some of the important header file functions are as follows −

 stdio.h − It is a standard i/o header file in which Input/output functions are declared
 conio.h − This is a console input/output header file.
 string.h − All string related functions are in this header file.
 stdlib.h − This file contains common functions which are used in the C programs.
 math.h − All functions related to mathematics are in this header file.
 time.h − This file contains time and clock related [Link] functions in stdio.h

SOLVED PROBLEMS 01

1) Copy string using library function

2) #include<string.h>
3) main (){
4) char a[50], b[50];
5) printf("enter a source string");
6) scanf("%s", a);
7) printf("enter destination string");
8) scanf("%s",b);
9) strcpy(b,a);
10) printf("copied string = %s",b);
11) getch();
12) }

OUTPUT:

Enter a source string : Hello


Copied string = Hello

2) Combine two srings using library function

CCCXXX: Book TitlePage 8


#include<string.h>
main(){
char a[50]="Hello";
char b[20]="Good Morning";
clrscr();
strcat(a,b);
printf("concatenated string = %s", a);
getch();
}

OUTPUT:

Concatenated string = Hello Good Morning

3) Compare two strings

#include<stdio.h>
#include<string.h>
int main (){
char a[50], b [50];
int d;
printf("Enter 2 strings:");
scanf("%s %s",a,b);
d =strcmp(a,b);
if(d==0){
printf("%s is (alphabetically) equal to %s",a,b);
}elseif(d>0){
printf("%s is (alphabetically) greater than %s",a,b);
}elseif(d<0){
printf("%s is (alphabetically) less than %s",a,b);
}
}

OUTPUT:

Enter 2 strings:apple ball

apple is (alphabetically) less than ball

CCCXXX: Book TitlePage 9


4) Write code to find out square root

#include <stdio.h>
#include <math.h>

int main ()
{

printf("Square root of %lf is %lf\n", 225.0, sqrt(225.0) );


printf("Square root of %lf is %lf\n", 300.0, sqrt(300.0) );

return(0);
}

Output:

Square root of 225.000000 is 15.000000

Square root of 300.000000 is 17.320508

SELF-TEST 01

1) Input/output function prototypes and macros are defined in which header file?
a) conio.h
b) stdlib.h
c) stdio.h
d) dos.h

2) If the two strings are found to be unequal then strcmp returns difference between the
first non-matching pair of characters.
a) True
b) false

3) The prototypes of all standard library string functions are declared in the file string.h.

CCCXXX: Book TitlePage 10


a) True
b) false

SHORT ANSWER QUESTIONS 01

1) In C, when you use a command like getchar() or strcpy() you are actually executing
what?
2) How libraries are included in code

3) How to manipulate strings and characters

4) Write down the C library to perform logarithmic or trigonometric functions

SUMMARY
Functions are sets of statements that take inputs, perform some operations, and
produce results. The operation of a function occurs only when it is called. Rather than
writing the same code for different inputs repeatedly, we can call the function instead of
writing the same code over and over again. Functions accept parameters, which are data. A
function performs a certain action, and it is important for reusing code. Within a function,
there are a number of programming statements enclosed by {}.
There are two types of functions user defined functions and library function.
Functions that are created by the programmer are known as User-Defined functions or
“tailor-made functions”. User-defined functions can be improved and modified according to
the need of the programmer. Whenever we write a function that is case-specific and is not
defined in any header file, we need to declare and define our own functions according to the
syntax.
Library functions are built-in functions that are grouped together and placed in a common
location called [Link] function here performs a specific operation. We can use this library
functions to get the pre-defined [Link] C standard library functions are declared by using many
header files. These library functions are created at the time of designing the [Link] include the
header files in our C program by using #include<filename.h>. Whenever the program is run and
executed, the related files are included in the C program.

KEY WORDS
C, functions, library function, user defined

CCCXXX: Book TitlePage 11


REFERENCES
YOUTUBE VIDEOS

[Link]

[Link]

[Link]

[Link]

[Link]

OER

[Link]

[Link]
BOOKS

1. YashavantKanetkar, “Let Us C” – Seventh Edition, BPB Publications,2007

2. [Link], “Programming in ANSI C”, Tata McGraw Hill, 2002

COURSE COMPANION WEBSITE

[Link]

[Link]

MOOCS

[Link]

[Link]

04-02: USER DEFINED FUNCTIONS: FUNCTION DEFINITION, FUNCTION


DECLARATION
INTRODUCTION:

CCCXXX: Book TitlePage 12


Fig. Introduction

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

Let us look at an example to calculate factorial of a number '5' in C.


#include<stdio.h>
int main() {
int num = 5, i = 0;
int fact = 1;
for(i = 2; i<= num; i++) {
fact *= i;
}
printf("Factorial(5) = %d", fact);
return0;
}

Output

Factorial(5) = 120

CCCXXX: Book TitlePage 13


Now every time we want to calculate the factorial of a different number, we have to
rewrite this complete logic again. Instead, we can write a general logic and use this logic
every time we need to calculate the factorial. This way using functions helps in avoiding
code duplicacy in the program because instead of calculating factorial several times for
different numbers, we can create a function and use it anywhere in the code.

A function is a block of code that can be used to perform a specific action. C allows
users to create their own functions called user-defined functions. A user-defined function
can perform specific actions defined by users based on given inputs and deliver the required
output.

Function divides our program into several independent sub-tasks, making our code
easier to test and debug than one extensive program. The function also helps us avoid
duplication of efforts in our code as we don't have to write the same code again, reducing
the time to write code as explained in the above example.

ELEMENTS OF USER-DEFINED FUNCTION IN C

Functions in the C language have three parts. Let us discuss each of them in detail.

FUNCTION DECLARATION

A function declaration is simply a prototype of our function. Function declaration


contains function name, return type, and parameters but does not contain the body of the
function. Function declaration gives information to the compiler about the user-defined
function that may be used in the later part of the code.

Syntax of function declaration

A function declaration has three main components: return type, function name,
and parameters. The function name is used to identify the function uniquely in code.
Function parameters are included in the declaration to identify the number and types of
inputs that the function accepts.

returnTypefunctionName(type1 parameterName1, type2 parameterName2, ...);

It is not compulsory to mention parameter name in declaration hence we can also use

returnTypefunctionName(type1 , type2, ...);

CCCXXX: Book TitlePage 14


For example, we have a function with the name getRectangleArea to calculate the area of a
rectangle that takes two integer inputs i.e. length and breadth, and returns an integer area as
an output.

Declaration of such a function will be

int getRectangleArea(int , int);

Let us understand each component of a function declaration in detail:

1. Return type: The type of data returned from the function is called return type. A
function may not return any output, in that case, we use void as the return type. In
function declaration return type is mentioned before the name of the function.
2. Function name: Function name is a unique name that can be used to identify our
function in the program. Function names are used to create function calls, which is
why they are unique identifiers for compilers. A valid function name in C can
contain letters, underscore, and digits; the first letter must not be a digit.

For example,

thisIsAfunction(); // valid
_getMaximum(); // valid
!getMinimum(); // invalid, symbols except underscore are not allowed
getPowerOf2(); // valid
2Root(); // invalid function name, must not start with a number

3. Parameter list: Parameters required by the function are also defined inside the
declaration to tell the compiler number of arguments required by the function along
with their data types.
4. Semicolon: Semicolon indicates the termination of a function declaration.

Note: Function declaration is not required if the function is defined before it is called in the
code.

FUNCTION DEFINITION

CCCXXX: Book TitlePage 15


Function definition contains the actual block of code that is executed once the function is
called. A function definition has four components:

1. Return type
2. Function name
3. Function parameters
4. Body of function

CCCXXX: Book TitlePage 16


We have discussed the first three components of a function declaration.

Function body contains a collection of instructions that define what a function does. If the
function returns any value, we use the keyword return to return the value from the function.
For example, return (5*10); returns value 50 of integer data type.

Syntax of function definition

returnTypefunctionName(functionParameters...) {
// function body
}

We can also give default values to function parameters that are assigned to the parameter if
no argument is passed. For example,

int getRectangleArea(int length = 10, int breadth = 5) {


return length * breadth;
}

If getRectangleArea() is called, default values will be assigned to function parameters and


50 will be returned as function output. Here return is used to terminate the function call.
After, the return statement control is transferred to the calling function in the program.

● return_data_type - It defines the data types of value that a function returns


afterexecuting its function body. The default return type is int. It is not necessary for a
function to always return a value. Sometimes, it returns nothing; in such cases, the void
return type is used.
● fun_name - It specifies the function name. It should be a valid identifier.
● arg_list - It is a list of arguments separated by commas received when the function is
called. When a function is called, the value to the arguments is passed. The argument list is
void if no value is passed through the function.
●function_body - It comprises a set of statements that describe the function's functionality.

The control can be passed to the called function in various ways (back to the place
from where the function was called). When the function returns nothing, the control is
transferred when the right curly brace of the function is encountered, or it can be
accomplished by executing the following statement.

CCCXXX: Book TitlePage 17


return;

When the function returns a value, the statement return expression; is used to return
the value to the point from which it has been invoked. Here, an expression could be a value
or an expression.
For example, a function finds the smallest number among two and returns the
smallest number.
int smallest(int var1 , int var2) //function definition
{
int small; if(var1 > var2) small = var2;
else
small = var1;
return small;
}

Here, in the above example, a function smallest is defined, which finds the
smallestnumber among the two numbers. This function takes two arguments of integer type
andreturns an integer value after executing the function’s body. The variable declared inside
the function’s body, that is, small is the local variable. It is identified within the function
smallest in which it is defined.

CCCXXX: Book TitlePage 18


SOLVED PROBLEMS 01

1)

2) #include <stdio.h>

3)

4) // Function declaration

CCCXXX: Book TitlePage 19


5) int myFunction(int, int);

6)

7) // The main method

8) int main() {

9) int result = myFunction(5, 3); // call the function

10) printf("Result is = %d", result);

11) return 0;

12) }

13)

14) // Function definition

15) int myFunction(int x, int y) {

16) return x + y;

2)

#include <stdio.h>

int myFunction(int x, int y) {

return x + y;

int main() {

int result = myFunction(5, 3);

printf("Result is = %d", result);

return 0;

3)

CCCXXX: Book TitlePage 20


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

SELF-TEST 01

1) Choose correct statement about Functions in C Language.

a) A Function is a group of c statements which can be reused any number of times


b) Container of objects of similar types.
c) Every Function may not return a value
d) All the above

2) What are the types of functions in C Language?

a) Library Functions
b) User Defined Functions
c) Both Library and User Defined
d) None of the above

3) What is the limit for number of functions in a C Program?

a) 16
b) 31
c) 32

CCCXXX: Book TitlePage 21


d) No limit

SHORT ANSWER QUESTIONS 01

1) Every C Program should contain which function?

2) What characters are allowed in a C function name identifier?

3)What is the default return value of a C function if not specified explicitly?

SUMMARY

The main difference between Function Declaration and Function Definition in C


Programming is that Function declaration indicates what the function is and Function
Definition indicates what the function does.

C is a high-level general purpose programming language developed by Dennis


Richie. It is the foundation programming language of many other languages such as C++,
Python, Java, PHP, etc. A function is an important concept in C programming. It is a set
of statements that performs a particular task. Rather than writing all the statements inside
the main program, the programmer can create functions and call them within the main
program. It makes the program more readable. After the execution of the function, the
control passes back to the main program. A function has a declaration and definition. The
declaration is a prototype whhile the definition contains the actual implementation.

KEY WORDS
C, user defined,functions,declaration

REFERENCES
YOUTUBE VIDEOS

[Link]

[Link]

[Link]

[Link]

OER

[Link]

CCCXXX: Book TitlePage 22


[Link]
BOOKS

1. YashavantKanetkar, “Let Us C” – Seventh Edition, BPB Publications,2007

2. [Link], “Programming in ANSI C”, Tata McGraw Hill, 2002

COURSE COMPANION WEBSITE

[Link]

[Link]

MOOCS

[Link]

[Link]

04-03: ARGUMENTS
INTRODUCTION:
The values that are declared within a function when the function is called are known as an
argument. Whereas, the variables that are defined when the function is declared are known
as a parameter. Let’s analyze the differences between arguments and parameters.

WHAT IS ARGUMENT?
The values that are declared within a function when the function is called are known as an
argument. These values are considered as the root of the function that needs the arguments
while execution, and it is also known as Actual arguments or Actual Parameters.

WHAT IS PARAMETER?
The variables that are defined when the function is declared are known as a parameter.
These are also known as formal parameters or formal arguments.

DIFFERENCE BETWEEN ARGUMENT AND PARAMETER IN C

[Link]. Argument Parameter

1 The values that are declared within a The variables that are defined when
function when the function is called are the function is declared are known as
known as an argument. parameters.

CCCXXX: Book TitlePage 23


2 These are used in function call These are used in the function header
statements to send value from the of the called function to receive the
calling function to the receiving value from the arguments.
function.

3 During the time of call each argument is Parameters are local variables which
always assigned to the parameter in the are assigned values of the arguments
function definition. when the function is called.

4 They are also known as Actual They are also known as Formal
Parameters. Parameters.

SOLVED PROBLEMS 01

NA

SELF-TEST 01

1) Select a function which is used to write a string to a file ______


a) pits()
b) putc()
c) fputs()
d) fgets()

2) Select a program which get input data from datafile and also send output into
datafile ,it is called _____
a) files
b) file processing
c) data files
d) file handling

CCCXXX: Book TitlePage 24


SHORT ANSWER QUESTIONS 01

1) How to create a record? using example


2) Write code for Employee Record System in C
3) Write C program to store Student records as Structures and Sort them by Name

SUMMARY

A file is a collection of records. This is a loose definition of a file. The term file,
however, is usually reserved for large collections of information stored on devices outside the
computer's internal memory. It usually implies that the records are stored in secondary storage
in the computer's external memory, on tapes or disks. As a result, the ways in which the file
must be organized so that operations on it can be carried out efficiently are dependent on the
characteristics of the secondary storage devices used to implement the file. The basic
operations on a file are to insert and delete records, process or update records, and search for
or retrieve records. These operations are the same as the basic operations on arrays, lists,
trees, list-structures, and more complex lists, which are stored in the computer's internal
memory.

KEY WORDS
C, structure, record,file,field

REFERENCES
YOUTUBE VIDEOS

[Link]

[Link]

[Link]

OER

[Link]

[Link]
BOOKS

3. YashavantKanetkar, “Let Us C” – Seventh Edition, BPB Publications,2007

CCCXXX: Book TitlePage 25


4. [Link], “Programming in ANSI C”, Tata McGraw Hill, 2002

COURSE COMPANION WEBSITE

[Link]

[Link]

MOOCS

[Link]

[Link]

05-04: FILE PROCESSING:

FOPEN(),FCLOSE(),FPRINTF(),FSCANF(),GETC(),PUTC(),CLOSING FILES.

INTRODUCTION:

Fig. Introduction File handling in C

In programming, we may require some specific input data to be generated several numbers of
times. Sometimes, it is not enough to only display the data on the console. The data to be displayed
may be very large, and only a limited amount of data can be displayed on the console, and since the
memory is volatile, it is impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is volatile and can be
accessed every time. Here, comes the need of file handling in C.

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.

o Creation of the new file

CCCXXX: Book TitlePage 26


o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file

Functions for file handling:

Fig. File handling in C

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

CCCXXX: Book TitlePage 27


9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

05-04-01: OPENING FILE: FOPEN()

We must open a file before it can be read, write, or update. The fopen() function is used to
open a file. The syntax of the fopen() is given below.

FILE *fopen( const char * filename, const char * mode );

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. For example, a file name can be
like "c://some_folder/some_file.ext".
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

CCCXXX: Book TitlePage 28


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.

Consider the following example which opens a file in write mode.

1. #include<stdio.h>
2. void main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10. if ( ch == EOF )

CCCXXX: Book TitlePage 29


11. break ;
12. printf("%c",ch) ;
13. }
14. fclose (fp ) ;
15. }

Output

The content of the file will be printed.

05-04-02:CLOSING FILE: FCLOSE()

The fclose() function is used to close a file. The file must be closed after performing all the
operations on it. The syntax of fclose() function is given below:

int fclose( FILE *fp );

#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the character file.
if ( ch == EOF )
break;
printf("%c",ch);

CCCXXX: Book TitlePage 30


}
fclose (fp );
}

05-04-03:C FPRINTF() AND FSCANF()

Writing File : fprintf() function :

The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.

Syntax:

int fprintf(FILE *stream, const char *format [, argument, ...])

Example:

1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("[Link]", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7. }

Reading File : fscanf() function

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.

Syntax:

int fscanf(FILE *stream, const char *format [, argument, ...])

Example:

CCCXXX: Book TitlePage 31


1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("[Link]", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10. }

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We
are going to store id, name and salary of the employee.

1. #include <stdio.h>
2. void main()
3. {
4. FILE *fptr;
5. int id;
6. char name[30];
7. float salary;
8. fptr = fopen("[Link]", "w+");/* open for writing */
9. if (fptr == NULL)
10. {
11. printf("File does not exists \n");
12. return;
13. }
14. printf("Enter the id\n");
15. scanf("%d", &id);
16. fprintf(fptr, "Id= %d\n", id);
17. printf("Enter the name \n");
18. scanf("%s", name);
19. fprintf(fptr, "Name= %s\n", name);

CCCXXX: Book TitlePage 32


20. printf("Enter the salary\n");
21. scanf("%f", &salary);
22. fprintf(fptr, "Salary= %.2f\n", salary);
23. fclose(fptr);
24. }

Output:

Enter the id
1
Enter the name
sonoo
Enter the salary
120000

Now open file from current directory. For windows operating system, go to TC\bin directory, you will
see [Link] file. It will have following information.

[Link]

Id= 1
Name= sonoo
Salary= 120000

05-04-04:C FPUTC() AND FGETC()

Writing File : fputc() function

The fputc() function is used to write a single character into file. It outputs a character to a stream.

Syntax:

int fputc(int c, FILE *stream)

Example:

1. #include <stdio.h>
2. main(){

CCCXXX: Book TitlePage 33


3. FILE *fp;
4. fp = fopen("[Link]", "w");//opening file
5. fputc('a',fp);//writing single character into file
6. fclose(fp);//closing file
7. }

Reading File : fgetc() function

The fgetc() function returns a single character from the file. It gets a character from the stream. It
returns EOF at the end of file.

Syntax:

int fgetc(FILE *stream)

Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("[Link]","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12. fclose(fp);
13. getch();
14. }

SOLVED PROBLEMS 01

1) C program to read name and marks of n number of students and store them in a file.

#include <stdio.h>
int main()
CCCXXX: Book TitlePage 34
{
char name[50];
int marks, i, num;

printf("Enter number of students: ");


scanf("%d", &num);

FILE *fptr;
fptr = (fopen("C:\\[Link]", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}

for(i = 0; i< num; ++i)


{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);

printf("Enter marks: ");


scanf("%d", &marks);

fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);


}

fclose(fptr);
return 0;
}

2) C program to read name and marks of n number of students from and store them in a
file. If the file previously exits, add the information to the file.

CCCXXX: Book TitlePage 35


#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;

printf("Enter number of students: ");


scanf("%d", &num);

FILE *fptr;
fptr = (fopen("C:\\[Link]", "a"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}

for(i = 0; i< num; ++i)


{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);

printf("Enter marks: ");


scanf("%d", &marks);

fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);


}

fclose(fptr);
return 0;
}

CCCXXX: Book TitlePage 36


3) C program to write all the members of an array of structures to a file using fwrite().
Read the array from the file and display on the screen.

int height;
};
int main(){
struct student stud1[5], stud2[5];
FILE *fptr;
int i;

fptr = fopen("[Link]","wb");
for(i = 0; i< 5; ++i)
{
fflush(stdin);
printf("Enter name: ");
gets(stud1[i].name);

printf("Enter height: ");


scanf("%d", &stud1[i].height);
}

fwrite(stud1, sizeof(stud1), 1, fptr);


fclose(fptr);

fptr = fopen("[Link]", "rb");


fread(stud2, sizeof(stud2), 1, fptr);
for(i = 0; i< 5; ++i)
{
printf("Name: %s\nHeight: %d", stud2[i].name, stud2[i].height);
}
fclose(fptr);
}

SELF-TEST 01

CCCXXX: Book TitlePage 37


1)Take a look at the following program:
int main()
{
file *file;
if(file=fopen(“[Link]”,”w”));
else printf(“program error detected”);
fclose(file);
return 0;
}
The opening mode would:

a) Close the program file


b) Open the program file for reading
c) Open the program file for writing
d) None of the above

2) Which library do we need to use the function fopen() in the C language?

a) math.h
b) file.h
c) canio.h
d) stdio.h

3) Why do we use the “rb” access mode for C files?


a) To write data in binary mode
b) To read data in binary mode
c) To point the file pointer to the file’s last word
d) To write the data in the file

SHORT ANSWER QUESTIONS 01

1) What is file handling in C?


2) What is file handling for?
3) What are file handling operations?

CCCXXX: Book TitlePage 38


4) What is the difference between text and binary files?

SUMMARY

So far the operations using the C program are done on a prompt/terminal which is not stored
anywhere. But in the software industry, most programs are written to store the information fetched
from the program. One such way is to store the fetched information in a file. Different operations that
can be performed on a file are:

1. Creation of 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 text in the brackets denotes the functions used for performing those operations.

The output of a C program is generally deleted when the program is closed. Sometimes, we need to
store that output for purposes like data analysis, result presentation, comparison of output for different
conditions, etc. The use of file handling is exactly what the situation calls for.

In order to understand why file handling makes programming easier, let us look at a few reasons:

 Reusability: The file-handling process keeps track of the information created after the program
has been run.
 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 code using individual commands which saves a lot of time and reduces
the chance of errors.
 Storage Capacity: Files allow you to store data without having to worry about storing everything
simultaneously in a program.

KEY WORDS
C, structure, file, file handling

CCCXXX: Book TitlePage 39


REFERENCES
YOUTUBE VIDEOS

[Link]

[Link]

[Link]

OER

[Link]

[Link]
BOOKS

5. YashavantKanetkar, “Let Us C” – Seventh Edition, BPB Publications,2007

6. [Link], “Programming in ANSI C”, Tata McGraw Hill, 2002

COURSE COMPANION WEBSITE

[Link]

[Link]

MOOCS

[Link]

[Link]

CCCXXX: Book TitlePage 40


CCCXXX: Book TitlePage 41

You might also like