PPSC Unit 5
PPSC Unit 5
FUNCTIONS
INTRODUCTION
“Modular programming is the process of subdividing a computer program into separate sub-
programs.” A module is a separate software component. It can often be used in a variety of
applications and functions with other components of the system. Similar functions are grouped in
the same unit of programming code and separate functions are developed as separate units of code
so that the code can be reused by other applications.Object-oriented programming (OOP) is
compatible with the modular programming concept to a large extent. Modular programming enables
multiple programmers to divide up the work and debug pieces of the program independently.
Function definition: A Function is a self-contained block of statement that performs a specific task
when called. A function is also called as sub program or procedure or subroutine.
Every C Program can be thought of as a collection of these functions. Function is a set of
instructions to carry out a particular task. Function after its execution returns a single value.
FUNCTIONS IN C
Generally, the functions are classified into two types:
1. Standard functions
2. User-defined functions.
The Standard functions are also called library functions or built-in functions. All standard functions,
such as sqrt(), abs(), log(), sin() etc. are provided in the library of function. But, most of the
applications need other functions than those available in the software; those are known as user-
defined functions.
Advantages of functions: Several advantages of dividing the program into functions include:
Modularity
Reduction in code redundancy
Enabling code reuse
Better readability
Parts of a function: A function has the following parts:
Function prototype declaration.
Function definition.
Function call.
Actual arguments and Formal arguments.
The return statement.
Function Declaration:Function prototype declaration consist function return type, function name,
and argument list. A function must be declared before it is used
Syntax:return_typefunction_name(parameter_list);
parameter_list: type param1,type param2,type param3, etc
Examples: double sqrt(double);
int func1();
void func2(char c);
Function Definition also known as function implementation, means composing a function. Every
Function definition consists of two Parts:
Header of the function,
Body of the function.
Syntax :return_typefunction_name(parameter_list)
{
// Function body
}
The body of a function consists of a set of statements enclosed within braces. The return statement
is used to return the result of the computations done in the calledfunction and/or to return the
program control back to the calling function. A function can be defined in any part of the program
text or within a library
Example: void welcome( )
{ Function header
printf(“hello world\n”); //Function body
}
Types/Categories of functions:
All C functions can be called either with arguments or without arguments in a C program. These
functions may or may not return values to the calling function. Functions can be divided into 4
categories:
1. A function with no arguments and no return value
2. A function with no arguments and a return value
3. A function with an argument/parameter or arguments and no return value
4. A function with arguments and a return value
C functions aspects syntax
function declaration:int function ( int );
function call: function ( a );
function definition:
int function( int a )
With arguments and with return values
{
statements;
return a;
}
function declaration:void function ( int );
function call: function( a );
function definition:
With arguments and without return values void function( int a )
{
statements;
}
NOTE:
If the return data type of a function is “void”, then, it can’t return any values to the calling
function.
If the return data type of the function is other than void such as “int, float, double etc”, then, it
can return values to the calling function.
Other examples programs for function types(same above topic with another examples)
int main(){
void addition() ; // function declaration
getch() ;
}
void addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 ) ;
}
o/p:
Enter any two integer numbers : 2
3
Sum = 5
//Function with Parameters and without Return value
#include<stdio.h>
#include<conio.h>
int main()
{
int num1, num2 ;
void addition(int, int) ; // function declaration
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
getch() ;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}
o/p:
Enter any two integer numbers : 2
3
Sum = 5
int main()
{
int result ;
int addition() ; // function declaration
#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and
b in main
swap(a,b);
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
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b
= 10
}
o/p:
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
Call by Reference: In call by reference method, the address of the variable is passed to the function
as parameter. The value of the actual parameter can be modified by formal parameter. Same
memory is used for both actual and formal parameters since only address is used by both
parameters.
Example:
#include<stdio.h>
void swap(int *, int *);
int main()
{
int a = 22, b = 44;
printf("\nValues before swap a = %d and b = %d", a, b);
swap(&a,&b); //passing address(s) to the function
printf(" \nValues after swap a = %d and b = %d", a, b);
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
OUTPUT:
Values before swap a =22 and b = 44
Values after swap a =44 and b = 22
INTER FUNCTION COMMUNICATION
When a function gets executed in the program, the execution control is transferred from calling a
function to called function and executes function definition, and finally comes back to the calling
function. In this process, both calling and called functions have to communicate with each other to
exchange information. The process of exchanging information between calling and called functions
is called inter-function communication.
In C, the inter function communication is classified as follows...
Downward Communication
Upward Communication
Bi-directional Communication
Downward Communication
In this type of inter function communication, the data is transferred from calling function to called
function but not from called function to calling function. The functions with parameters and without
return value are considered under downward communication. In the case of downward
communication, the execution control jumps from calling function to called function along with
parameters and executes the function definition,and finally comes back to the calling function
without any return value. For example consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
addition(num1, num2) ; // calling function
getch() ;
}
void addition(int a, int b) // called function
{
printf("SUM = %d", a+b) ;
}
o/p:sum=30
Upward Communication
In this type of inter-function communication, the data is transferred from called function to calling-
function but not from calling-function to called-function. The functions without parameters and
with return value are considered under upward communication. In the case of upward
communication, the execution control jumps from calling-function to called-function without
parameters and executes the function definition, and finally comes back to the calling function
along with a return value. For example, consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int result ;
int addition() ; // function declaration
clrscr() ;
result = addition() ; // calling function
printf("SUM = %d", result) ;
getch() ;
}
int addition() // called function
{
int num1, num2 ;
num1 = 10;
num2 = 20;
return (num1+num2) ;
}
Output: sum=30
Bi - Directional Communication
In this type of inter-function communication, the data is transferred from calling-function to called
function and also from called function to calling-function. The functions with parameters and with
return value are considered under bi-directional communication. In the case of bi-directional
communication, the execution control jumps from calling-function to called function along with
parameters and executes the function definition and finally comes back to the calling function along
with a return value. For example, consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2, result ;
int addition(int, int) ; // function declaration
num1 = 10 ;
num2 = 20 ;
result = addition(num1, num2) ; // calling function
printf("SUM = %d", result) ;
getch() ;
}
int addition(int a, int b) // called function
{
return (a+b) ;
}
Output: Sum=30
Standard Functions in C
The standard functions are built-in functions. In C programming language, the standard functions
are declared in header files and defined in .dll files. In simple words, the standard functions can be
defined as "the ready made functions defined by the system to make coding more easy". The
standard functions are also called as library functions or pre-defined functions.
In C when we use standard functions, we must include the respective header file
using #include statement. For example, the function printf() is defined in header
file stdio.h (Standard Input Output header file). When we use printf() in our program, we must
include stdio.h header file using #include<stdio.h> statement.
Header Example
File Purpose Functions
stdio.h Provides functions to perform standard I/O operations printf(), scanf()
time.h Provides functions to perform operations on time and date time(), localtime()
ctype.h Provides functions to perform - testing and mapping of character data isalpha(), islower()
values
Function Description
This function returns the absolute value of an integer. The absolute value of a
abs ( ) number is always positive. Only integer values are supported in C.
This function returns the nearest integer which is less than or equal to the
floor ( ) argument passed to this function.
This function returns the nearest integer value of the float/double/long
double argument passed to this function. If decimal value is from “.1 to .5”, it
returns integer value less than the argument. If decimal value is from “.6 to .9”,
round ( ) it returns the integer value greater than the argument.
This function returns nearest integer value which is greater than or equal to the
ceil ( ) argument passed to this function.
sin ( ) This function is used to calculate sine value.
cos ( ) This function is used to calculate cosine.
tan ( ) This function is used to calculate tangent.
sqrt ( ) This function is used to find square root of the argument passed to this function.
pow ( ) This is used to find the power of the given number.
Header Example
File Purpose Functions
This function truncates the decimal value from floating point value and returns
trunc ( ) integer value.
abs( ) function in C returns the absolute value of an integer. The absolute value of a number
is always positive. Only integer values are supported in C.
“stdlib.h” header file supports abs( ) function in C language. Syntax for abs( ) function in C
is given below.
int abs ( int n );
Example :abs
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m = abs(200); // m is assigned to 200
int n = abs(-400); // n is assigned to -400
printf("Absolute value of m = %d\n", m);
printf("Absolute value of n = %d \n",n);
return 0;
}
Absolute value of m=200
Absolute value of n = 400
Example :floor
#include <stdio.h>
#include <math.h>
int main()
{
float i=5.1, j=5.9, k=-5.4, l=-6.9;
printf("floor of %f is %f\n", i, floor(i));
printf("floor of %f is %f\n", j, floor(j));
printf("floor of %f is %f\n", k, floor(k));
printf("floor of %f is %f\n", l, floor(l));
return 0;
}
floor of 5.100000 is 5.000000
floor of 5.900000 is 5.000000
floor of -5.400000 is -6.000000
floor of -6.900000 is -7.000000
Example :round
#include <stdio.h>
#include <math.h>
int main()
{
float i=5.4, j=5.6;
printf("round of %f is %f\n", i, round(i));
printf("round of %f is %f\n", j, round(j));
return 0;
}
round of 5.400000 is 5.000000
round of 5.600000 is 6.000000
Example :ceil
#include <stdio.h>
#include <math.h>
int main()
{
float i=5.4, j=5.6;
printf("ceil of %f is %f\n", i, ceil(i));
printf("ceil of %f is %f\n", j, ceil(j));
return 0;
}
o/p: ceil of 5.400000 is 6.000000
ceil of 5.600000 is 6.000000
Example :square
#include <stdio.h>
#include <math.h>
int main()
{
printf ("sqrt of 16 = %f\n", sqrt (16) );
printf ("sqrt of 2 = %f\n", sqrt (2) );
return 0;
}
sqrt of 16 = 4.000000
sqrt of 2 = 1.414214
Example :pow
#include <stdio.h>
#include <math.h>
int main()
{
printf ("2 power 4 = %f\n", pow (2.0, 4.0) );
printf ("5 power 3 = %f\n", pow (5, 3) );
return 0;
}
OUTPUT:
2 power 4 = 16.000000
5 power 3 = 125.000000
#include <stdio.h>
#include <math.h>
int main()
{
float i = 0.314;
float j = 0.25;
float k = 6.25;
float sin_value = sin(i);
float cos_value = cos(i);
float tan_value = tan(i);
float sinh_value = sinh(j);
float cosh_value = cosh(j);
float tanh_value = tanh(j);
float log_value = log(k);
float log10_value = log10(k);
float exp_value = exp(k);
We can understand the above program of recursive method call by the figure given below:
Recursion terminates when a base case is Iteration terminates when the loop-
4
recognized condition fails
Recursion is usually slower then iteration Iteration does not use stack so it's faster
5
due to overhead of maintaining stack than recursion
Recursion uses more memory than
6 Iteration consume less memory
iteration
#include<stdio.h>
int main()
{
int myArray[] = { 2, 3, 4 };
giveMeArray(myArray[2]); //Passing array element myArray[2] only.
return 0;
}
void giveMeArray(int a)
{
printf("%d", a);
}
o/p:4
Passing a complete One-dimensional array to a function
To understand how this is done, let's write a function to find out average of all the elements of the
array and print it.
We will only send in the name of the array as argument, which is nothing but the address of the
starting element of the array, or we can say the starting memory address.
#include<stdio.h>
int main()
{
float avg;
int marks[] = {99, 90, 96, 93, 95};
avg = findAverage(marks); // name of the array is passed as argument.
printf("Average marks = %.1f", avg);
return 0;
}
int main()
{
int arr[3][3], i, j;
printf("Please enter 9 numbers for the array: \n");
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 3; ++j)
{
scanf("%d", &arr[i][j]);
}
}
// passing the array as argument
displayArray(arr);
return 0;
}
void displayArray(int arr[3][3])
{
int i, j;
printf("The complete array is: \n");
for (i = 0; i < 3; ++i)
{
// getting cursor to new line
printf("\n");
for (j = 0; j < 3; ++j)
{
// \t is used to provide tab space
printf("%d\t", arr[i][j]);
}
}
}
For example:
"c string tutorial"
Here, "c string tutorial" is a string. When, compilers encounter strings, it appends a null
character /0 at the end of string.
“Strings are just char arrays. So, they can be passed to a function in a similar manner as arrays”.
Example:
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
gets(str);
displayString(str); // Passing string PPS in str to function. return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
o/p: Enter string: ppsc
String Output: ppsc
Here, string PPS is passed from main() function to user-defined function displayString(). In
func- tion declaration, str[] is the formal argument.
n C programming language, a variable can be declared in three different positions and they are as
follows...
Before the function definition (Global Declaration)
Inside the function or block (Local Declaration)
In the function definition parameters (Formal Parameters)
#include<stdio.h>
#include<conio.h>
int num1, num2 ;
void main(){
void addition() ;
void subtraction() ;
void multiplication() ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
addition() ;
subtraction() ;
multiplication() ;
getch() ;
}
void addition()
{
int result ;
result = num1 + num2 ;
printf("\naddition = %d", result) ;
}
void subtraction()
{
int result ;
result = num1 - num2 ;
printf("\nsubtraction = %d", result) ;
}
void multiplication()
{
int result ;
result = num1 * num2 ;
printf("\nmultiplication = %d", result) ;
}
o/p:
num1=10,num2=20
addition=10
substraction=-10
multiplication=200
#include <stdio.h>
void disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
/* I'm passing each element one by one using subscript*/
disp (arr[x]);
}
return 0;
}
Output:
abcde fghij
Passing array to function using call by reference
When we pass the address of an array while calling a function then this is called function call by
reference. When we pass an address as an argument, the function declaration should have
a pointer as a parameter to receive the passed address.
#include <stdio.h>
void disp( int *num)
{
printf("%d ", *num);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++) {
/* Passing addresses of array elements*/
disp (&arr[i]);
}
return 0;
}
Output:
1234567890
#include <stdio.h>
void myfuncn( int *var1, int var2)
{
/* The pointer var1 is pointing to the first element of
* the array and the var2 is the size of the array. In the
* loop we are incrementing pointer so that it points to
* the next element of the array on each increment.
*
*/
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}
int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(var_arr, 7);
return 0;
}
Output:
Value of var_arr[0] is: 11
Value of var_arr[1] is: 22
Value of var_arr[2] is: 33
Value of var_arr[3] is: 44
Value of var_arr[4] is: 55
Value of var_arr[5] is: 66
Value of var_arr[6] is: 77
FILES:Generally, a file is used to store user data in a computer. In other words, computer stores
the datausing files. we can define a file as follows...
Definition :
File is a collection of data that stored on secondary memory like haddisk of a computer.
File:
It is a place on hard disk where data is stored permanently. A file represents a sequence
of bytes, does not matter if it is a text file or binary file. C programming language
provides access onhigh level functions as well as low level (OS level) calls to handle file
on your storage devices.
Types of files:
C programming language supports two types of files and they are as follows...
Text Files (or) ASCII Files
Binary Files
Text File (or) ASCII File - The file that contains ASCII codes of data like digits, alphabets and
symbols is called text file (or) ASCII file.
Binary File - The file that contains data in the form of bytes (0's and 1's) is called as binary file.
Generally, the binary files are compiled version of text files.
Why Files?
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.
Types of Files:
1. Text file
2. Binary File
ASCII Text Files:
A text file can be a stream of characters that a computer can process sequentially.
It is processed only in forward direction.
It is opened for one kind of operation (reading, writing, or appending) at any given time.
It can read only one character at a time.
text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad.
When you open those files, you'll see all the contents within the file as plain text. You can easily
edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the least security and
takes bigger storage space.
Binary Files:
Modes of file:
Modes of the opening the file:
r - File is opened for reading
w - File is opened for writing
a - File is opened for appending (adding)
r+ - File is opened for both reading & writing
w+ - File is opened for both writing & reading
a+ - File is opened for appending & reading
rt - text file is opened for reading
wt - text file is opened for writing
at - text file is opened for appending
r+t - text file is opened for reading & writing
w+t - text file is opened for both writing & reading
a+t - text file is opened for both appending &reading
rb - binary file is opened for reading
wb - binary file is opened for writing
ab - binary file is opened for appending
r+b - binary file is opened for both reading & writing
w+b - binary file is opened for both writing & reading
a+b - binary file is opened for both appending & reading.
Accessing of files:
STREAMS:
File streams: A stream is a series of bytes of data flow from your program to a file or vice-versa. A
stream is an abstract representation of any external source or destination for data, so the keyword,
the command line on your display and files on disk are all examples of stream. “C” provides
numbers of function for reading and writing to or from the streams on any external devices. There
are two formats of streams which are as follows:
1. Text Stream 2. Binary Stream
Text Stream:
It consists of sequence of characters, depending on the compilers.
Each character line in a text stream may be terminated by a newline character.
Text streams are used for textual data, which has a consistent appearance from one
environment to another or from one machine to another.
Binary Stream:
It is a series of bytes.
Binary streams are primarily used for non-textual data, which is required to keep exact
contents of the file.
Declaring, Opening, and Closing File Streams: you can perform four major operations on the file,
either text or binary:
1. Opening a file
2. Closing a file
3. Reading a file
4. Writing in a file
Opening a file:
To create a new file or open an existing file, we need to create a file pointer of FILE type. Following
is the sample code for creating file pointer.
File *f_ptr ;
We use the pre-defined method fopen() to create a new file or to open an existing file. There are
different modes in which a file can be opened. Consider the following code...
To create a new file or open an existing file, we need to create a file pointer ofFILE type.
Following is the sample code for creating file pointer.
File *f_ptr ;
We use the pre-defined method fopen() to create a new file or to open an existing file. There
are different modes in which a file can be opened. Considerthe following code...
File *f_ptr ;
*f_ptr = fopen("abc.txt", "w") ;
The above example code creates a new file called abc.txt if it does not existsotherwise it is
opened in writing mode.
To perform any operation (read or write), the file has to be brought into memory from the storage
device. Thus, bringing the copy of file from disk to memory is called opening the file.
The fopen() function is used to open a file and associates an I/O stream with it. The general form
of fopen() is
or fopen ("filename","mode");
This function takes two arguments. The first argument is the name of the file to be opened while
the second argument is the mode in which the file is to be opened.
NOTE: Before opening a file, we have to create/declare a file pointer that is created using FILE
structure is defined in the “stdio.h” header file.
For example:
Fopen program:
#include<stdio.h>
void main( )
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
fclose (fp ) ;
Output
Closing a file:
To close a file and dis-associate it with a stream, use fclose() function. It returns zero if successful
else returns EOF if error occurs. The fcloseall() closes all the files opened previously. The general
form is:
fclose(file pointer);
FILE *fp;
fp = fopen("INPUT.txt","r") // Open file in Read mode
return(0);
1. Create a variable of type FILE *, and store the return value from fopen in it.
2. Check the return value to make sure it is not equal to NULL before using it. If
fopen returnsNULL, then it was unable to open the requested file for some
reason.
#include,stdio.h>
main()
FILE *fp;
fp=fopen(“data.txt”,”r”); if(fp
= = NULL)
exit(0);
Closing a file
To close a file you simply use the function fclose with the file pointer in the parentheses.
Actually, inthis simple program, it is not necessary to close the file because the system will
close all open files before returning to DOS, but it is good programming practice for you to
close all files in spite of the fact that they will be closed automatically, because that would
act as a reminder to you of what files are open at the end of each program.
Syntax:
fclose(file-pointer);
Example ::
#include<stdio.h>
void main()
if(fptr==null)
return 0;
}
Output
Character input ouput functions:
The reading from a file operation is performed using the following pre-defined file handling
methods.
Reading from a file(character input functions)
1. getc()
2. getw()
3. fgets()
getw( *file_pointer ) - This function is used to read an integer value form the specified file
which is opened in reading mode. If the data in file is set of characters then it reads ASCII
values of those characters.
Example Program to illustrate getw() in C.
#include<stdio.h>
int main(){
FILE *fp;
int i,j;
fp = fopen("MySample.txt","w");
putw(65,fp); // inserts A
putw(97,fp); // inserts a
fclose(fp);
fp = fopen("MySample.txt","r");
i = getw(fp); // reads 65 - ASCII value of A
j = getw(fp); // reads 97 - ASCII value of a
printf("SUM of the integer values stored in file = %d", i+j); // 65 + 97 = 162
fclose(fp);
getch();
return 0;
}
Output
fgets( variableName, numberOfCharacters, *file_pointer ) - This method is used for reading a set
of characters from a file which is opened in reading mode starting from the current cursor
position. The fgets() function reading terminates with reading NULL character.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char *str;
clrscr();
fp = fopen ("file.txt", "r");
fgets(str,6,fp);
printf("str = %s", str);
fclose(fp);
getch();
return 0;
}
Output:
putc( char, *file_pointer ) - This function is used to write/insert a character to the specified
file when the file is opened in writing mode.
Example Program to illustrate putc() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char ch;
fp=fopen("C:/TC/EXAMPLES/MySample.txt","w");
putc('A',fp);
ch = 'B';
putc(ch,fp);
fclose(fp);
getch();
return 0;
} Output
putw( int, *file_pointer ) - This function is used to writes/inserts an integer value to the
specified file when the file is opened in writing mode.
Example Program to illustrate putw() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
int i;
fp = fopen("MySample.txt","w");
putw(66,fp);
i = 100;
putw(i,fp);
fclose(fp);
getch();
return 0;
} Output
fputs( "string", *file_pointer ) - TThis method is used to insert string data into specified file
which is opened in writing mode.
Example Program to illustrate fputs() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char *text = "\nthis is example text";
clrscr();
fp = fopen("MySample.txt","w");
fputs("Hi!\nHow are you?",fp);
fclose(fp);
getch();
return 0;
}
Output
ftell( *file_pointer ) - This function returns the current position of the cursor in the file.
Example Program to illustrate ftell() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
int position;
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
Output
rewind( *file_pointer ) - This function is used reset the cursor position to the beginning of
the file.
Example Program to illustrate rewind() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
int position;
clrscr();
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
rewind(fp);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
Output
fseek( *file_pointer, numberOfCharacters, fromPosition ) - This function is used to set the
cursor position to the specific position. Using this function we can set the cursor position
from three different position they are as follows.
o from beginning of the file (indicated with 0)
o from current cursor position (indicated with 1)
o from ending of the file (indicated with 2)
return 0;
}
Output
File conversions
#include <stdio.h>
#include <string.h>
#define MAX 256
int main() {
int num;
FILE *fp1, *fp2;
char ch, src[MAX], tgt[MAX];
/* error
handling */if
(!fp2) {
printf("Unable to open the output
file!!\n");return 0;
}
/*
* read data from input file and write
* the binary form of it in output file
*/
while (!feof(fp1)) {
/* reading one byte of
data */ fread(&ch,
sizeof(char), 1, fp1);
/* converting the character to ascii integer
value */num = ch;
/* writing 4 byte of data to the
output file */fwrite(&num, sizeof(int),
1, fp2);
}
/* close all opened
files */fclose(fp1);
fclos
e(fp
2);
retu
rn 0;
}
Output: jp@jp-VirtualBox:~/$ cat data.txt
abcde
fg123
4
56789
hijklm
12345
6abcd
e
fghijk1
2345
jp@jp-VirtualBox:~/$ ./a.out
Enter your input file name:
data.txt Enter your output
file name: res.bin
a^@^@^@b^@^@^@c^@^@^@d^@^@^
@e^@^
a^@^@^@b^@^@^@c^@^@^@d^@^@^
@e^@^
a^@^@^@b^@^@^@c^@^@^@d^@^@^
@e^@^
name:tgt