You are on page 1of 36

INTRODUCTION

Storage of data in variables and arrays is temporary- all such data are lost when a program
terminates. Files are used for permanent maintenance of large amounts of data. Computers store
files on secondary storage devices, especially on disks. Usually, a file is a collection of related
records. Each record is a collection of data items (or fields). E.g., a company maintains employee
payroll file, which stores records about the salaries paid to all employees. Each record in that file
may include the fields like empno, name, department, salary … etc. All these records in payroll file
should be organized in such a way that each record should be retrieved very easily.
To facilitate the retrieval of specific records from a file, at least one field in each record is
chosen as a record key. A record key identifies a record as belonging to a particular person or
entity. E.g., empno in payroll file is used to retrieve the specific record easily.

What is a file?
“A file is a collection of data that is stored permanently on disk”.
(or)
“A file is a stream of bytes of arbitrary length, which is used to hold data”.
A file is a sequence of bytes that will be implemented by the operating system to provide
persistent (or permanent) storage. Each file is owned by some user and is protected from
unauthorized use by other users. File provides reliable data storage and it will provide simple,
easy-to-use operations to access data.

Why do we need files?


We need files in order
1. To store data permanently. i.e., the content in the file can never be lost even after
program termination.
2. To maintain large amount of data. i.e., it is easy to handle voluminous data during
execution.
3. To make disk user-friendly. i.e., the complex interface of disk can be converted to user-
friendly interface by using file so that user can interact with it.
4. To have its storage capacity more. i.e., a file can have its content till there is no space in
storage device.

1
Types of files

Types of Files

Stream-oriented Files System-oriented Files


(Standard) (Low-level)

Text Files Binary Files


(Formatted) (Unformatted)

There are two ways to link and access files in a program. These are: by means of library functions
and by means of system-calls of operating system.
1. The files linked and accessed through the library functions are known as stream-oriented
files. These are also called as high-level files, since these involve high-level (programming
language level) functions.
2. It is also possible to link and access files directly by means of an operating system. The
system calls of operating system connect the files with the program. The files linked and
accessed using system calls known as system-oriented files. These are also known as low-
level files because low-level (system level) commands or functions are involved.

Stream-oriented files are supported by C library functions which are common for all operating
systems. But system-oriented files are not at all common to all operating systems because system
calls for each operating system are different.

Stream-oriented files are easier to work with than the system-oriented files because the same
library functions may be used regardless of the device or disk files are involved. Also, the data can
be stored in a manageable form such as one byte at a time.

Stream-oriented files can be subdivided into two categories: text files and binary files. The text
files consist of consecutive characters. These characters can be interpreted as individual data items
or as components of strings or numbers. The manner in which these characters are interpreted is
determined either by the particular library functions used to transfer the information, or by the
format specifiers those start with % with in the library function.

The binary files organize data into blocks containing contiguous bytes of information. These blocks
represent more complex data structures such as arrays and structures. A separate set of library

2
functions is available for processing these binary files. These library functions provide single
instructions that can transfer entire arrays or structures to or from files. These binary files are very
useful to handle file containing machine language contents, e.g., .exe or .com files.

To understand the stream-oriented files, first, it is necessary to understand the concept of stream.

What do you mean by a stream?


The ANSI standard I/O functions support the stream-oriented files in which input and output are
treated as a continuous stream of bytes. A stream is a source or destination of data that may be
associated with a disk or other I/O devices. The source stream provides data to a program and it is
known as input stream. The destination stream receives the output from the program and is known as
output stream. The generic term I/O stream is used for any file, device or facility on which a
program may perform I/O operations.
An I/O stream can be treated as a flowing sequence of characters. It can be a text stream or
binary stream. A text stream is a sequence of lines of text. In a text stream, each character can be
represented by using ASCII. Each line consists of zero or more characters and a terminating new line
character. ANSI C allows atleast 254 characters in a line. The characters in a text stream may be
modified, added or deleted during I/O operations. A file that contains data written using a text stream
is called a text file. Input from/output to a terminal are mostly performed using text streams. Hence, a
terminal is also associated with the I/O streams in text file.
A binary stream is a sequence of unprocessed bytes. A binary stream, represents raw data
without any conversion unlike a text stream. For example, the character ‘\n’ in a text stream is mapped
to carriage return and line feed. But, in a binary stream, it is never modified. If the data are only stored
as backup for the purpose of reading them afterwards, it is more efficient in using binary streams. A
All the stream-oriented files (whether text files or binary files) are of two types based on the way of
binary file contains data written in it using binary stream.
accessing them. Sequential-access files are the stream-oriented files in which the data can be
accessed sequentially. E.g., if a file contains 100 records and we want to access 57 th record in that
file. Then we should first access all the previous 56 records in sequence and then only we can access
57th record.

Random-access files are the stream-oriented files in which the data can be accessed
directly. E.g., if a file contains 100 records and we want to access 57 th record in that file, then it is
not necessary to access all the previous 56 records first. We can directly place our file pointer to 57 th
record directly. The random-access files are called as direct-access files.

In order to process the sequential-access file, first we should learn basic operations on files:

BASIC OPERATIONS ON FILES


The standard library in C has many file I/O functions. The file-handling functions in C are easy to
use, powerful and complete. The console I/O functions such as scanf() and printf() help the user

3
to read from keyboard and write to monitor (The term console refers to keyboard-monitor pair). But
the file I/O functions read from a file and write to a file (or to the same file).
File I/O is always done in a program in the following sequence:
1. Open the file.
2. Read from or write to the file.
3. Close the file.
A) Opening files:
Before performing any file I/O, the file must be opened. While opening the file, the following are to
be specified:
 The name of the file and
 The manner (or mode) in which it should be opened (i.e., for reading, writing, reading and
writing, appending at the end of file, or overwriting the file …etc).
The function fopen() is used to open a file. It accepts two strings as arguments with the following
form:
FILE *fopen(filename,mode);

From this prototype, it is clear that the function fopen() has:


Arguments:
o file name is the name of the file to opened. As it is a string, it should be enclosed with in
double quotation marks. If we want to specify the full path name for the file, we should use
double backslash (as in DOS) or a single front slash (as in UNIX).
o mode is used to specify the manner in which a file should be opened. As it is a string, it
should be enclosed with in double quotation marks. The possible modes are:
File Opening Mode Meaning

r (read-only) Open an existing file for reading only.


