Unit 3 Que & Ans
Unit 3 Que & Ans
Ans: Function in C:
( CO - 2, BT – 2 )
A function is a block of code that performs a specific task. It has a name and it is reusable
.It can be executed from as many different parts in a program as required, it can also return a
value to calling program.
All executable code resides within a function. It takes input, does something with it, then give
the answer. A C program consists of one or more functions.
A computer program cannot handle all the tasks by itself. It requests other program like entities
called functions in C. We pass information to the function called arguments which specified
when the function is called. A function either can return a value or returns nothing. Function is
a subprogram that helps reduce coding.
Simple Example of Function in C
#include<stdio.h>
#include <conio.h>
int adition (int, int); //Function Declaration
int addition (int a, int b) //Function Definition
{
int r;
r=a + b;
return (r);
}
int main()
{
int z;
z= addition(10,3); //Function Call
1. B. Distinguish between Library functions and User defined functions in C and Explain with
examples. (CO - 2, BT – 3 )
Ans: Types of Function in C:
(i). Library Functions in C
C provides library functions for performing some operations. These functions are present in the c
library and they are predefined.
For example sqrt() is a mathematical library function which is used for finding the square root of
any number .The function scanf and printf() are input and output library function similarly we
have strcmp() and strlen() for string manipulations. To use a library function we have to include
some header file using the preprocessor directive #include.
For example to use input and output function like printf() and scanf() we have to include stdio.h,
for math library function we have to include math.h for string library string.h should be included.
1. Function declaration
The program or a function that calls a function is referred to as the calling program or calling
function. The calling program should declare any function that is to be used later in the
program this is known as the function declaration or function prototype.
2. Function Definition
The function definition consists of the whole description and code of a function. It tells that
what the function is doing and what are the input outputs for that. A function is called by
simply writing the name of the function followed by the argument list inside the parenthesis.
Function definitions have two parts:
Function Header
The first line of code is called Function Header.
int sum( int x, int y)
It has three parts
(i). The name of the function i.e. sum
(ii). The parameters of the function enclosed in
parenthesis (iii). Return value type i.e. int
Function Body
Whatever is written with in { } is the body of the function.
3. Function Call
In order to use the function we need to invoke it at a required place in the program. This is
known as the function call.
When a function has no arguments, it does not return any data from calling function. When a
function does not return a value, the calling function does not receive any data from the called
function. That is there is no data transfer between the calling function and the called function.
Example
#include <stdio.h>
#include <conio.h>
void printmsg()
{
printf ("Hello ! I Am A Function .");
}
int main()
{
printmsg();
return 0;
}
When a function has arguments data is transferred from calling function to called function. The
called function receives data from calling function and does not send back any values to calling
function. Because it doesn‟t have return value.
Example
#include<stdio.h>
#include <conio.h>
void add(int,int);
void main()
{
int a, b;
%d”,&a,&b);
add(a,b);
}
The sum = 5
In this data is transferred between calling and called function. That means called function
receives data from calling function and called function also sends the return value to the calling
function.
Example
#include<stdio.h>
#include <conio.h>
int add(int, int);
main()
{
int a,b,c;
printf(“enter value”);
scanf(“%d%d”,&a,&b);
c=add(a,b);
printf ("The sum =%d",c);
}
int add (int x, int y)
{
int z;
z=x+y;
return z;
}
output : enter values 2 3
The sum = 5
When function has no arguments data cannot be transferred to called function. But the called
function can send some return value to the calling function.
Example
#include<stdio.h>
#include <conio.h>
int add( );
main()
{
int c;
c=add();
printf ("The sum =%d",c);
}
int add ()
{
int x,y,z;
printf(“enter value”);
scanf(“%d%d”,&a,&b);
z=x+y;
return z;
}
Output: enter values 2 3
The sum = 5
Ans: ( CO - 2, BT – 2 )
In this method calling function sends a copy of actual values to called function, but the changes
in called function does not reflect the original values of calling function.
Example program:
#include<stdio.h>
void main( )
fun1(a,b);
printf(“a=%d,b=%d”, a,b);
0; y=
y+20;
}
Output: a=10 b=15
The result clearly shown that the called function does not reflect the original values in main
function.
In this method calling function sends address of actual values as a parameter to called function,
called function performs its task and sends the result back to calling function. Thus, the changes
in called function reflect the original values of calling function. To return multiple values from
called to calling function we use pointer variables.
Calling function needs to pass „&‟ operator along with actual arguments and called function
need to use „*‟ operator along with formal arguments. Changing data through an address
variable is known as indirect access and „*‟ is represented as indirection operator.
Example program:
#include<stdio.h>
void fun1(int,int);
void main( )
fun1(&a,&b); printf(“a=
%d,b=%d”, a,b);
}
void fun1(int *x, int *y)
*x = *x + 10;
*y = *y + 20;
The result clearly shown that the called function reflect the original values in main function. So
that it changes original values.
Formal and actual parameters need not match for their names.
4. A. What is recursive function? Differentiate between recursion and iteration/ non-
recursion
Ans: (CO - 2, BT – 1 )
Recursion
Recursion is a process by which a function calls itself repeatedly, until some specified condition
has been satisfied.
When a function calls itself, a new set of local variables and parameters are allocated storage on
the stack, and the function code is executed from the top with these new variables. A recursive
call does not make a new copy of the function. Only the values being operated upon are new. As
each recursive call returns, the old local variables and parameters are removed from the stack,
and execution resumes immediately after the recursive call inside the function.
The main advantage of recursive functions is that we can use them to create clearer and simpler
versions of several programs.
Syntax:-
void f( )
{
f( );
}
(or) indirectly:
void f( )
{
g( );
}
void g( )
{
f( );
}
Recursion rule 1: Every recursive method must have a base case -- a condition under which no
recursive call is made -- to prevent infinite recursion.
Recursion rule 2: Every recursive method must make progress toward the base case to prevent
infinite recursion
Recursion:- Recursion is a process by which a function calls itself repeatedly, until some
specified condition has been satisfied.
When a function calls itself, a new set of local variables and parameters are allocated storage on
the stack, and the function code is executed from the top with these new variables. A recursive
call does not make a new copy of the function. Only the values being operated upon are new. As
each recursive call returns, the old local variables and parameters are removed from the stack,
and execution resumes immediately after the recursive call inside the function.
Ex:-
void main( )
{
int n=5;
fact( n);
}
int fact( )
{
if(n==0 || n==1)
return 1;
else
return(n*fact(n-1));
}
Non-Recursion:-
Using looping statements we can handle repeated statements in „C‟. The example of non
recursion is given below.
Syntax:-
void main( )
{
int n=5;
res = fact(n);
printf(“%d”,res);
}
int fact( )
{
for(i=1;i<=n;i++)
{
f=f+1;
}
return f;
}
Differences:
- Recursive version of a program is slower than iterative version of a program due to overhead
of maintaining stack.
- Recursive version of a program uses more memory (for the stack) than iterative version of a
program.
- Sometimes, recursive version of a program is simpler to understand than iterative version of a
program.
Factorial of 5 is 120
5. A. How to Pass Array Individual Elements to Functions? Explain with example program.
Ans: (CO - 2, BT – 2 )
To process arrays in a large program, we need to pass them to functions. We can pass arrays in
two ways:
One-dimensional Arrays:
We can pass individual elements by either passing their data values or by passing their addresses.
We pass data values i.e; individual array elements just like we pass any data value .As long as the
array element type matches the function parameter type, it can be passed. The called function
cannot tell whether the value it receives comes from an array, a variable or an expression.
void main()
func1(a[3]);
printf(“%d”,x+100);
}
Two-dimensional Arrays:
The individual elements of a 2-D array can be passed in the same way as the 1-D array. We can
pass 2-D array elements either by value or by address.
void fun1(int a)
main()
int a[2][2]={1,2,3,4};
fun1(a[0][1]);
void fun1(int x)
printf(“%d”,x+10);
5.b How can we pass the Whole Array to Functions? Explain with example
program. ( CO - 2, BT – 2 )
Ans: Passing an entire array to a function:
One-dimensional array:
To pass the whole array we simply use the array name as the actual parameter. In the called
function, we declare that the corresponding formal parameter is an array. We do not need to
specify the number of elements.
Program :
void main()
fun1(a);
int i, sum=0;
for(i=0;i<5;i++)
sum=sum+a[i];
printf(“%d”,sum);
Two-dimensional array:
When we pass a 2-D array to a function, we use the array name as the actual parameter just as we
did with 1-D arrays. The formal parameter in the called function header, however must indicate
that the array has two dimensions.
Rules:
void main()
{
int a[2][2]={1,2,3,4};
fun1(a);
int i,j;
for(i=0;i<2;i++)
for(j=0;j<2;j++)
printf(“%d”,x[i][j]);
Variables in C differ in behavior. The behavior depends on the storage class a variable may
assume. From C compiler‟s point of view, a variable name identifies some physical location
within the computer where the string of bits representing the variable‟s value is stored. There are
four storage classes in C:
Keyword Auto
Storage Memory.
Default initial value An unpredictable value, which is often called a garbage value.
Scope Local to the block in which the variable is defined.
Life Till the control remains within the block in which the
variable is defined
Following program shows how an automatic storage class variable is declared, and the fact that
if the variable is not initialized it contains a garbage value.
main( )
{
auto int i, j ;
printf ( "\n%d %d", i, j ) ;
}
When you run this program you may get different values, since garbage values are unpredictable.
So always make it a point that you initialize the automatic variables properly, otherwise you are
likely to get unexpected results. Scope and life of an automatic variable is illustrated in the
following program.
main( )
{
auto int i = 1 ;
{
auto int i = 2 ;
{
auto int i = 3 ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
Storage Memory.
main()
{
Increment();
Increment();
Increment();
}
Increment()
{
static int i=1;
printf(“%d”,i);
i++;
}
Output:
1
2
3
The features of a variable whose storage class has been defined as external are as follows:
Keyword Extern
Storage Memory
default initial value Zero
Scope Global
Life As long as the program execution does not come
to end
External variables differ from those we have already discussed in that their scope is global, not
local. External variables are declared outside all functions, yet are available to all functions that
care to use them. Here is an example to illustrate this fact.
Ex:
#include<stdio.h>
extern int i;
void main()
{
printf(“i=%d”,i);
default initial value An unpredictable value, which is often called a garbage value.
Life Till the control remains within the block in which the variable
is defined.
A value stored in a CPU register can always be accessed faster than the one that is stored in
memory. Therefore, if a variable is used at many places in a program it is better to declare its
storage class as register. A good example of frequently used variables is loop counters. We can
name their storage class as register.
main( )
register int i ;
printf ( "\n%d", i ) ;
A function, like a variable has a type and address location in the memory. It is therefore possible
to declare a pointer to a function, which can then be used as an argument in another function.
This tells the complier that fptr is a pointer to a function which returns type value the parentheses
around *fptr is necessary.
Because type *gptr(); would declare gptr as a function returning a pointer to type.
We can make a function pointer to point to a specific function by simply assigning the name
of the function to the pointer.
double (*p1)();
p1=mul();
It declares p1 as a pointer to a function and mul as a function and then make p1 to point to the
function mul.
To call the function mul we now use the pointer p1 with the list of parameters.
Program:
void main()
int x,y;
double (*p1)();
double res;
p1=mul;
scanf("%d %d",&x,&y);
res=(*p1)(x,y);
}
double mul(int a,int b)
double val;
val=a*b;
return(val);
}
Output:
Enter 2 numbers: 22 7
Res is 154.00000
We can pass each element of the structure through function but passing individual element is
difficult when number of structure element increases. To overcome this, we use to pass the
whole structure through function instead of passing individual element.
#include<stdio.h>
#include<string.h>
void main()
{
struct student
char name[30];
char branch[25];
int roll;
}struct student s;
char name[30];
int age,roll;
};
void main()
{
display(struct student s)
1. Static allocation
2. Dynamic allocation
1) Static allocation: If the memory is allocated during compilation time itself, the allocated
memory space cannot be expanded to accommodate more data or cannot be reduced to
accommodate less data.
In this technique once the size of the memory is allocated it is fixed. It cannot be altered
even during execution time .This method of allocating memory during compilation time is called
static memory allocation.
2) Dynamic allocation: Dynamic memory allocation is the process of allocating memory during
execution time. This allocation technique uses predefined functions to allocate and release
memory for data during execution time.
The memory is allocated in memory stack. The memory is allocated from free memory
pool (heap).
Memory is allocated either in stack area or Memory is allocated only in heap area
data area
Ans: The function malloc( ) allocates a block of size bytes from the free memory pool (heap).
It allows a program to allocate an exact amount of memory explicitly, as and when needed.
Ptr= (cat_type*)malloc(byte_size);
Ptr is a pointer of type cast_type.The malloc returns a pointer to an area of memory with size
byte_size.The parameter passed to malloc() is of the type byte_size. This type is declared in the
header file alloc.h. byte_size is equivalent to the unsigned int data type. Thus, in compilers
where an int is 16 bits in size, malloc() can allocate a maximum of 64KB at a time, since the
maximum value of an unsigned int is 65535.
Return value:
On success, i.e., if free memory is available, malloc() returns a pointer to the newly allocated
memory. Usually, it is generic pointer. Hence, it should be typecast to appropriate data type
before using it to access the memory allocate.
On failure, i.e., if enough free memory does not exist for block, malloc() returns NULL. The
constant NULL is defined in stdio.h to have a value zero. Hence, it is safe to check the return
value.
Ex: 1) malloc(30); allocates 30 bytes of memory and returns the address of byte0.
Ptr= (cast_type*)calloc(n,ele_size);
calloc( ) provides access to the C memory heap, which is available for dynamic allocation
of variable-sized blocks of memory.
Unlike malloc(), the function calloc( ) accepts two arguments: n and ele_size. The parameter n
specifies the number of items to allocate and ele_size specifies the size of each item.
Return value:
On success, i.e., if free memory is available, calloc( ) returns a pointer to the newly allocated
memory. Usually, it is generic pointer. Hence, it should be typecast to appropriate data type
before using it to access the memory allocated.
On failure, i.e., if enough free memory does not exist for block, calloc( ) returns NULL. The
constant NULL is defined in stdio.h to have a value zero. Hence, it is safe to verify the return
value before using it.
Ex: calloc(3,5); allocates 15 bytes of memory and returns the address of byte0.
Ptr=realloc(ptr,newsize);
The function realloc() allocates new memory space of size newsize to the pointer variable ptr
and returns a pointer to the first byte of the new memoty block.
ptr is the pointer to the memory block that is previously obtained by calling malloc(), calloc() or
realloc(). If ptr is NULL pointer, realloc() works just like malloc().
Return value:
On success, this function returns the address of the reallocated block, which might be different from the
address of the original block.
On failure, i.e., if the block can‟t be reallocated or if the size passed is 0, the function returns NULL.
The function realloc() is more useful when the maximum size of allocated block cann‟t be
decided in advance.
Free(ptr);
ptr is the pointer that is points to allocated memory by malloc( ), calloc( ) or realloc(). Passing
an uninitialized pointer, or a pointer to a variable not allocated by malloc( ), calloc() or realloc()
could be dangerous and disastrous.
9. A. What are Command Line Arguments ? Write an example program for command
line arguments ? (CO - 2, BT – 2 )
It is possible to pass some values from the command line to your C programs when
they are executed. These values are called command line arguments and many times they
are important for your program especially when you want to control your program from
outside instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer array which
points to each argument passed to the program.
#include <stdio.h>
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
The C preprocessor is a macro processor that is used automatically by the C compiler to transform
programmer defined programs before actual compilation takes place. It is called a macro processor
because it allows the user to define macros, which are short abbreviations for longer constructs.
This functionality allows for some very useful and practical tools to design our programs.
To include header files(Header files are files with pre defined function definitions, user
defined data types, declarations that can be included.)
To include macro expansions. We can take random fragments of C code and abbreviate them
into smaller definitions namely macros, and once they are defined and included via header files
or directly onto the program itself it(the user defined definition) can be used everywhere in the
program. In other words it works like a blank tile in the game scrabble, where if one player
possesses a blank tile and uses it to state a particular letter for a given word he chose to play
then that blank piece is used as that letter throughout the game. It is pretty similar to that rule.
Special pre processing directives can be used to, include or exclude parts of the program
according to various condition.
# include preprocessor directive:
Only defined at the top of the program definition and only white space and comments may appear
before preprocessor directive line.This directive includes a copy of the specified file or library. And is
written like so-
#include<filename>
Or #include “file name”
If included inside <> then the compiler looks for the file in an implementation defined manner (or
system directory paths).
If included inside a quote “ ” statement then it searches for the file in the same directory as the program
being written.
So if we include a file named file1 while writing a program name code.c which is being stored in a
folder called test. Then inclusion like so -- #include “file1”
Will tell the compiler to look for the file inside the test folder, It looks at neighboring folders or
subfolders too but it starts its search in the test folder.(This sub search option is compiler dependent).
Int maint(){
Char array[BUFFER_SIZE] = [0];
Int I = 9;
Printf(“%d”,i);
Printf(“%s”,array);
Return 0;
}//end main body
Conditional Compilation:
Conditional compilation enables the coder to control the execution of preprocessor directives and
the compilation of program code.
->Conditional preprocessor directives evaluate constant integer expressions.The ones that cannot
be evaluated in preprocessor directives are sizeof expressions and enumeration constants.
Every #if construct ends with #endif
Example –
#if !defined(MY_CONSTANT) #define
MY_CONSTANT 0
#endif
10 (a) Write the syntax for opening a file and closing a file? (CO 3 BT-1)
Ans) FILE:A file is an external collection of related data treated as a unit. The primary purpose of a file is to keep
a record of data. Files are stored in auxiliary or secondary storage devices .Buffer is a temporary storage area that
holds data while they are being transferred to or from memory.
Declare a file pointer variable.
FILE *file_pointer_name;
Eg: FILE *fp;
Streams
A stream can be associated with a physical device, such as a terminal, or with a file stored in auxiliary
memory.
Text and Binary Streams
C uses two types of streams: text and binary .A text stream consists of characters divided into lines with
each line terminated by a newline(\n).A binary stream consists of data values such as integer, real or
complex.
Creating a Stream
We create a stream when we declare it. The declaration uses the FILE type as shown in the following
example the FILE type is a structure that contains the information needed for reading and writing a file.
FILE *file_pointer_name;
Eg: FILE *fp;
In this example,*fp is a pointer to the stream.
Opening a File
When the file is opened, the stream and the file are associated with each other and the FILE type is filled
with the pertinent file information. The open function returns the address of the file type, which is stored
in the stream pointer variable,*fp .
Using the Stream Name
After we create the stream, wecanusethestreampointerinallfunctionsthatneedtoaccessthecorresponding file
for input and output.
Closing the Stream
When the File processing is complete, we close the file. Closing the association between the stream name
and file name. After the close, the stream is no longer available and any attempt to use it results in an
error.
File Modes
R Open a text file for reading.
W Create a text file for writing .If the file exists, it is overwritten.
A Open a text file in append mode. Text is added to the end of the file.
Rb Open a binary file for reading.
Wb Create a binary file for writing. If the file exists, it is overwritten.
Ab Any file in append mode. Data is added to the end of the file.
r+ Open a text file for reading and writing.
w+ Create a text file for reading and writing. If the file exists, it is overwritten.
a+ Open a text file for reading and writing at the end.
r+b O
+ pen binary file for reading and writing.
w+b C
+ reate a binary file for reading and writing .If the file exists, it is overwritten.
a+b O
+ pen a text file for reading and writing at the end.
The update modes are used with fseek,fset pos and rewind functions. The fopen function return s a file
pointer, or NULL if an error occurs.
The following example opens a file, tarun.tx tin read-only mode .It is good programming practice to test
the file exists.
if((in=fopen("tarun.txt","r"))== NULL)
{
puts("Unable to open the file");
return0;
}
11a) Explain about files and with it types of file processing? (CO 3 BT-2)
Ans) Files: As we know that Computers are used for storing the information for a Permanent Time or the
Files are used for storing the Data of the users for a Long time Period. And the files can contains any type
of information means they can Store the text, any Images or Pictures or any data in any Format. So that
there must be Some Mechanism those are used for Storing the information, Accessing the information and
also Performing Some Operations on the file There are Many files which have their Owen Type and own
names. When we Store a File in the System, then we must have to specify the Name and the Type of File.
The Name of file will be any valid Name and Type means the application with the file has linked.
So that we can say that Every File also has Some Type Means Every File belongs to Special Type of
Application software‘s. When we Provides a Name to a File then we also specify the Extension of the File
because a System will retrieve the Contents of the File into that Application Software. For Example if
there is a File Which Contains Some Paintings then this will Opened into the Paint Software.
1) Ordinary Files or Simple File: Ordinary File may belong to any type of Application for example
notepad, paint, C Program, Songs etc. So all the Files those are created by a user are Ordinary Files.
Ordinary Files are used for Storing the information about the user Programs. With the help of Ordinary
Files we can store the information which contains text, database, any image or any other type of
information.
2) Directory files: The Files those are Stored into the a Particular Directory or Folder. Then these are
the Directory Files. Because they belongs to a Directory and they are Stored into a Directory or Folder.
For Example a Folder Name Songs which Contains Many Songs So that all the Files of Songs are known
as Directory Files.
3) Special Files: The Special Files are those which are not created by the user. Or The Files those are
necessary to run a System. The Files those are created by the System. Means all the Files of an Operating
System or Window, are refers to Special Files. There are Many Types of Special Files, System Files, or
windows Files, Input output Files. All the System Files are Stored into the System by using. sys Extension.
4) FIFO Files: The First in First Out Files are used by the System for Executing the Processes into
Some Order. Means To Say the Files those are Come first, will be Executed First and the System
Maintains a Order or Sequence Order. When a user Request for a Service from the System, then the
Requests of the users are Arranged into Some Files and all the Requests of the System will be performed
by the System by using Some Sequence Order in which they are Entered or we can say that all the files or
Requests those are Received from the users will be Executed by using Some Order which is also called as
First in First Out or FIFO order
Types of File Operations
Files are not made for just reading the Contents, we can also Perform Some other operations on the Files
those are Explained below As :
1) Read Operation: Meant To Read the information which is Stored into the Files.
2) Write Operation: For inserting some new Contents into a File.
3) Rename or Change the Name of File.
4) Copy the File from one Location to another.
5) Sorting or Arrange the Contents of File.
6) Move or Cut the File from One Place to Another.
7) Delete a File
8) Execute Means to Run Means File Display Output.
b. ftell():
This function returns the value of the current pointer position in the file. The value is count from the
beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.
c. rewind():
This function is used to move the file pointer to the beginning of the given file.
Syntax: rewind (fptr);
where fptr is a file pointer.
d. ferror():
The macro ferror() is used for detecting whether an error occur in the file on file pointer or not .It returns
the value nonzero if an error ,otherwise it returns zero.
Syntax: ferror(fptr);
Where fptr is a file pointer.
12. a) Write a C program to read name and marks of n number of students from user and store
them in a file. (CO 3 BT-4)
Ans)
#include<stdio.h>
#include<conio.h>
Int main (){
Char name [50];
Int marks,i,n;
Printf("Enter number of students:");
scanf ("%d" ,&n);
FILE*fptr;
fptr=(fopen("C:\\student.txt","w"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student %d\nEntername:",i+1);
scanf("%s" ,name);
printf("Enter marks:");
scanf("%d",& marks);
fprintf(fptr,"\n Name:%s\n Marks=%d\n" ,name, marks);
}
fclose(fptr);
return0;
}
12.b)Explain about Sequential and Random Access File Handling in C? (CO 3 BT-2)
Ans) Sequential and Random Access File Handling in C
A file handling in C tutorial detailing the use of sequential and random access files in C, along with
examples of using the fseek, ftell and rewind functions.
In computer programming, the two main types of file handling are:
• Sequential;
• Random access.
Sequential files are generally used in cases where the program processes the data in a sequential fashion –
i.e. counting words in a text file – although in some cases, random access can be affected by moving
backwards and forwards over a sequential file.
True random access file handling, however, only accesses the file at the point at which the data should be
read or written, rather than having to process it sequentially. A hybrid approach is also possible whereby a
part of the file is used for sequential access to locate something in the random access portion of the file, in
much the same way that a File Allocation Table (FAT) works.
The three main functions that this article will deal with are:
13 a). Write a C program to copy the contents from one file to another file? (CO 3 BT-4)
Ans)#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr1, *fptr2;
Char ch, fname1[20], fname2[20];
printf("\n\n Copy a file in another name :\n");
printf(" Input the source file name : ");
scanf("%s",fname1);
fptr1=fopen(fname1, "r");
if(fptr1==NULL)
{
printf(" File does not found or error in opening.!!");
exit(1);
}
printf(" Input the new file name : ");
scanf("%s",fname2);
fptr2=fopen(fname2, "w");
if(fptr2==NULL)
{
printf(" File does not found or error in opening.!!");
fclose(fptr1);
exit(2);
}
while(1)
{
ch=fgetc(fptr1);
if(ch==EOF)
{
break;
}
else
{
fputc(ch, fptr2);
}
}
printf(" The file %s copied successfully in the file %s. \n\n",fname1,fname2);
fclose(fptr1);
fclose(fptr2);
getchar();
}
Output:
Copy a file in another name:
Input the source file name: test.txt
Input the new file name: test1.txt
The file test.txt copied successfully in the file test1.txt.
13. b) Write a C program to count number of characters, words of a file. (CO 3 BT-4)
Ans)
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr;
Char ch;
int wrd=1,charctr=1;
char fname[20];
printf("\n\n Count the number of words and characters in a file :\n");
printf(" Input the filename to be opened : ");
scanf("%s",fname);
fptr=fopen(fname,"r");
if(fptr==NULL)
{
printf(" File does not exist or cannot be opened.");
}
else
{
ch=fgetc(fptr);
printf(" The content of the file %s are : ",fname);
while(ch!=EOF)
{
printf("%c", ch);
if(ch==' '||ch=='\n')
{
wrd++;
}
else
{
Char ctr++;
}
ch=fgetc(fptr);
}
printf("\n The number of words in the file %s are : %d\n",fname,wrd-2);
printf(" The number of characters in the file %s are : %d\n\n",fname,charctr-1);
}
fclose(fptr);
}
Output:
Count the number of words and characters in a file :
Input the filename to be opened : test.txt
The content of the file test.txt are :
test line 1
test line 2
test line 3
test line 4
The number of words in the file test.txt are : 12
The number of characters in the file test.txt are : 36
14 a) Write a program in C to append multiple lines at the end of a text file. (CO 3 BT-4)
#include <stdio.h>
int main ()
FILE * fptr;
Int i,n;
Char str[100];
Char fname[20];
char str1;
scanf("%s", fname);
scanf("%d", &n);
fputs(str, fptr);
fclose (fptr);
str1 = fgetc(fptr);
printf("\n\n");
fclose (fptr);
return 0;
Output:
test line 5
test line 6
test line 7
test line 1
test line 2
test line 3
test line 4
test line 5
test line 6
test line 7
14 b) Write short notes on
i.fgets() ii. fputs() iii. fprintf () iv.fscanf() (CO 3 BT-3)
i) fgets (): The C library function char *fgets (char *str, int n, FILE *stream) reads a line from the
specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are
read, the newline character is read, or the end-of-file is reached, whichever comes first.
char*fgets(char*str, int n, FILE *stream)
str − This is the pointer to an array of chars where the string read is stored.
n − This is the maximum number of characters to be read (including the final null-character).
Usually, the length of the array passed as str is used.
ii) fputs():
The C library function int fputs (const char *str, FILE *stream) writes a string to the specified stream
up to but not including the null character.
Declaration: intfputs(const char*str, FILE *stream)
str − This is an array containing the null-terminated sequence of characters to be written.
stream − This is the pointer to a FILE object that identifies the stream where the string is to be
written.
The fprintf and fscanf functions are identical to printf and scanf functions except that they work on files.
The first argument of these functions is a file pointer which specifies the file to be used. The general form
of fprintf is
fprintf(fp,”control string”, list);
Where fp id a file pointer associated with a file that has been opened for writing. The control string is file
output specifications list may include variable, constant and string.
fprintf(f1,%s%d%f”,name,age,7.5);
Here name is an array variable of type char and age is an int variable The general format of fscanf is
fscanf(fp,”control string” ,list);
This statement would cause the reading of items in the control string.
Example:
#include <stdio.h>
Int main()
{
FILE*fp;
file = fopen("file.txt","w");
fprintf(fp,"%s", "This is just an example:)");
fclose(fp);
return0;
}
Variables
Variables defined in the stdio.h header include:
Name Notes
Stdin A pointer to a FILE which refers to the standard input stream, usually a keyboard.
A pointer to a FILE which refers to the standard output stream, usually a display
Stdout
terminal.
a pointer to a FILE which refers to the standard error stream, often a display terminal.
Stderr
15) Explain how to create a binary file and store structures in a binary with an example program?
(CO 3 BT-2)
Ans)
Program to store structure data into a binary file and display on the output screen
#include<stdio.h>
struct Employee
{
char name[40];
int age;
float bs;
};
int main( )
{
FILE *fp = fopen("employee.dat", "wb");
char ch = 'Y';
struct Employee e;
//reading employee detail from user and storing them in a binary file
while (ch == 'Y')
{
printf("Enter name, age and basic salary: ");
scanf("%s %d %f", e.name, &e.age, &e.bs);
fwrite(&e, sizeof(struct Employee), 1, fp);
printf("Add another record (Y/N) ");
fflush(stdin);
ch=getchar();
}
fclose(fp);
if(fp2 == NULL)
{
puts("Cannot open file");
return 0;
}
printf("\nFile content:\n");
while(fread(&e, sizeof(e), 1, fp2) == 1)
{
printf ("%s %d %.2f\n", e.name, e.age, e.bs);
}
fclose(fp2);
Output:
Enter name, age and basic salary: Ram 45 65000
Add another record (Y/N) Y
Enter name, age and basic salary: Shyam 28 48000
Add another record (Y/N) Y
Enter name, age and basic salary: Sita 30 52000
Add another record (Y/N) N
File content:
Ram 45 65000.00
Shyam 28 48000.00
Sita 30 52000.00