w(write-only) Open a new file for writing only. If a file with specified filename currently exists,
it will be destroyed and a new file with the same name will be created in its
place.
a (append-only) Open an existing file for appending (i.e., for adding new information at the end
of file). A new file will be created if the file with the specified filename does not
exist.
r+ (read & write) Open an existing file for update (i.e., for both reading and writing).
w+ (write & read) Open a new file for both writing and reading. If a file with the specified filename
currently exists, it will be destroyed and a new file will be created in its place.
a+(append & Open an existing file for both appending and reading. A new file will be created
read) if the file with specified filename does not exist.
Return value:
 On success, fopen() returns a pointer to the predefined structure FILE, whose definition is
available in stdio.h.
 On failure, it returns NULL.
Ex: FILE *fp; //statement-1
fp=fopen(“sample.txt”,”w”); //statement-2
if(fp==NULL) //statement-3
{
printf(“\n Unable to open a file”);
exit(0);
}
In this example,
Statement-1 declares fp, the pointer to the structure FILE.
4
Statement-2 helps us in opening the file sample.txt in writing mode. If there is no file with name
sample.txt in the current directory, then it is created. If already exists, then its content will be
erased and the file is ready for writing the new content. As fopen() returns pointer to the structure
FILE, it is handled with the pointer fp. This pointer will be very helpful in subsequent operations such
as read,write…etc.
Statement-3 helps us to handle the failed situation of fopen(). If it is not handled, then there will
be problems such as system crash.

B) Writing to files:
The functions printf(), puts() and putchar() are used to write the content to monitor. To write to
a file, the functions fprintf(), fputs() and fputc() are used. All these functions accept a file pointer
as one of the parameters along with other parameters required by the standard output functions.
1) Writing a character to a file: To write a character to a file, do the following:
 Open the existing file in “w”,“w+”,”a” or “a+” mode using fopen() and handle the file
pointer that is returned.
 Read the character from keyboard using getchar() or scanf().
 Input that character as an argument to the function fputc() along with the file pointer
as follows:

int fputc(character,pointer_to_FILE);

From this prototype, it is clear that:


o fputc() takes two arguments: a character that is to be written to file and
pointer to the structure FILE.
o On success, it returns an unsigned integer. Otherwise, it returns EOF.
Ex: FILE *fp;
char ch;
fp=fopen(“sample.txt”,”w”); //step-1:open file in writing mode
printf(“\n Enter the text to the file (ctrl+d to end):”);
ch=getchar(); //step-2: reads a character from keyboard
while(ch!=EOF) //write character-by-character till the end-of-file is reached
{
fputc(ch,fp); //step-3
ch=getchar();
}

2) writing a String to a file: To write a string to the file, do the following:

 Open the existing file in “w”,“w+”,”a” or “a+” mode using fopen() and handle the file
pointer that is returned.
 Read the string from keyboard using gets() or scanf().
 Input that string as an argument to the function fgets() along with the file pointer as
follows:
int fputs(string,pointer_to_FILE);

From this prototype, it is clear that:


o fputs() takes two arguments: first argument is a string that is to be written to the
file and second argument is file pointer.
5
o fputs() writes the string to the specified file. On success, it returns an unsigned
integer. On failure, fputs() returns EOF.
Ex: FILE *fp;
char str[25];
fp=fopen(“normal.txt”,”w”); //step-1
printf(“\n Enter any string to write to the file:”);
scanf(“%s”,str); //step-2
fputs(str,fp); //step-3

3) writing formatted data to a file: To write formatted data from a file do the following:

 Open the existing file in “w”,“w+”,”a” or “a+” mode using fopen() and handle the file
pointer that is returned.
 Read the formatted data from keyboard using scanf().
 Input that formatted data to function fscanf() along with the file pointer as follows:

fprintf(pointer_to_FILE,<format string>,< variables>);

From this prototype, it is clear that:


o fprintf() is same as printf(), except that it accepts a file pointer as first argument.
o On success, it returns the number of bytes output. Otherwise, it returns EOF.

Ex: struct student


{
int rno,rank;
float fees;
char name[15];
}s1;
FILE *fp;
fp=fopen(“student.dat”,”w”); //step-1:open file in write mode
printf(“\n Enter student details( rno,name,rank and fees):”);
scanf(“%d%s%d%f”,&s1.rno,s1.name,&s1.rank,&s1.fees); //step-2
fprintf(fp,”%d\t%s\t%d\t%f”,s1.rno,s1.name,s1.rank,s1.fees); //step-3

c) Reading from files:


The functions scanf(), gets() and getch() are used to read content from the keyboard. To read
from a file, the functions fscanf(), fgets() and fgetc() are used. All these functions accept a FILE
pointer as one of the parameters along with other parameters required by the standard input
functions.

1) Reading a character from a file: To read a character from a file, do the following:
a. Open the existing file in “r” or “r+” mode using fopen() and handle the file pointer
that is returned.
b. Use the function fgetc() that is used to read a character from file which has the
following prototype:

int fgetc(pointer_to_FILE);
From this prototype it is clear that:

6
o fgetc() takes an argument which is a pointer to the structure FILE and returns
an unsigned integer value that should be converted to a character. We should
place that file pointer which is already returned by using fopen().
o When end-of-file is reached or there is an error, the predefined character EOF
is returned.
Ex: FILE *fp;
char ch;
fp=fopen(“sample.txt”,”r”); //step-a
ch=fgetc(fp); //step-b
while(ch!=EOF) //read character-by-character till the end-of-file is reached
{
printf(“%c”,ch);
ch=fgetc(fp);
}
2) Reading a String from a file: To read a string from the file, do the following:

a. Open the existing file in “r” or “r+” mode using fopen() and handle the file pointer
that is returned.
b. Use the function fgets() that is used to read a string of specified length from file
which has the following form:

char * fgets(string,size,pointer_to_FILE);

From this prototype it is clear that:


o fgets() takes three arguments: first argument is a string, second argument is used
to specify the size of string that is to be read and third argument file pointer.
o fets() reads the next line from the specified file. On success, the string of specified
size that is read will be stored in the first argument. On failure, fgets() returns
NULL.

Ex: FILE *fp;


char *str=””; //initialize with empty string
fp=fopen(“sample.txt”,”r”); //step-a
fgets(str,10,fp); //step-b: str holds the string that is read from file
printf(“%s”,str); //prints the string to monitor.

3) Reading formatted data from a file: To read formatted data from a file do the following:

a. Open the existing file in “r” or “r+” mode using fopen() and handle the file pointer
that is returned.
b. Use the function fscanf() that is used to read formatted data (i.e., different forms of
data at a time) from file which has the following prototype:

fscanf(pointer_to_FILE,<format string>,<addresses of variables>);

From this prototype it is clear that:


o fscanf() is same as scanf(), except that it accepts a file pointer as first argument.
7
o On success, it returns the number fields successfully scanned, converted and
stored. On failure, it returns 0, if no fields are stored.

Ex: struct student


{
int rno,rank;
float fees;
char name[15];
}s1;
FILE *fp;
fp=fopen(“student.dat”,”r”); //step-a:open file in read mode
fscanf(fp,”%d%s%d%f”,&s1.rno,s1.name,&s1.rank,&s1.fees); //step-b
printf(“\nRoll number=%d”,s1.rno);
printf(“\n Name=%s”,s1.name);
printf(“\n Rank=%d”,s1.rank);
printf(“\n Fees=%.2f”,s1.fees);

D) Closing a file: During a write to a file, the data written to it is not put on the disk immediately.
It is stored in a buffer (a temporary storage area in primary memory). When the buffer is full or the
program gets ended, all the content in buffer is actually written back to the disk. The process of
emptying the buffer by writing its content back to disk is called flushing the buffer.
Closing a file flushes the buffer and releases the space taken by FILE structure which is
returned by fopen(). If we want to close a file, pass its file pointer to the function fclose() that has
the following form:

int fclose(pointer_to_FILE);

From this prototype, it is clear that:


o fclose() function takes one argument: the file pointer to which we want to close.
o On success, it returns 0. on failure, it returns EOF.
Ex: FILE *fp;
fp=fopen(“sample.txt”,”w”);
…………..
………….
fclose(fp); //closes the file sample.txt

8
What are pre-defined streams?
stream Meaning
stdin Standard input device (opened for input).
stdout Standard output device (opened for output).
stderr Standard error output device (opened for error output).
The output of a function like printf() goes to the stream stdout. A function like scanf() receives
its input from the stream stdin. We can write to any of the output streams by using functions
like fputc(),fputs()…etc and read from any of input streams by using functions like
fgetc(),fgets()…etc. These streams are considered to be files. Usually, stdin is connected to the
keyboard, stdout and stderr are connected to monitor, stdaux is connected to serial port com1
and stdprn is connected to lpt1.
Write a program to create a file, write some text to it and print that text on monitor.
#include<stdio.h>
main()
{
char filename[15],ch;
FILE *fp;
printf(“\n Enter the file name to be created:”);
scanf(“%s”,filename);
fp=fopen(filename,”w”); //first, open file in write mode
if(fp==NULL)
{
printf(“\n unable to open”);
exit(0);
}
printf(“\n Enter some text to file (ctrl+d to end):”);
ch=getchar(); //read a character from key board
while(ch!=EOF) // check that the entered character is not ctrl+d
{
fputc(ch,fp); //write that character to file
ch=getchar(); //again, read a character from key board
}
fclose(fp); // close the file

fp=fopen(filename,”r”); //open the same file in read mode


if(fp==NULL)
{
printf(“\n unable to open”);
exit(0);
}
printf(“\n The content of file %s is:”,filename);
ch=fgetc(fp); //get a character from file
while(ch!=EOF) // check the character is not EOF
{
printf(“%c”,ch); //print that character on monitor
ch=fgetc(fp);
}
fclose(fp); //close the file
}
Output:
Enter the file name to be created: master.txt
Enter some text to file (ctrl+d to end):
Master minds are not born. They are made.
But master minds are mad.
Master minds’ numbers consist of digits: 0-9
The persons who read this text are master minds
The content of file master.txt is:
Master minds are not born. They are made……
9
Program #2
Write a program to copy the content of one file to another.
#include<stdio.h>
main()
{
char source[15],destination[15],ch;
FILE *fp1,*fp2;
printf(“\n Enter the an existing file name to be opened:”);
scanf(“%s”,source);
printf(“\n Enter the file name to which the content should be copied”);
scanf(“%s”,destination);
fp1=fopen(source,”r”); //open source file in read mode
if(fp1==NULL)
{
printf(“\n unable to open”);
exit(0);
}
fp2=fopen(destination,”w”); //open destination file in write mode
if(fp2==NULL)
{
printf(“\n unable to open”);
exit(0);
}

ch=fgetc(fp1); //get a character from source file


while(ch!=EOF) // check that character is not EOF
{
fputc(ch,fp2); //write that character to destination file
ch=fgetc(fp1); //Again, read a character from source file
}
fclose(fp); //close the file
}
Output:
Enter an existing filename to be opened: master.txt
Enter the file name to which the content should be copied: copy.txt
Usually, the content of first file is copied to second file. To check the correctness of program, type
the destination file name by using vi command at $ prompt. If we get the content of source file in
destination file, the program is absolutely correct.

What is the purpose feof()?


The feof() is a pre-defined macro that checks the given stream for an end-of-file indicator. It

int feof(pointer_to_FILE);
has the following form:
From this prototype, it is clear that:
o feof() function takes one argument: the file pointer to which we want to search for
EOF character.
o On success, it returns non-zero if an end-of-file character is detected. If end-of-file is
not reached, then it returns 0.

10
Program #3
Write a program to count number of characters, alphabets, digits, white spaces and
special symbols in an existing file.
#include<stdio.h>
main()
{
char filename[15],ch;
FILE *fp;
int ccount,acount,dcount,scount,sscount;
printf(“\n Enter an existing file name to be read:”);
scanf(“%s”,filename);
fp=fopen(filename,”r”); //open an existing file in read mode
if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
ccount=acount=dcount=scount=sscount=0; //initially, all counts are 0
ch=fgetc(fp); //read a character from file
while(ch!=EOF)
{
ccount++; //increment character count by 1
if(toupper(ch)>=’A’ &&toupper(ch)<=’Z’) //if it is alphabet
acount++; //increment alphabet count by 1
else if(ch>=’0’ && ch<=’9’) //if it is digit
dcount++; //increment alphabet count by 1
else if(ch==’ ‘ || ch==’\t’ || ch==’\n’) //if it is white space
scount++; //increment space count by 1
else
sscount++; //increment special symbol count by 1
ch=fgetc(fp); //again, read a character from file
}
fclose(fp); //close the file
printf(“\n No.of characters=%d”,ccount);
printf(“\n No.of Alphabets=%d”,acount);
printf(“\n No.of digits=%d”,dcount);
printf(“\n No.of spaces=%d”,scount);
printf(“\n No.of special symbols=%d”,ccount);
}
Output:
Enter an existing filename to be read: master.txt
No.of characters=160
No.of Alphabets=122
No.of digits=2
No.of spaces=30
No.of special symbols=6

11
Program #4
Write a program to write student records to a sequential file and access them
#include<stdio.h>
struct student
{
int rno,rank;
char name[15];
float fees;
struct date_of_birth
{
int day,month,year;
}dob;
}s1;
main()
{
FILE *fp;
char ch;
fp=fopen(“sturecords”,”w”); //create a new file
if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
do
{
printf(“\nEnter student details (rno,name,rank,fees and date of birth):”);
scanf(“%d%s%d%f%d%d
%d”,&s1.rno,s1.name,&s1.rank,&s1.fees,&s1.dob.day,&s1.dob.month,&s1.dob.year); //read the student
record from keyboard
fprintf(fp,”%d\t%s\t%d\t%f\t%d/%d/%d”,s1.rno,s1.name,s1.rank,s1.fees,s1.dob.day,
s1.dob.month,s1.dob.year); //write the student record to file
printf(“\n Do u want to add one more record (y/n):”);
scanf(“\n%c”,&ch);
}while(toupper(ch)!=’N’);
fclose(fp);

fp=fopen(“sturecords”,”r”); //open the file in read mode


if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
printf(“\n content of sturec file:”);
while(fscanf(fp, ”%d\t%s\t%d\t%f\t%d/%d/%d”,&s1.rno,&s1.name,&s1.rank,&s1.fees,&s1.dob.day,
&s1.dob.month,&s1.dob.year)!=EOF) //read a record from file
{
printf(”\n%d\t%s\t%d\t%f\t%d/%d/%d”,s1.rno,s1.name,s1.rank,s1.fees,s1.dob.day,
s1.dob.month,s1.dob.year); //print the record onto monitor
}
fclose(fp);
}
Output:
Enter student details (rno, name ,rank ,fees and date of birth):1
Mercylin
193
27500.00
29
2
1990
Do you want to add one more record (y/n):n
Content of sturec file:
1 Mercylin 193 27500.00 29/2/1990

12
The above program has one disadvantage: if the members of structure are increased, the functions
fprintf() and fscanf() become difficult to understand. To solve this problem, fwrite() and fread()
functions are introduced.
 The function fwrite() is used to write formatted data to the file. It has the following form:

size_t fwrite(ptr,size,n,pointer_to_FILE);

From this prototype, it is clear that:


o fwrite() takes four arguments: ptr is a pointer to the data that is to be written. Size is
a value of type size_t, an unsigned integer, used to hold the size of data that is to be
written. n is a value of type size_t, an unsigned integer, used to hold number of data
items to be appended. Pointer_to_FILE is the pointer to the file in which the data is
to be written.
o On success, it returns the number of items (not bytes) actually written. on failure, it
returns a short count (possibly zero).
Ex: struct student s1;
fwrite(&s1,sizeof(s1),1,fp);

 The function fread() is used to read formatted data from the file. It has the following form:

size_t fread(ptr,size,n,pointer_to_FILE);
From this prototype, it is clear that:
o fread() takes four arguments: ptr is a pointer to the block into which data is read.
Size is a value of type size_t, an unsigned integer, used to hold the length of each
item read, in bytes. n is a value of type size_t, an unsigned integer, used to hold
number of data items to read. Pointer_to_FILE is the pointer to the file in which the
data is to be read.
o On success, it returns the number of items (not bytes) actually read. On end-of-file or
error, it returns 0.
Ex: struct student s1;
fread(&s1,sizeof(s1),1,fp);

By using fread() and fwrite() functions, fixed-length records are written or read. By using fprintf()
and fscanf() functions, variable-length records are written or read.

By using fread() and fwrite(), the above program can be modified as follows:

13
Program #5
Write a program to write student records to a sequential file and access them
#include<stdio.h>
struct student
{
int rno,rank;
char name[15];
float fees;
struct date_of_birth
{
int day,month,year;
}dob;
}s1,s2;
main()
{
FILE *fp;
char ch;
fp=fopen(“sturecords”,”w”); //create a new file
if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
do
{
printf(“\nEnter student details (rno,name,rank,fees and date of birth):”);
scanf(“%d%s%d%f%d%d
%d”,&s1.rno,s1.name,&s1.rank,&s1.fees,&s1.dob.day,&s1.dob.month,&s1.dob.year); //read the student
record from keyboard
fwrite(&s1,sizeof(s1),1,fp); //write the student record to file
printf(“\n Do u want to add one more record (y/n):”);
scanf(“\n%c”,&ch);
}while(toupper(ch)!=’N’);
fclose(fp);

fp=fopen(“sturecords”,”r”); //open the file in read mode


if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
printf(“\n content of sturec file:”);
while(!feof(fp)) //read a record from file
{
fread(&s2,sizeof(s2),1,fp);
printf(”\n%d\t%s\t%d\t%f\t%d/%d/%d”,s2.rno,s2.name,s2.rank,s2.fees,s2.dob.day,
s2.dob.month,s2.dob.year); //print the record onto monitor
}
fclose(fp);
}
Output:
Enter student details (rno, name ,rank ,fees and date of birth):1
Mercylin
193
27500.00
29
2
1990
Do you want to add one more record (y/n):n
Content of sturec file:
1 Mercylin 193 27500.00 29/2/1990

14
15.3. RANDOM - ACCESS FILES
Random-access files are the stream-oriented files in which the accessing of data is done at any
position. That is the data should be written to or read from any position in the specified file. To
move the position pointer in the file, three functions are very helpful:
1. fseek()- places the position pointer at the specified position.
2. rewind()- places the position pointer to the beginning of the file.
3. ftell()- tells the current position of the position pointer in the file.

fseek() function: The fseek() function is used to place the position pointer at the specified location
in the file. It has the following prototype:

int fseek(pointer_to_FILE,offset,location);

From this prototype, it is clear that:


o fseek() function takes three arguments: the first argument is the file pointer that points to
the file in which the position pointer should be placed. The second argument, a long integer
value, is the position at which the pointer should be placed. If it is positive value, the file
position pointer will be moved forward. If it is negative number, the file position pointer will
be moved back. The third argument takes one of the following three:
Constant value File location
SEEK_SET 0 Seeks from beginning of file.
SEEK_CUR 1 Seeks from current position.
SEEK_END 2 Seeks from end of file.
o On success, it returns 0. On failure, it returns a non-zero value. fseek() returns an error code
only when an unopened file or when a non-existing device is accessed.

rewind() function: The function rewind() is used to place the position pointer to the beginning of
the file. It has the following prototype:

void rewind(pointer_to_FILE);

From this prototype, it is clear that:


o rewind() function takes one argument: a pointer to the FILE in which we want to place the
position pointer at the beginning of the file.
The same operation can also be done using the function call:
fseek(pointer_to_FILE,0,0);

ftell() function: The function ftell() is used to get the current file position pointer. It has the
following prototype:

long ftell(pointer_to_FILE);

From this prototype, it is clear that:


o ftell() function takes one argument: file pointer.

15
o on success, it returns the current file pointer position. On error, it returns -1 and sets errno
to a positive value.
Program #6
Write a program to demonstrate fseek(), ftell() and rewind() functions
#include<stdio.h>
main()
{
FILE *fp;
char ch;
fp=fopen("stud.txt","w+");
if(fp==NULL)
{
printf("\n Unable to open file:");
exit(0);
}
printf("\n Enter the text into file (end with ctrl+d):");
ch=getchar();
while(ch!=EOF)
{
fputc(ch,fp);
ch=getchar();
}
ch=fgetc(fp);
while(ch!=EOF)
{
printf("%c",ch);
ch=fgetc(fp);
}
fseek(fp,5,SEEK_SET); //place the cursor at the position 5
printf("\n The cursor is at %d position",ftell(fp)); //tells the cursor position as 5
printf("\n Enter the character to insert:");
scanf("\n%c",&ch);
fputc(ch,fp); //inserts the character at specified position
ch=fgetc(fp);
while(ch!=EOF) //prints all the characters from specified position
{
printf("%c",ch);
ch=fgetc(fp);
}
rewind(fp); //places the cursor to the beginning of file
printf("\n The cursor is at %d position",ftell(fp));
fclose(fp);

}
Output:
Enter the text into file (end with ctrl+d):
pradeep is a good boy.

The cursor is at 5 position


Enter the character to insert:K
ep is a good boy.

The cursor is at 0 position


The content of stud.txt
pradKep is a good boy.

16
Program #7
Write a program to reverse the content of file.
#include<stdio.h>
main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen("sample.txt","w+");
if(fp1==NULL)
{
printf("\n Unable to open file:");
exit(0);
}
printf("\n Enter the text into file (end with ctrl+d):");
ch=getchar();
while(ch!=EOF)
{
fputc(ch,fp1);
ch=getchar();
}
fp2=fopen(“reverse.txt”,”w”);
fseek(fp1,0,2);
while(fseek(fp1,-2,1)= =0)
{
ch=fgetc(fp1);
putchar(ch);
fputc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
}
Output:
Enter the text into file (end with ctrl+d):
Files topic is easy one.
.eno ysae si cipot seliF (content of reverse.txt)

Program #8
Write a program to print the transpose of matrix in a file
#include<stdio.h>
main()
{
FILE *fp;
int i,j;
int matrix[2][3]={{1,2,3},{4,5,6}};
fp=fopen(“mat”,’w”);
fprintf(fp,”\t Transpose matrix\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
fprintf(fp,”%d\t”,matrix[j][i]);
fprintf(fp,”\n”);
}
fclose(fp);
}
Output:
Content of file “mat”
1 4
2 5
3 6

17
Program #9
Write a program to search for particular word in a file
#include<stdio.h>
#include<string.h>
main()
{
WriteFILE *fp;
a program to demonstrate a random-access file
char ch,temp[15],word[15],filename[15];
#include<stdio.h>
int count=0;
main()
{
printf("\n Enter file name:");
struct student
scanf("%s",filename);
{
fp=fopen(filename,"w");
int rno,rank;
printf("\n Enter
charthe text (end with ctrl+d):");
name[15];
ch=getchar(); float fees;
while(ch!=EOF) struct date_of_birth
{ {
fputc(ch,fp); int day,month,year;
ch=getchar();
}dob;
} }s1;
fclose(fp);
FILE *fp;
printf("\n
char ch; Enter the word to be searched:");
scanf("%s",word);
int sz,len,n,i;
fp=fopen(filename,"r");
fp=fopen(“sturecords”,”w”); //create a new file
//fscanf(fp,"%s",temp);
if(fp==NULL)
while(!feof(fp))
{
{ printf(“\n Unable to open file”);
fscanf(fp,"%s",temp);
exit(0);
}if(strcmp(temp,word)==0)
docount++;
} {
fclose(fp); printf(“\nEnter student details (rno,name,rank,fees and date of birth):”);
printf("\n The word %s is occured %d times",word,count);
scanf(“%d%s%d%f%d%d
}
%d”,&s1.rno,s1.name,&s1.rank,&s1.fees,&s1.dob.day,&s1.dob.month,&s1.dob.year); //read the student
Output:
record from keyboard
Enter the file name: sample.txt
fwrite(&s1,sizeof(s1),1,fp); //write the student record to file
Enter the text printf(“\n
into file (end with to
Do u want ctrl+d):
add one more record (y/n):”);
Mater minds are not made.
scanf(“\n%c”,&ch);
Master }while(toupper(ch)!=’N’);
minds are born.
Enter the fclose(fp);
word to be searched: minds
The word minds is occurred 2 times.
sz=sizeof(s1);
len=ftell(fp);
n=len/sz;
fp=fopen(“sturecords”,”r”); //open the file in read mode
if(fp==NULL)
What is { the purpose ferror()?
The ferror() is printf(“\n
a macro Unable to open
that tests thefile”);
given file pointer for a read or write error. It has the
exit(0);
following } prototype:
do
{ int ferror(pointe r_to_FILE);
printf(“\n Enter the record number to read (o to stop):”);
From this prototype,scanf(“%d”,&i);
it is clear that:
if(i>0 && i<=n)
o ferror(){ function takes one argument: the file pointer .
fseek(fp,(i-1)*sz,SEEK_SET);
o On success, it returns non-zero if an error is detected on the named file pointer.
fread(&s1,sz,1,fp);
printf(”\n%d\t%s\t%d\t%f\t%d/%d/%d”,s2.rno,s2.name,s2.rank,s2.fees,s2.dob.day,
s2.dob.month,s2.dob.year);

}
}while(i);
Program fclose(fp);
#10
}
18
Output:
Enter student details (rno,name,rank,fees and date of birth):
1 master 1 27500.00 12 3 1990
Do you want to add one more record (y/n):y
Enter student details (rno,name,rank,fees and date of birth):
2 maya 13 23500.00 11 9 2004
Do you want to add one more record (y/n):y
Enter student details (rno,name,rank,fees and date of birth):
3 maneesha 14 22500.00 23 3 1982
Do you want to add one more record (y/n):n

Enter the record number to read (0 to stop): 2


2 maya 13 23500.00 11/9/2004
Enter the record number to read (0 to stop): 1
1 master 1 27500.00 12/ 3/1990 19
Enter the record number to read (0 to stop): 0
Program #11
Write a program to merge multiple files into one file using command line arguments
#include<stdio.h>
main(int argc,char *argv[])
{
FILE *fp,*fp2;
int i;
fp2=fopen(“ans”,”a”);
for(i=1;i<argc;i++)
{
fp=fopen(argv[i],”r”);
while((ch=fgetc(fp))!=EOF)
fputc(ch,fp2);
}
fclose(fp);
fclose(fp2);
}
Output:
$./a.out stud.txt sample.txt master.txt
content of file ans
=========
pradeep is a good boy.
Mater minds are not made.
Master minds are born.
Master minds are not born. They are made.
But master minds are mad.
Master minds’ numbers consist of digits: 0-9
The persons who read this text are master minds

20
Program #12
Write a program convert the text in file into upper case
#include<stdio.h>
main()
{
FILE *fp1,*fp2;
char ch;

fp1=fopen(“master.txt”,”r”);
fp2=fopen(“case.txt”,”w”);
ch=fgetc(fp1);
while(ch!=EOF)
{
fputc(toupper(ch),fp2);
ch=fgetc(fp1);
}
fclose(fp1);
fclose(fp2);
fp2=fopen(“case.txt”,”r”);
ch=fgetc(fp2);
while(ch!=EOF)
{
printf(“%c”,ch);
ch=fgetc(fp2);
}
fclose(fp2);
}
output:
content of master.txt
=======
Master minds are not born. They are made.
But master minds are mad.
Master minds’ numbers consist of digits: 0-9
The persons who read this text are master minds
content of case.txt
=========
MASTER MINDS ARE NOT BORN. THEY ARE MADE.
BUT MASTER MINDS ARE MAD.
MASTER MINDS’ NUMBERS CONSIST OF DIGITS: 0-9
THE PERSONS WHO READ THIS TEXT ARE MASTER MINDS

Error-handling
While processing files, we usually assume that:
o The file that is opened exists.
o There is enough space on the disk for the file.
o The functions fseek(), fread(), fwrite()…etc carry out the requested job successfully.
It is important to note that these assumptions are not always true. There is possibility of the
following errors in manipulating files:

21
Error Reason
File not found Wrong file name used (spelling mistake, error in the path specified) or file
actually not present.
Disk full When writing to a disk with no more free sectors.
Disk write The disk has its write protect tag put on or some software has disabled writes
protected to the disk.
Unexpected EOF File length is zero of file length is less than that expected.
Sector not found (i) Reading and writing to two different streams, one as read only and
the other write only, but the file used for these streams is the same.
(ii) The disk head is not aligned on the physical sectors.
The error-handling functions in C are:
perror() function: The perror() function is used to print the nature of the error. It has the
following prototype:

void perror(char *msg);

The argument msg points to an optional user-defined message. This message is printed first,
followed by a colon and the implementation-defined message that describes the most recent
error. If you call perror() when no error has occurred, the message displayed is no error.

Program
Write a program to demonstrate perror() function
#include <stdio.h>
#include <stdlib.h>
main()
{
FILE *fp;
char filename[80];

printf("Enter filename: ");


gets(filename);

if (( fp = fopen(filename, "r")) == NULL)


{
perror("You made a mistake");
exit(1);
}
else
{
puts("File opened for reading.");
fclose(fp);
}
}
Output:
Enter file name: master.xxx
You made a mistake: No such file or directory.

What is the purpose ferror()?


The ferror() is a macro that tests the given file pointer for a read or write error. It has the following
prototype:

int ferror(pointe r_to_FILE);

From this prototype, it is clear that:


o ferror() function takes one argument: the file pointer .
o On success, it returns non-zero if an error is detected on the named file pointer.
22
Write a program to demonstrate ferror()
#include<stdio.h>
main()
{
char filename[15],ch;
FILE *fp;
printf("\n Enter file name:");
scanf("%s",filename);
fp=fopen(filename,"r");
if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
fputc(ch,fp);
if(ferror(fp)>0)
{
perror("error");
}
fclose(fp);
}
Output:
Enter file name: master.txt
error: Bad file descriptor.

Concept of binary files


Apart from text files, every computer uses another kind of files that are known as binary files. All
machine language files such as files with extension .com, .exe, .obj, .dll, etc are actually binary files.
For opening a binary file, file mode has to be mentioned as “rb” or “wb” in fopen(). Otherwise, all
files are opened in default mode, which is text mode. These binary files should be handled in a
different way as compared to text files. The binary files differ from text files in three ways:
1) The storage of new line characters: In text files, \n is stored as a single new line
character by user, but it takes 2 bytes of storage inside the memory. Actually, new line
character is collection of two characters- first carriage return (\r ASCII code 13) and second
line feed (ASCII code 10). When a text file stores \n, it is stored using 2 bytes, but is
considered as a single character. So when we try to count the number of characters of a text
file, each new line character contributes by one.
2) The eof character: The eof character in text files corresponds to the character having ASCII
code 26. In binary files, there is no such explicit eof character. The binary files do not store
any special character at the end of the file and their file-end is verified by using their size
itself.
3) While discussing binary files, one more point is worth mentioning and corresponds to storage
of numbers in binary format. The numbers can be written to files using fprintf() statement as
a sequence of characters. E.g., the number 1001 can be written using fprintf() as a sequence
of characters: ‘1’,’0’,’0’,’1’. It means that storage of 4-digit number will take 4 bytes. But on
a 16-bit computer, an integer needs 2 bytes of storage and this concept can be utilized with
help of fwrite() statement. The fwrite() function will store every integer value by taking two
bytes.

23
Multifile Compilation

Multiple files can be compiled at a time using the command cc. Suppose that there are three files
namely, “first.c”,”second.c” and ”third.c”. These three files can be compiled at a time.This can be
done as follows:
cc first.c second.c third.c
These files will be separately compiled into object files as “first.o”, “second.o” and “third.o” and then
linked to produce an executable program file a.out.
Note:
1) It is also possible to compile each file separately and link them later. E.g., the commands :
cc –c first.c
cc –c second.c
will compile the source files “first.c” and “second.c” into object files “first.o” and “second.o”.
They can be linked together by the command:
cc first.o second.o

2) We may also combine the source files and object files as follows:
cc sample.c second.o
only “sample.c” gets compiled and then linked with the object file “second.o”. This approach
is very useful when one of the multiple source files need to be changed and recompiled or an
already existing object files is to be used along with the program to be compiled.

3) The linker always assigns the same name to the executable object file as a.out. When we
compile another program, this file will be overwritten by the executable object code of the
new program. If we want to prevent from happening, we should rename the file immediately
by using the command: mv a.out name

We may also achieve this by specifying an option in the cc command as follows: cc –


o name source_file
This will store the executable object code in the file name and prevent the old file
a.out from being destroyed.

24
SHORT ANSWER QUESTIONS

1. Distinguish between local and global variables.


2. What is a variable? How a constant data is stored in a variable?
3. What is conditional operator? Give syntax and example?
4. What is meant by key words in C?
5. What is the difference between Character Constants and Numeric Constants?
6. What is meant by a prototype?
7. Write the type conversion rules
8. Write down the various data types.
9. What is pre-processor directive? What is the purpose of preprocessors?
10. State void specifier.
11. Define Boolean expression
12. What are the relational operators in C.
13. Define ternary operator with an example.
14. What is the format used to get the address of a variable?
15. Define unary operator with an example.
16. What is the format used to get the address of a pointer?
17. Write the syntax of switch statement.
18. Write the use of Break and Continue statements
19. How do you define a pointer to a structure?
20. Write the purpose of header file.
21. List out the header files related to input-output functions and
mathematical functions are defined.
22. How do you define a pointer to a linear array?
23. What is the role played by ‘sizeof’ in dynamic memory?.
24. What is meant by recursion?
25. Explain arrays of structures
26. Write the syntax of for loop.
27. What is meant by multi-file compilation?
28. What is the difference between character and string constants
29. What is an arithmetic expression?
30. What do you understand by signed character?
31. What is the difference between structure and union?
32. Distinguish between getchar( ) and getch( ).
33. What is a pointer?
34. What is meant by ‘call by reference’ method?
35. What is meant by array of pointers?
36. Define scope of variable. Write scope rules..
37. Write the different modes of opening a file.

25
38. How do variables and symbolic names differ?
39. What are enumeration variables? How are they declared?
40. What would be the value of ‘x’ after execution of the following statement?
int x,y=10;
char z=’a’;
x=y+z;
41. In what ways does a switch statement differ from an if statement?
42. What is a null statement?
43. Compare in terms of their functions, the following pairs of statements.
(i) break and goto
(ii) while and do while
44. Distinguish between (i) Global and (ii) Local variables.
45. How is a pointer initialized?
46. What is the difference between ‘call by reference’ and ‘call by value’?
47. What is the output of the given code?
main()
{
int a,b,x=10;
a=b=x+5;
a=10;
b=20;
printf(”%d %d %d”, a, b, x);
}

48) What is the value of b in the following code


main()
{
int b=5;
int j;
j=(++b)*(b++)*(b++);
printf(“%d”, j, b);
}
49)What is an automatic storage class?
50)What is a dereference operator?
51)What is the output of the code given?
main()
{
int *p, I;
int **q;
p=&I;

26
q=&p;
i=10;
printf(“%d”, **q);
printf(“%d”, *p);
}
52.) Differentiate between getchar() and gets() functions?
52) Define an algorithm.
53) Write the rules for type- conversion.
54) How can you define string constants?
55) Define C token with an example.
56) Differentiate between keywords and identifiers.
57) Define Program loop.
58) Differentiate between Entry-controlled loop and Exit-controlled loop.
59) From the given statement
for(X=(m+n)/2; X>0; X=X/2)
60)justify whether it is valid or not.
61) What is single subscript variable?
62) Give the declaration of two dimensional arrays.
63) Classify functions and define them.
(i)Define longevity.
(ii) Differentiate between malloc and calloc functions.
64) What are logical operators?
65) What is sequential file procession?
66) Write syntax for scanf();
67) Define getchar statement.
68)Define Structure in C programming.
69) What are the values of K and i in the following program:
int K , i =1;
K=i++;
printf(“K= %d, i= %d”,K,i);

70) Explain scanf() function with suitable example


71) What is the output of the given code?
int main(void)
{ int i=0, power=1;
while (++i<=10)
printf(“%-6d”,power*=2);
printf(“\n”);
return 0;}
72)Write the syntax of structure declaration.
73)Explain with an example the initialization of structures.
74)Explain briefly about extern storage class in C.
27
75) Explain the gets and puts functions.
76) What are nested loops? What are its advantages?
77) Give an example where pointers are very necessary.
78) What are ‘ragged arrays’?
79) Differentiate between pointer to a function and a function that accepts pointers.

80) How can the size of a structure be determined? In what units is the size reported?
81) If a pointer variable points to a structure that contains an array as a member, how can the
element of the embedded array be processed?
82) What are the various file-types that can be specified?

28
UNIT I

1. Discuss various data types and their sizes in C.

2. Write a program to find out roots of a Quadratic equation.

3. Discuss input/output functions and other library functions.

4. Write a program to convert the lower case characters to its upper case
characters.

5. Explain type conversion rules

6. Write a program to find the type of triangle formed by the given sides.

7. Write a program to find the largest of three numbers.

8. Explain Arithmetic operations and expressions in C.

9. Explain input/output functions and other library functions in C.

10. What are the basic data types and sizes? List out the secondary data types?

11. Write about the operators available in C-language.

12. Write a C-code to find the maximum number among three numbers using conditional
operator.

13. Write a program that reads a character from the keyboard and prints the following
i.) Is the character alphabetic?
ii.) Is the character numeric?
iii.) If alphabetic, is the character uppercase?
iv.) If alphabetic, is the character lowercase?

14. What is the output of the given code?


15. main()
{ int i,j,k,m;
i=3; j=-2; k=0;
m=++i &&j || ++k;
}

16. Write about space requirements for variables of different data types.

29
17. Explain about increment and decrement operators, conditional operators in C.

18. Describe four basic data types. How could we extend the range of values they represent?

19. In inventory management, the Economic Order Quantity for single item is given by
EOQ= 2 x demand rate x Set up costs
Holding cost per item per unit time

And Time Between Orders


TBO= 2 x setup costs
a.) Demand rate x holding cost per item- unit time
Write a C program to compute EOQ and TBO, given demand rate, set up costs
and the holding costs.

20. What are storage classes in C? Explain with examples.


21. Write a program to read the value of x and y and print the result of the following
expressions in one line.
i.) (x + y) / (x - y)
ii.) (x + y) / 2
iii.) (x + y) (x - y)

22. The total distance traveled by a vehicle in t seconds is given by


distance = ut + ½ at2 where u is the initial velocity ( meters per second), a is the
acceleration ( meters per second2). Write a program to evaluate the distance traveled at regular
intervals of time, given the values of u and a. The program should provide the flexibility to the
user to select his own time interval and repeat the calculations for different values of u and a.

23. Explain Arithmetic, Rotational, Logical and assignment operators with suitable examples.

24. Write a program to determine whether a number is odd or even and print the message
“Number is odd” or “Number is even” (i) without using else option and
(ii) using else option.

25. b.) What is an escape sequence in C?


c.) What are preprocessor directives?
d.) Explain the use of library functions?
e.) Write an interactive program that will read in a positive integer value and Determine if
the integer is a prime number.
26. Discuss the gets() and puts() functions with examples.
Write a C program for averaging and finding the maximum of a list of numbers.

30
UNIT II

1. Write a program to find all prime numbers with in a given set of input numbers.

2. Explain various loops with suitable example.

3. Write a program to find all prime factors of a given number.

4. Write a program to find whether a given number is prime.

5. Write a program to count the no.of characters in a given word.

6. Write a program to the Fibonacci numbers between 100 and 999.

7. Write a program to find whether a given number is prime.

8. Write a program to compute the sum of digits of a given integer.

9. Explain Multi file compilation in C.

10. Write syntax of for-loop? Write the while-loop statement equivalent to for-loop.

11. Write a program to count the no.of characters, no.of lines, no. of words, no. of spaces in
given text using switch statement.

12. Write a program to find the summation of the series


S=1+x+x2+x3+x4+………using while-loop?

13. Explain about parameter passing mechanism to a function with examples.

14. Explain different iterative statements in C with an example each.

15. Write a C program to check whether the given number is perfect or not.

16. Write a C program to print prime numbers up to 200.


17. Write a C program to print Fibonacci Series using do-while loop.

18. What is a null statement? Explain its usefulness.

19. Write a program that will read a positive integer and determine and print its binary
equivalent.

20. Write short notes on switch, do-while and while statements.

21. Write about unconditional statements in C

31
22. Write a program to reverse a given number of 5 digits.

23. Write a complete C program to compute and print the first m Fibonacci numbers, where m is
the input to the program.

24. Write a program that reads in an integer value for n and then sums the integers from n to
2*n if n is non-negative or from 2*n to n if n is negative. Write the code in two versions one
using only for loop and the other using only while loop.

25. The mathematical operation min(x,y) can be represented by the conditional expression
(x<y)? x: y In similar fashion, using only conditional expression describe the mathematical
operations min(x,y,z) and max(x,y,z,w).

26. The following code is a recursive function that computes the gcd of two positive integers:
int gcd(int p, int g)
{ int r;
if((r=p%q)==0) return q;
else return gcd(q,r);
}
Write and test an equivalent iterative function.
27. Write a program to find the factorial of a given number using recursion.
28.
Differentiate between do-while and while.
What are function prototypes? Explain.
Write a program to read a line of text and write it out backwards using recursion.

29. Explain the concept of recursion.


30. Write a C program for counting the number of characters, words and lines in a given text.

32
UNIT III

1. Explain the concept of Dynamic memory allocation with suitable example.

2. Write a program to implement insertion sort.

3. Explain the concept of character arrays and pointers and pointer arrays with
suitable examples.

4. Write a program to implement binary search.

5. Write a program to find the product of two matrices.

6. Write a program to implement bubble sort.

7. Explain different string handling functions.

8. Given are two dimensional arrays A and B which are sorted in ascending order.
i.) Write a program to merge them into a single sorted array ‘C’ that contains
ii.) every item from arrays A and B , in ascending order.

9. The annual examination results of 100 students are tabulated as follows

Roll Subject 1 Subject 2 Subject


No 3

Write a program to read the data and determine the following


Total marks obtained by each student
The highest marks in each subject and the Roll No of student who secured it.
The student who obtained the highest total marks.

10. Write C function to compare the two given strings without using library functions.
List out all the library functions used to perform operations on strings and its headerfile.
11. Write a program to find transpose of a matrix into same matrix using functions.

12. Write a program to multiply the 3 x 3 matrices.

13. Write a function to sort an array of N-elements using Insertion sort.

14. Explain the command line arguments. What are the syntactic constructs followed in C?
15. Define an array. In what way an array is different from an ordinary variable? What advantage
is there in defining an array size in terms of a symbolic constant rather than a fixed integer
quantity?
.
16. Write a program to sorting of names using pointer arrays.

33
17. Give syntax and declaration of case statement. Compare it with looping constructs.
18. Write a C program to find the product of two matrices A(m x K) and B(K x n).

19. What is a pointer? How are pointers used in call-by-reference type of parameter passing?
Write a C function Swap(a,b) which interchanges the values of variables a and b.

20. Write a C program to merge two sorted arrays.

21. give syntax of the following C construct and explain them


i.) Case statements
ii.) Function declaration
iii.) Array declaration.

22. Explain the functions calloc(), malloc() and free() with suitable examples.
.
23. Write a program to sort names using pointer arrays.

34
UNIT IV

1. Write a short note on pointers to structures and unions with suitable examples.

2. Write a program to sort a list of library records on name, author using dynamic
allocation.

3. Discuss sequential file processing with illustrations.

4. Write a program to sort a list of birth records by date of birth using dynamic
allocation.

5. Explain arrays of structures.

6. Write a program to process the student marks in six subjects and sort it on the
student name.

7. Explain arrays of structures.

8. Write a program to multiply two complex numbers.

9. An n order polynomial can be evaluated as follows:


P= (……..((a0x+a1)x+a2)x+a3)x+………+an)
Write a program to evaluate the polynomial, using an array variable a.

10. Write short notes on structures?

11. Write a program to read a student record in a class of 10 and display it.

12. Write a program using pointers to find the sum of the diagonal elements in a 4 x 4
matrix?

13. Distinguish between an array of structures and array within a structure. Give an example of
each.

14. Define a structure that represent a complex number (contains two floating – point numbers,
called real and imaginary). Write a C program to add, subtract and multiply two complex
numbers.

15. Distinguish between structures and arrays. Explain structure data types with
examples.

16. Write a program to illustrate the use of structure pointers.

17. Distinguish between structures and arrays. Explain structure data type with examples.

35
18. Write a C program to illustrate the use of Unions.

19. Distinguish between structures and arrays. Explain structure data type with example.

20. Write a program to illustrate the use of structure pointers.

21. Write a program to calculate the subject-wise and student-wise totals and store them on a
part of the structure for 100 students and 3 subjects.

22. Write a program using pointers to read in an array of integers and print its elements in
reverse order

23. What is a self-referential structure? For what kinds of applications are self-referential
structures useful?
24. Write a program for library records processing- sort books on author name. Use other
appropriate entries.

36

You might also like