Let Us C / Chapter 10 (Structures)

                                 Exercise [D]


(a) Create a structure to specify data on students given below:
Roll number, Name, Department, Course, Year of joining
Assume that there are not more than 450 students in the collage.
(a) Write a function to print names of all students who joined in a particular year.
(b) Write a function to print the data of a student whose roll number is given.

Solution:


/* NOTE: since number of students to be assumed is too much ( about 450 )
I have alloted full size (about 450) to it but array has been kept empty,
if you have time then you can fill up all 450 names and can search through
them.program has been tested by me and it works accurately. you can reduce
the size of array of structure conveniently by changing the value of N */

#include<stdio.h>
#include<conio.h>
#define N 450

struct students {
int rlnm;
char name[25];
char dept[25];  /* structure defined outside of main(); */
char course[25];
int year;
};

void main() {           /* main() */

struct students s[N];
int i,ch;

clrscr();


/* taking input of 450 students in an array of structure */

for(i=0;i<N;i++) {

printf("  Enter data of student %d\t\t\t\ttotal students: %d\n",i+1,N);
printf("****************************\n\n");

printf("enter rollnumber:  ");
scanf("%d",&s[i].rlnm);

printf("\n\nenter name:  ");
scanf(" %s",&s[i].name);

printf("\n\nenter department:  ");
scanf("%s",&s[i].dept);

printf("\n\nenter course:  ");
scanf("%s",&s[i].course);

printf("\n\nenter year of joining:  ");
scanf("%d",&s[i].year);

clrscr();

}

  /* displaying a menu */

printf("\n\tenter your choice: \n");
printf("\t**********************\n\n");

printf("1: enter year to search all students who took admission in that:\n\n");
printf("2: enter roll number to see details of that student\n\n\n");

printf("your choice:  ");     /* taking input of your choice */
scanf("%d",&ch);

clrscr();

switch(ch) {

case 1:
     clrscr();

     dispyr(&s);  /* function call to display names of students who joined in\
    a particular year */

     break;

case 2:
     clrscr();

     disprl(&s);    /* function call to display information of a student \
      whose roll number is given */

     break;

default:

     printf("\n\nerror! wrong choice");

}

getch();

}
/******************* main() ends **************/

dispyr(struct students *a) {   /* function for displaying names of students\
   who took admission in a particular year */

int j,yr;

printf("\nenter year:  ");
scanf("%d",&yr);

printf("\n\nthese students joined in %d\n\n",yr);

for(j=0;j<N;j++) {

if(a[j].year==yr)  {

printf("\n%s\n",a[j].name);
}

}
return 0;
}


disprl(struct students *a) {        /* function to print information of a\
    student whose roll number has been \
    given. */

int k,rl;

printf("\nenter roll number: ");
scanf("%d",&rl);

for(k=0;k<N;k++)  {

if(a[k].rlnm==rl) {

printf("\n\n\t Details of roll number: %d\n",a[k].rlnm);
printf("\t***************************\n\n");
printf("           Name: %s\n",a[k].name);
printf("     Department: %s\n",a[k].dept);
printf("         Course: %s\n",a[k].course);
printf("Year of joining: %d",a[k].year);

break;
}

else {
printf("\nRoll number you entered does not exist\n\n");

break;
}

 }

return 0;
}


--------------------------------------------------------------------------------------------------------------

(b) Create a structure to specify data of customers in a bank. The data to be stored is: Account number, Name, Balance in account. Assume maximum of 200 customers in the bank.
(a) Write a function to print the Account number and name of each customer with balance below Rs. 100.
(b) If a customer request for withdrawal or deposit, it is given in the form:
Acct. no, amount, code (1 for deposit, 0 for withdrawal)
Write a program to give a message, “The balance is insufficient for the specified withdrawal”.

Solution:



/* NOTE: since number of customers to be assumed is too much ( about 200 )

I have alloted full size (about 200) to it but array has been kept empty,

if you have time then you can fill up all 200 names and can search through

them.program has been tested by me and it works accurately. you can reduce
the size of array of structure conveniently by changing the value of N */

#include<stdio.h>
#include<conio.h>
#define N 200

struct bank {
   int acn;
   char name[20];
   int bal;         /* defined out of main() */
   };

void main() {

struct bank b[N];

int i,ch,lw=100,ch2,ac,am;

clrscr();

for(i=0;i<N;i++) {           /* inputting customer data */

printf("\tEnter information of customers \n");
printf("\t******************************\n\n");

printf("enter account no.: ");
scanf("%d",&b[i].acn);

printf("\n\nenter customer name: ");
scanf("%s",&b[i].name);

printf("\n\nenter balance: ");
scanf("%d",&b[i].bal);

clrscr();

}

clrscr();

printf("\tEnter your choice\n");    /* further processing of transaction */
printf("\t*****************\n\n");

printf("1: to know whose balance is below 100.\n\n");
printf("2: to process request or withdrawl.\n\n\n");


scanf("%d",&ch);

switch(ch) {

case 1:

      clrscr();

      disp(&b);         /* displaying whose balance is below 100 */

      break;



case 2:

     clrscr();

     printf("enter your account number: ");
     scanf("%d",&ac);

     for(i=0;i<N;i++) {

     if((b[i].acn)==ac) {

     clrscr();

     printf("\tHello %s\n",b[i].name);
     printf("\n\n");

     printf("\n\nenter your choice\n");
     printf("\n1: deposite:\n");
     printf("\n0: withdrawl:\n\n");
     scanf("%d",&ch2);

     switch(ch2) {


     case 0:

   clrscr();

  if(b[i].bal<lw) {

  printf("\n\nsorry! account balance is too low for withdrawl.\n");

  break;
  }

  else {

  printf("\n\nenter amount for withdrawl: ");
  scanf("%d",&am);

  }

  if(b[i].bal<am) {

  printf("\n\nyou don't have enough balance for withdrawl.\n");


  }


  else {

  b[i].bal=b[i].bal+am;

  printf("\n\nwithdrawl was successful.\n");

  }
  break;

     case 1:

 clrscr();

 printf("\n\nenter amount to deposite: ");
 scanf("%d",&am);

 b[i].bal=b[i].bal+am;

 printf("\n\ncash deposited successfully.\n\n");

 break;

}

}
}
}
 getch();
 }

disp(struct bank *a) {

int k;

printf("\tCustomers whose balance is below 100:\n");
printf("\t*************************************\n\n");

for(k=0;k<N;k++) {

if((a[k].bal)<100) {

printf("%2d\t%s\n",a[k].acn,a[k].name);

}
}
return 0;

 }


-----------------------------------------------------------------------------------------------------------------

(c) An automobile company has serial number for engine parts starting from AA0 to FF9. The other characteristics of parts to be specified in a structure are: Year of manufacture, material and quantity manufactured.
(a) Specify a structure to store information corresponding to a part.
(b) Write a program to retrieve information on parts with serial numbers between BB1 and CC6.

Solution:


#include<stdio.h>

#include<conio.h>

struct automob {

char name[5];
int year;
char mtr[10];
int qty;
};
void main() {

struct automob a[54]={{"AA1",2009,"AAA",10},
{"AA2",2009,"AAA",10},
{"AA3",2009,"AAA",10},
{"AA4",2009,"AAA",10},
{"AA5",2009,"AAA",10},
{"AA6",2009,"AAA",10},
{"AA7",2009,"AAA",10},
{"AA8",2009,"AAA",10},
{"AA9",2009,"AAA",10},
{"BB1",2010,"BBB",11},
{"BB2",2010,"BBB",11},
{"BB3",2010,"BBB",11},
{"BB4",2010,"BBB",11},
{"BB5",2010,"BBB",11},
{"BB6",2010,"BBB",11},
{"BB7",2010,"BBB",11},
{"BB8",2010,"BBB",11},
{"BB9",2010,"BBB",11},
{"CC1",2011,"CCC",12},
{"CC2",2011,"CCC",12},
{"CC3",2011,"CCC",12},
{"CC4",2011,"CCC",12},
{"CC5",2011,"CCC",12},
{"CC6",2011,"CCC",12},
{"CC7",2011,"CCC",12},
{"CC8",2011,"CCC",12},
{"CC9",2011,"CCC",12},
{"DD1",2012,"DDD",13},
{"DD2",2012,"DDD",13},
{"DD3",2012,"DDD",13},
{"DD4",2012,"DDD",13},
{"DD5",2012,"DDD",13},
{"DD6",2012,"DDD",13},
{"DD7",2012,"DDD",13},
{"DD8",2012,"DDD",13},
{"DD9",2012,"DDD",13},
{"EE1",2013,"EEE",14},
{"EE2",2013,"EEE",14},
{"EE3",2013,"EEE",14},
{"EE4",2013,"EEE",14},
{"EE5",2013,"EEE",14},
{"EE6",2013,"EEE",14},
{"EE7",2013,"EEE",14},
{"EE8",2013,"EEE",14},
{"EE9",2013,"EEE",14},
{"FF1",2014,"FFF",15},
{"FF2",2014,"FFF",15},
{"FF3",2014,"FFF",15},
{"FF4",2014,"FFF",15},
{"FF5",2014,"FFF",15},
{"FF6",2014,"FFF",15},
{"FF7",2014,"FFF",15},
{"FF8",2014,"FFF",15},
{"FF9",2014,"FFF",15}};


int i,j,k;

clrscr();


printf("Information of parts between BB1 to CC6:\n\n");

printf("\n\nName\t\tyear(manu.)\t\tmaterial\tquantity\n\n\n");

for(i=0;i<54;i++) {


if(i>=9 && i<=23) {
printf("%3s\t\t%4d\t\t\t%5s\t\t%4d\n",a[i].name,a[i].year,a[i].mtr,a[i].qty);


}
}


getch();
}

-----------------------------------------------------------------------------------------------------------------

(d) A record contains name of cricketer, his age, number of test matches that he has played and the average runs that he has scored in each test match. Create an array of structure to hold records of 20 such cricketer and then write a program to read these records and arrange them in ascending order by average runs. Use the qusort( ) standard library function.

Solution:



#include<stdio.h>

#include<conio.h>

#include<string.h>


void main() {

struct cricketer {
char name[50];
int age;
int match;
float avrn;
};
struct cricketer c[20],temp;
int i,j;
clrscr();

for(i=0;i<20;i++) {

printf("Enter data of cricketer %d\n\n\n",i+1);

fflush(stdin);
printf("Name: ");
gets(c[i].name);

printf("\n\nAge: ");
scanf("%d",&c[i].age);

printf("\n\nMatches: ");
scanf("%d",&c[i].match);

printf("\n\nAverage runs: ");
scanf("%f",&c[i].avrn);

clrscr();

}

/*******************/
/* sorting records */
/*******************/


for(i=0;i<20;i++) {

for(j=i+1;j<20;j++) {

if(c[i].avrn > c[j].avrn) {

temp=c[i];
c[i]=c[j];
c[j]=temp;
}
}
}

printf("Sorted records:\n\n");

for(i=0;i<20;i++) {

printf("%d\t%s\t%d\t%d\t%f\n\n\n",i+1,c[i].name,c[i].age,c[i].match,c[i].avrn);

}

getch();
}

linkfloat() {

float a=0,*b;

b=&a;
a=*b;

return 0;
}

-----------------------------------------------------------------------------------------------------------------

(e) There is a structure called employee that holds information like employee code, name, date of joining. Write a program to create an array of the structure and enter some data into it. Then ask the user to enter current date. Display the names of those employees whose tenure is 3 or more than 3 years according to the given current date.

Solution:


#include<stdio.h>
#include<conio.h>
#define N 3
void main() {


struct employee {
int code;
char name[20];
int dd,mm,yy;
} e[N];

int d,m,y,i;
clrscr();

for(i=0;i<N;i++) {

printf("\tEnter employee data:\n");
printf("\t*********************\n");

printf("\nEnter employee code: ");
scanf("%d",&e[i].code);

printf("\n\nEnter employee name: ");
scanf("%s",&e[i].name);

printf("\n\nEnter date of joining (dd mm yy): ");
scanf("%d%d%d",&e[i].dd,&e[i].mm,&e[i].yy);

clrscr();

}

clrscr();

printf("\nenter current date(dd mm yy): \n\n");
scanf("%d%d%d",&d,&m,&y);

clrscr();

for(i=0;i<N;i++) {

if((y-(e[i].yy))>=3) {

printf("%s\n\N",e[i].name);

}


}

getch();
}

-----------------------------------------------------------------------------------------------------------------

(f) Write a menu driven program that depicts the working of a library. The menu options should be:
1. Add book information
2. Display book information
3. List all books of given author
4. List the title of specified book
5. List the count of books in the library
6. List the books in the order of accession number
7. Exit
Create a structure called library to hold accession number, title of the book, author name, price of the book, and flag indicating whether book is issued or not.


Solution:



#include<stdio.h>

#include<conio.h>

#include<dos.h>


void main() {

struct library {
int acn;
char title[25];
char auth[25];
float price;
int   flag;
};

struct library a[5]={
   {2,"AAA","AAA",154.8,1},
   {1,"BBB","BBB",124.6,0},
   {5,"EEE","EEE",234.3,0},
   {3,"CCC","CCC",232.3,1},
   {4,"DDD","DDD",121.3,0}
   };

struct library temp;    /* temporary structure to overwrite information /
    and for assistance in sorting the whole structure */




int i,ch,k,flag,j=0;
char author[10];

clrscr();

while(1) {       /* initialized an indefinite loop */

clrscr();
printf("\t1: Add book information\n");
printf("\t2: Display book information\n");
printf("\t3: List all books of given author\n");
printf("\t4: List the title of specified book\n");
printf("\t5: List the count of books in the library\n");
printf("\t6: List the books in order of accesion number\n");
printf("\t7: Exit\n\n\n");

printf("Choice:   ");
scanf("%d",&ch);

switch(ch) {

case 1:       /* adding book information over current information */

clrscr();

printf("\t\t1: Add book information:\n\n\n");

printf("enter book information:\n\n");

printf("Accesion number of book to be modified:  ");
scanf("%d",&j); fflush(stdin);

for(i=0;i<5;i++) {

if(j==a[i].acn) {

printf("\n\nenter new information:\n\n");
printf("accesion no.: ");
scanf("%d",&temp.acn); fflush(stdin);
printf("\n\ntitle: ");
scanf("%s",&temp.title);  fflush(stdin);
printf("\n\nauthor: ");
scanf("%s",&temp.auth);  fflush(stdin);
printf("\n\nprice: ");
scanf("%f",&temp.auth); fflush(stdin);
printf("\n\nflag(1/0): ");
scanf("%d",&temp.flag); fflush(stdin);

}
}

a[j]=temp;   /* overwriting current information with new one  */

clrscr();

printf("\n\nInformation added succesfully!\n\n");

delay(2000);

break;


case 2:    /* displaying current book information */


clrscr();

printf("\t\t2: Display book information:\n\n\n");

printf("Enter accesion number: ");
scanf("%d",&k);

for(i=0;i<5;i++) {

if(k==a[i].acn) {
clrscr();
printf("Book information: \n\n");
printf("\n\nAccesion Number: %d",a[i].acn);
printf("\nTitle: %s",a[i].title);
printf("\nAuthor: %s",a[i].auth);
printf("\nPrice: %f",a[i].price);

if(a[i].flag==0) {
printf("\nFlag: Not issued\n\n");
}
else{
printf("\nFlag: Issued\n\n");
}
}
}
delay(1000);

break;


case 3: /* listing all books of given author */


clrscr();

printf("\t\t3: List all books of given author:\n\n\n");

printf("Enter author name:  ");
scanf("%s",&author);  fflush(stdin);

printf("\n\nbooks of %s\n\n",author);
for(i=0;i<5;i++) {

k=strcmp(author,a[i].auth);

if(k==0) {
j=j+1;
printf("%d.\t%s\n",j,a[i].title);

}
}
delay(2000);
break;


case 4:    /* displaying title of given book */


clrscr();
printf("\t\t4: Title of the specified book:\n\n\n");

printf("Enter the accesion number:  ");
scanf("%d",&k);

printf("\n\n");

for(i=0;i<5;i++) {

if(k==a[i].acn) {

printf("Title: %s\n",a[i].title);

}
}
delay(2000);
break;


case 5:    /* counting total books in library */


clrscr();
printf("\t\t5: List the count of books in the library: \n\n\n");

for(i=0;i<5;i++) {
j=j+1;
}
printf("\tTotal books: %2d",j);

delay(2000);
break;


case 6:   /* sorting the books by their accesion numbers */


clrscr();
printf("6: List the books in order of accesion number: \n\n\n");

for(i=0;i<5;i++) {

for(j=i+1;j<4;j++) {

if(a[i].acn>a[j].acn) {
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}

printf("Access no.\tTitle\tAuthor\tFlag\n\n\n");
for(i=0;i<5;i++) {

printf("%4d\t\t%5s\t%5s\t",a[i].acn,a[i].title,a[i].auth);

if(a[i].flag==0)
printf("not issued\n\n");

else
printf("issued\n\n");
}

delay(2000);
break;


case 7:      /* condition for going out */

      exit();

}
}

}

linkfloat() {   /* special function to solve compilar error */
float a=0,*b;   /* not used withing the program but still defined */
b=&a;
a=*b;
return 0;
}

------------------------------------------------------------------------------------------------------------------

(g) Write a program that compares two given dates. To store date use structure say date that contains three members namely date, month and year. If the dates are equal then display message as "Equal" otherwise "Unequal".


Solution:


#include<stdio.h>
#include<conio.h>

void main() {

struct date {
   int date;
   int month;
   int year;
   }d1;

int d,m,y,i;
clrscr();

printf("enter the date to save in structure: \n\n");

printf("Enter the date: ");
scanf("%d",&d1.date);

printf("\n\nEnter the month: ");
scanf("%d",&d1.month);

printf("\n\nEnter the year: ");
scanf("%d",&d1.year);

clrscr();

printf("\nenter the date to compare with structure:\n\n");

printf("Enter the date: ");
scanf("%d",&d);

printf("\n\nEnter the month: ");
scanf("%d",&m);

printf("\n\nEnter the year: ");
scanf("%d",&y);

if(d==d1.date && m==d1.month && y==d1.year) {

printf("\n\ndates are equal\n\n");

}

else {

printf("\n\ndates are unequal\n\n");

}

getch();

}


-----------------------------------------------------------------------------------------------------------------

(h) Linked list is a very common data structure often used to store similar data in memory. While the elements of an array occupy contiguous memory locations, those of a linked list are not constrained to be stored in adjacent location. The individual elements are stored “somewhere” in memory, rather like a family dispersed, but still bound together. The order of the elements is maintained by explicit links between them. Thus, a linked list is a collection of elements called nodes, each of which stores two item of information—an element of the list, and a link, i.e., a pointer or an address that indicates explicitly the location of the node containing the successor of this list element.
Write a program to build a linked list by adding new nodes at the beginning, at the end or in the middle of the linked list. Also write a function display( ) which display all the nodes present in the linked list.

Solution:


#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<ctype.h>

struct linklist {
int data;
linklist *link;
};

void main() {

struct linklist *first, *temp;

char choice='y';

int count=0;

clrscr();


/* taking the input of first element */


printf("Enter element %d: ",++count);

first=(linklist *)malloc(sizeof(linklist));

scanf("%d",&first->data);

first->link=NULL;

printf("\n\nEnter another element(Y/N): ");

choice=getche();

tolower(choice); /* converting to lowercase to match the condition of switch */

switch(choice) {

case 'y':

clrscr();


while(choice=='y' || choice=='Y') {

printf("\nEnter element %d: ",++count);

temp=(linklist *)malloc(sizeof(linklist));

scanf("%d",&temp->data);

temp->link=first;

first=temp;


printf("\n\n\nEnter another elements(Y/N): ");
choice=getche();

clrscr();

}

break;


case 'n':

break;

}



printf("\nTotal elements = %d\n\n",count);


/* printing all elements */


for(temp=first; temp!=NULL; temp=temp->link) {

printf("%d ",temp->data);

}


getch();

}


-----------------------------------------------------------------------------------------------------------------

(i) A stack is a data structure in which addition of new element or deletion of existing element always takes place at the same 
end. This end is often known as ‘top’ of stack. This situation can be compared to a stack of plates in a cafeteria where every new plate taken off the stack is also from the ‘top’ of the stack. There are several application where stack can be put to use. For example, recursion, keeping track of function calls, evaluation of expressions, etc. Write a program to implement a stack using a linked list.

Solution:

NOTE: Topic not discussed in the book. I am learning from other resources.

-----------------------------------------------------------------------------------------------------------------

(j) Unlike a stack, in a queue the addition of new element takes place at the end (called ‘rear’ of queue) whereas deletion takes place at the other end (called ‘front’ of queue). Write a program to implement a queue using a linked list


Solution:

NOTE: Topic not discussed in the book. I am learning from other resources.
_______________________________________________________________________

Let Us C / Chapter 11 (Console Input Output)

                                 Exercise [D]


(a) 
Write down two functions xgets( ) and xputs( ) which work similar to the standard library functions gets( ) and puts( ).

Solution:


#include<stdio.h>
#include<conio.h>

void xgets();
void xputs();

void main() {

char str[80];
clrscr();

xgets(str);

printf("\n");

xputs(str);

getch();

}

void xgets( char *s) {

int i=0;
char ch;


for(i=0;i<=79;i++) {

ch=getche();

if(ch=='\r') {

*s='\0';
break;
}

if(ch=='\b') {

printf("\b");

i-=2;
s-=2;
}

else {

*s=ch;
s++;

}

 }

}

void xputs( char *s) {

while(*s!='\0') {

putch(*s);

s++;

}


}

---------------------------------------------------------------------------------------------------------------

(b) Write down a function getint( ), which would receive a numeric string from the keyboard, convert it to an integer number and return the integer to the calling function. A sample usage of getint( ) is shown below:
main( )
{
int a ;
a = getint( ) ;
printf ( "you entered %d", a )
}

Solution:



#include<stdio.h>
#include<conio.h>
void main() {

int a;
char s[80];

printf("Enter any numeric string: ");
gets(s);

a=getint(s);     /* converting and receiving string as integer */

printf("\n\nYou entered = %d\n",a);

getch();

}

int getint(char s1[80]) {

int digit;

digit=atoi(s1);   /* converting string to integer */

return digit;

}

______________________________________________________________________

Let Us C / Chapter 12 (File Input Output)

                                    Exercise [C]


(a) Write a program to read a file and display contents with its line numbers.

Solution:

NOTE: Make a file as "DATA.TXT" in bin directory and write/paste some text in it, then run the program.

#include<stdio.h>
#include<conio.h>
void main() {

FILE *fp;
char i;
int line=1;

clrscr();

fp=fopen("DATA.TXT","r");

if(fp==NULL) {

printf("\n\nCannot open file!");

delay(1000);
exit();
}

printf("%2d.  ",line);  /* we already print 1st for the first line */

while(i!=EOF) {

i=fgetc(fp);

printf("%c",i);

/* if the character is newline,the line number will be\
printed after it */

if(i=='\n') {
line++;
printf("%2d.  ",line);
}


}

fclose(fp);
getch();
}




---------------------------------------------------------------------------------------------------------------

(b) Write a program to find the size of a text file without traversing it character by character.

Solution:

NOTE: Make a file as "DATA.TXT" in bin directory and write/paste some text in it, then run the program.

#include<stdio.h>
#include<conio.h>
#include<string.h>

void main() {

FILE *fp;
char s[80],ch;
int len=0;

clrscr();

fp=fopen("data.txt","r");


while(fgets(s,79,fp)!=NULL)

len=len+strlen(s);   /* length of each string */
    /* spaces and newlines are also counted */

fclose(fp);

printf("length of file = %d",len);

getch();
}



----------------------------------------------------------------------------------------------------------------

(c) Write a program to add the contents of one file at the end of another.

Solution:


NOTE: Make two file as "FILE1.TXT" and "FILE2.TXT" in bin directory and then run the program. The contents of FILE1.TXT will be appended to FILE2.TXT.

#include<stdio.h>
#include<conio.h>
void main() {

FILE *f1,*f2;
char ch;

clrscr();

f1=fopen("FILE1.TXT","r");    /* file to append */
f2=fopen("FILE2.TXT","a+");   /* file to be appended */

if(f1==NULL || f2==NULL) {
printf("\ncannot open one of files!");

exit();
}

while(1) {

ch=fgetc(f1);

if(ch==EOF) {
break;
}

fputc(ch,f2);

}

fclose(f1);
fclose(f2);

printf("\ntask completed successfully!");

getch();

}


---------------------------------------------------------------------------------------------------------------

(d) Suppose a file contains student’s records with each record containing name and age of a student. Write a program to read these records and display them in sorted order by name.

Solution:


#include<stdio.h>
#include<conio.h>
#define N 100
struct student {
char name[30];
int age;
};

void main() {

struct student std;
struct student s[N];  /* size of array of structure defined globally for
convenience */

FILE *fp;
int flag=0,ch,i=0,count=0;
long recsize;
char another='y';
void srt_print();   /* funtion to sort and print */

clrscr();

recsize=sizeof(std);

fp=fopen("STUDENT.DAT","rb+");
if(fp==NULL) {
fp=fopen("STUDENT.DAT","wb+");
if(fp==NULL)
exit();
}

while(1) {

clrscr();

printf("\t\t\tStudent database\n");
printf("\t\t\t****************\n\n\n");
printf("\t\t\n1: Add student data\n");
printf("\t\t\n2: List student data\n");
printf("\t\t\n0: Exit");

gotoxy(2,24);
printf("Your choice: ");
scanf("%d",&ch);

switch(ch) {

case 1:

clrscr();

while(another=='y' || another=='Y') {

clrscr();

printf("\t\tAdd student data\n");
printf("\t\t****************\n\n");
printf("\nEnter student name: ");
scanf("%s",&std.name);
printf("\n\naEnter student age: ");
scanf("%d",&std.age);

fseek(fp,0,SEEK_END);
fwrite(&std,recsize,1,fp);

gotoxy(2,24);
printf("Add another information(Y/N): ");
fflush(stdin);
another=getche();

}
break;

case 2:

clrscr();

printf("\t\tList student data\n");
printf("\t\t*****************\n\n");
rewind(fp);
while(fread(&std,recsize,1,fp)==1) {
s[i]=std;
flag=1;
i++;
count++;
}

srt_print(&s,count);       /* function to print names */

if(flag==0) {

printf("\n\n\nNo data found!\n");

}
printf("\n\n\npress any key to return...");
getch();

break;

case 0:

fclose(fp);
exit();

default:

printf("wrong input!\n");
exit();

   }

 }

}
/******** main ends ************/


/****  sorting and printing function ****/
void srt_print(struct student *ss, int n) {

struct student temp;
int i,j;


for(i=0;i<=n;i++) {

for(j=i+1;j<n;j++) {


/* checking first alphabets of both names */


if(ss[i].name[0] > ss[j].name[0]) {

temp=ss[i];
ss[i]=ss[j];
ss[j]=temp;
}


/* if first alphabets are same */


else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1] > ss[j].name[1]) {

temp=ss[i];
ss[i]=ss[j];
ss[j]=temp;

}


/* if first 2 alphabets are same */


else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2] > ss[j].name[2]) {

temp=ss[i];
ss[i]=ss[j];
ss[j]=temp;
}
}


/* if first 3 alphabets are same */


else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2]==ss[i].name[2]) {

if(ss[i].name[3] > ss[j].name[3]) {

temp=ss[i];
ss[i]=ss[j];
ss[j]=ss[i];
}
}
}


/* if first four 4 alphabets are same */


else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2]==ss[j].name[2] && ss[i].name[2]==ss[j].name[2]) {

if(ss[i].name[3]==ss[j].name[3]) {

if(ss[i].name[4] > ss[j].name[4]) {

temp=ss[i];
ss[i]=ss[j];
ss[j]=ss[i];

    }
   }
  }
 }

 }
}


/* printing sorted list */


for(i=0;i<n;i++) {

printf("\n%10s\t\t%2d\n",ss[i].name,ss[i].age);

 }

}

--------------------------------------------------------------------------------------------------------------

(e) Write a program to copy one file to another. While doing so replace all lowercase characters to their equivalent uppercase characters.

Solution:

NOTE: Make a file as "FILE.TXT" in bin directory and write/paste some text in it. then run the program and you will receive another file as "RESULT.TXT" with uppercase letters.


#include<stdio.h>
#include<conio.h>

void main() {

FILE *fr,*fw;
char a[1000];
char ch,upr;
clrscr();

fr=fopen("SOURCE.TXT","r");

if(fr==NULL) {
printf("cannot open source file!\n");

}

fw=fopen("RESULT.TXT","w");

if(fw==NULL) {
printf("cannot open target file!\n");

}

while(1) {

ch=fgetc(fr);

if(ch==EOF)
break;

else {

if(ch>=97 && ch<=122) {

ch=ch-32;

}

fputc(ch,fw);
}

}
fclose(fr);
fclose(fw);

printf("Task completed!");
getch();
}


----------------------------------------------------------------------------------------------------------------

(f) Write a program that merges lines alternately from two files and writes the results to new file. If one file has less number of lines than the other, the remaining lines from the larger file should be simply copied into the target file.

Solution:


----------------------------------------------------------------------------------------------------------------

(g) Write a program to display the contents of a text file on the screen. Make following provisions:
Display the contents inside a box drawn with opposite corner
co-ordinates being ( 0, 1 ) and ( 79, 23 ). Display the name of the file whose contents are being displayed, and the page numbers in the zeroth row. The moment one screenful of file has been displayed, flash a message ‘Press any key...’ in 24th row. When a key is hit, the next page’s contents should be displayed, and so on till the end of file.

Solution:


#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<types.h>
#include<stat.h>
#include<fcntl.h>

void box();
void print();

void main() {

int inhandle,bytes,pg=1;
FILE *fp;
char source[80],buffer[1400];

clrscr();

printf("Enter file name: ");
gets(source);

inhandle=open(source, O_RDONLY);

if(inhandle==-1) {

printf("cannot open file!");
exit();

}

clrscr();

while(1) {



bytes=read(inhandle,buffer,1387);


if(bytes>0) {

gotoxy(32,1);          /* showing filename */
printf("%s",strupr(source));

gotoxy(70,1);
printf("Pg: %3d",pg);      /* showing page number */

box();   /* passing the heading and page number to the function */

print(buffer);    /* passing the buffer to the function */

}

else  {

gotoxy(70,1);
printf("Pg: %3d",pg);
break;
}

++pg;
}

close(inhandle);

getch();
}

/********************************/
/* function to print the buffer */
/********************************/


void print(char s[1400]) {


int x=4,y=3,i=0;

while(s[i]!=EOF) {


gotoxy(x,y);
printf("%c",s[i]);

if(x>74) {

x=4;
y+=1;

}

if(y>21) {

gotoxy(2,24);
printf("press any key to go to next page...");


x=4;
y=3;

getch();

clrscr();
box();
}

x++;
i++;

}

}


/****************************/
/* function to draw the box */
/****************************/


void box() {

int i,j;

for(i=2;i<=77;i++) {

gotoxy(i,2);
printf("%c",196);

gotoxy(i,23);
printf("%c",196);

}

for(j=3;j<=22;j++) {

gotoxy(2,j);
printf("%c",179);

gotoxy(77,j);
printf("%c",179);

}

gotoxy(77,23);
printf("%c",217);

gotoxy(77,2);
printf("%c",191);

gotoxy(2,23);
printf("%c",192);

gotoxy(2,2);
printf("%c",218);

}


----------------------------------------------------------------------------------------------------------------

(h) Write a program to encrypt/decrypt a file using:
(1) An offset cipher: In an offset cipher each character from the source file is offset with a fixed value and then written to the target file.
For example, if character read from the source file is ‘A’, then convert this into a new character by offsetting ‘A’ by a fixed value, say 128, and then writing the new character to the target file.
(2) A substitution cipher: In this each character read from the source file is substituted by a corresponding predetermined character and this character is written to the target file.
For example, if character ‘A’ is read from the source file, and if we have decided that every ‘A’ is to be substituted by ‘!’, then a ‘!’ would be written to the target file in place of every ‘A’ Similarly, every ‘B’ would be substituted by ‘5’ and so on.

Solution:

Offset cipher Encryption:

#include<stdio.h>
#include<conio.h>

void main() {         /* offset cipher encryption */

/* every character has been added to 128 and the new value has been
written */

FILE *fp,*ft;
char ch;

clrscr();

fp=fopen("data.txt","r");
ft=fopen("temp.txt","w");

if(fp==NULL)  {
printf("cannot open one of files!");
exit();
}

while(1) {

ch=fgetc(fp);

if(ch==EOF)
break;


ch=ch+128;              /* offset cipher encryption */

fputc(ch,ft);

}

fclose(fp);
fclose(ft);

remove("data.txt");
rename("temp.txt","data.txt");


printf("task completed!");
getch();
}


Offset cipher Decryption:

#include<stdio.h>
#include<conio.h>
void main() {        /* offset cipher decryption */

FILE *fp,*ft;
char ch;

fp=fopen("data.txt","r");
ft=fopen("temp.txt","w");

if(fp==NULL)  {
printf("cannot open one of files!");

exit();
}



while(1) {

ch=fgetc(fp);

if(ch==EOF)
break;


ch=ch-128;              /* decryption */

fputc(ch,ft);

}

fclose(fp);
fclose(ft);

remove("data.txt");
rename("temp.txt","data.txt");

printf("task completed!");
getch();

}

Substitution cipher encryption:

#include<stdio.h>
#include<conio.h>

void main() {            /* substitution cipher encryption */

/* all vowels have been exchanged with first five ascii characters and
 every space has been converted to 6th ascii character */

FILE *fp,*ft;
char ch;

clrscr();

fp=fopen("data.txt","r");
ft=fopen("temp.txt","w");

if(fp==NULL)  {
printf("cannot open one of files!");
exit();
}

while(1) {

ch=fgetc(fp);

if(ch==EOF)
break;

encrypt(&ch);          /* function for encryption */

fputc(ch,ft);

}

fclose(fp);
fclose(ft);

remove("data.txt");
rename("temp.txt","data.txt");


printf("task completed!");
getch();
}
encrypt(char *c) {

if(*c=='a') {
*c='!';
}

if(*c=='e') {
*c='@';
}

if(*c=='i') {
*c='#';
}

if(*c=='o') {
*c='$';
}

if(*c=='u') {
*c='%';
}

if(*c==' ') {
*c='^';
}

return *c;
}

Substitution cipher Decryption:

#include<stdio.h>
#include<conio.h>
void main() {

     /* substitution cipher's decryption */


FILE *fp,*ft;
char ch;

fp=fopen("data.txt","r");
ft=fopen("temp.txt","w");

if(fp==NULL)  {
printf("cannot open one of files!");

exit();
}



while(1) {

ch=fgetc(fp);

if(ch==EOF)
break;

decrypt(&ch);    /* function for decryption */

fputc(ch,ft);

}

fclose(fp);
fclose(ft);

remove("data.txt");
rename("temp.txt","data.txt");

printf("task completed!");
getch();

}

decrypt(char *c) {

if(*c=='!')
*c='a';

if(*c=='@')
*c='e';

if(*c=='#')
*c='i';

if(*c=='$')
*c='o';

if(*c=='%')
*c='u';

if(*c=='^')
*c=' ';

return *c;


}
----------------------------------------------------------------------------------------------------------------

(i) In the file ‘CUSTOMER.DAT’ there are 100 records with the following structure:
struct customer
{
int accno ;
char name[30] ;
float balance ;
} ;
In another file ‘TRANSACTIONS.DAT’ there are several records with the following structure:
struct trans
{
int accno ,
char trans_type ;
float amount ;
} ;
The parameter trans_type contains D/W indicating deposit or withdrawal of amount. Write a program to update ‘CUSTOMER.DAT’ file, i.e. if the trans_type is ‘D’ then update the balance of ‘CUSTOMER.DAT’ by adding amount to balance for the corresponding accno. Similarly, if trans_type is ‘W’ then subtract the amount from balance. However, while subtracting the amount make sure that the amount should not get overdrawn, i.e. at least 100 Rs. Should remain in the account.

Solution:

NOTE: If on withdrawal, the balance subtracts to less than 100. The withdrawal will not be performed.
  #include<stdio.h>
#include<conio.h>
void main() {

struct customer {
int accno;
char name[30];
float balance;
}cust;
struct trans {
     int accno;
     char trans_type;
     float amount;
     }tra;
FILE *fp,*ft,*ftemp;
int flag=0;
long recsize,retsize;
char another,ch;
clrscr();

fp=fopen("CUSTOMER.DAT","rb+");

if(fp==NULL) {

fp=fopen("CUSTOMER.DAT","wb+");

if(fp==NULL)

printf("cannot open customer data file!\n");

exit();

}

ft=fopen("TRANSACTIONS.DAT","rb+");

if(ft==NULL) {

ft=fopen("TRANSACTIONS.DAT","wb+");

if(ft==NULL)

printf("cannot open transactions file!\n");

exit();

}

recsize=sizeof(cust);
retsize=sizeof(tra);

while(1) {

clrscr();

printf("\t\tCutomer Transactions:\n");
printf("\t\t*********************\n\n\n");
printf("\t1: Add customer information:\n\n");
printf("\t2: Add transaction information:\n\n");
printf("\t3: List customer information:\n\n");
printf("\t4: List transaction information:\n\n");
printf("\t5: Perform transaction:\n\n");
printf("\t0: Exit:\n\n\n");

gotoxy(2,24);
printf("Your choice: ");
fflush(stdin);
ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd customer information:\n");
printf("\t\t*************************\n\n");
printf("\nEnter account number: ");
scanf("%d",&cust.accno);
printf("\n\nEnter name: ");
scanf("%s",cust.name);
printf("\n\nEnter balance: ");
fflush(stdin);
scanf("%f",&cust.balance);


fwrite(&cust,recsize,1,fp);

gotoxy(2,24);
printf("Add another customer information(Y/N): ");
another=getche();

clrscr();

}
break;

case '2':

clrscr();

fseek(ft,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd transaction information:\n");
printf("\t\t****************************\n\n\n");
printf("Enter existing customer account number: ");
scanf("%d",&tra.accno);
printf("\n\nEnter transaction type(D/W): ");
fflush(stdin);
scanf("%c",&tra.trans_type);
printf("\n\nEnter amount for transaction: ");
fflush(stdin);
scanf("%f",&tra.amount);


fwrite(&tra,retsize,1,ft);

gotoxy(2,24);
printf("Enter another information(Y/N): ");
another=getche();

clrscr();
}
break;

case '3':

clrscr();

printf("\t\tList customer information:\n");
printf("\t\t**************************\n\n");

rewind(fp);
while(fread(&cust,recsize,1,fp)==1) {
printf("\n%5d\t%-8s\t%5.2f\n",cust.accno,cust.name,cust.balance);
flag=1;
}

if(flag==0) {
gotoxy(2,12);
printf("No customer information found!\n");
}
printf("\n\npress any key to go back...");
getch();

break;

case '4':

clrscr();

printf("\t\tList transaction information:\n");
printf("\t\t*****************************\n\n");

rewind(ft);
while(fread(&tra,retsize,1,ft)==1)  {
printf("\n%5d\t%c\t%6.2f\n",tra.accno,tra.trans_type,tra.amount);
flag=1;
}

if(flag==0) {
gotoxy(2,12);
printf("No transaction information found!\n");
}

printf("\n\npress any key to go back...");
getch();

break;

case '5':

clrscr();

printf("\t\tPerform transactions\n");
printf("\t\t********************\n\n");

rewind(fp);

while(fread(&cust,recsize,1,fp)==1) {

rewind(ft);

while(fread(&tra,retsize,1,ft)==1) {

if(cust.accno==tra.accno) {

flag=1;

if(tra.trans_type=='D' || tra.trans_type=='d') {

cust.balance+=tra.amount;

fseek(fp,-recsize,SEEK_CUR);
fwrite(&cust,recsize,1,fp);

}

else if(tra.trans_type=='W' || tra.trans_type=='w') {

if((cust.balance-tra.amount)>=100)  {

cust.balance-=tra.amount;

fseek(fp,-recsize,SEEK_CUR);
fwrite(&cust,recsize,1,fp);

}

}

}
}
}

fclose(ft);

ftemp=fopen("TEMP.DAT","rb+");

if(ftemp==NULL) {

ftemp=fopen("TEMP.DAT","wb+");

}

remove("TRANSACTIONS.DAT");
rename("TEMP.DAT","TRANSACTIONS.DAT");

ft=fopen("TRANSACTIONS.DAT","rb+");

if(ft==NULL) {

ft=fopen("TRANSACTIONS.DAT","wb+");

}

if(flag==0) {

gotoxy(2,12);
printf("No active transactions\n");

}

else if(flag>0) {

gotoxy(2,12);
printf("Transactions performed seccussfully!\n");
gotoxy(2,14);
printf("NOTE: withdrawl for low balance accounts has not been performed\n");

}
gotoxy(2,24);
printf("press any key to return...");
getch();

break;

case '0':

fclose(fp);
fclose(ft);
exit();

}
}

}

---------------------------------------------------------------------------------------------------------------

(j) There are 100 records present in a file with the following structure:
struct date
{
int d, m, y ;
} ;
struct employee
{
int empcode[6] ;
char empname[20] ;
struct date join_date ;
float salary ;
} ;
Write a program to read these records, arrange them in ascending order of join_date and write them in to a target file.

Solution:


----------------------------------------------------------------------------------------------------------------

(k) A hospital keeps a file of blood donors in which each record has the format:
Name: 20 Columns
Address: 40 Column
Age: 2 Columns
Blood Type: 1 Column (Type 1, 2, 3 or 4)
Write a program to read the file and print a list of all blood donors whose age is below 25 and blood is type 2. 

Solution:

Program to creat record file of blood donors



/* This program will make a file of blood donors and save information in it */

         /* Writing program */

#include<stdio.h>
#include<conio.h>
void main() {

FILE *fp;
char another='y';

struct blood {
  char name[50];
  char adr[50];
  int age;
  int bld;
  } b;

clrscr();

fp=fopen("BLOODBANK.DAT","wb");

if(fp==NULL) {
printf("cannot open target file!\n");
exit();
}

while(another=='Y' || another=='y') {

clrscr();
printf("\t\tInformation of Blood donor\n");
printf("\t\t**************************\n\n\n");
printf("Enter the name: ");
scanf("%s",b.name);
printf("\n\nenter the address: ");
scanf("%s",b.adr);
printf("\n\nenter the age: ");
scanf("%d",&b.age);
printf("\n\nenter the blood group(1/2/3/4): ");
scanf("%d",&b.bld);

fprintf(fp,"%s\t%s\t%d\t%d",b.name,b.adr,b.age,b.bld);

printf("\n\n\nenter more information(Y/N): ");
fflush(stdin);

another=getch();

}

fclose(fp);

}



Program to read record file for specifications





/* This program will read the information from the file made by writing program */

           /* Reading Program */

#include<stdio.h>
#include<conio.h>
void main() {

FILE *fp;
char ch;

struct blood {
      char name[50];
      char adr[50];
      int age;
      int bld;
      }b;
clrscr();

fp=fopen("BLOODBANK.DAT","rb");

if(fp==NULL) {
printf("cannot open source file!\n\n");
exit();
}

while(fscanf(fp,"%s\t%s\t%d\t%d",&b.name,&b.adr,&b.age,&b.bld)!=EOF)
if(b.age<25 && b.bld==2) {
printf("\n%s\t %s\t%2d\t %d",b.name,b.adr,b.age,b.bld);
}
fclose(fp);

getch();
}

----------------------------------------------------------------------------------------------------------------
(l) Given a list of names of students in a class, write a program to store the names in a file on disk. Make a provision to display the nth name in the list (n is data to be read) and to display all names starting with S.

Solution:


#include<stdio.h>
#include<conio.h>
void main() {

struct name {
    int sn;
    char name[30];
    }s;
int i,num,flag=0;
long recsize;
char another,ch;
FILE *fp;
clrscr();

fp=fopen("NAMES.DAT","rb+");

if(fp==NULL) {

fp=fopen("NAMES.DAT","wb+");

if(fp==NULL)

printf("cannot open file! \n");
exit();
}

recsize=sizeof(s);

while(1) {

clrscr();
printf("\t\tStudent Names:\n");
printf("\t\t**************\n\n\n");
printf("\t1: Add names of students:\n\n");
printf("\t2: Search a student name:\n\n");
printf("\t3: List all student names:\n\n");
printf("\t4: List all names starting with 'S':\n\n");
printf("\t0: Exit\n\n");


gotoxy(2,24);
printf("Your choice: ");
fflush(stdin);

ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd names of students:\n");
printf("\t\t**********************\n\n");
printf("Enter student number: ");
scanf("%d",&s.sn);
printf("\n\nEnter student name: ");
scanf("%s",s.name);


fwrite(&s,recsize,1,fp);

gotoxy(2,24);
printf("Enter another name(Y/N): ");
fflush(stdin);
another=getche();

clrscr();
}
break;

case '2':

clrscr();

printf("\t\tSearch a student name:\n");
printf("\t\t**********************\n\n");
printf("Enter student number: ");
scanf("%d",&num);

rewind(fp);

while(fread(&s,recsize,1,fp)==1) {

if(s.sn==num) {

printf("\n\nStudent Number: %5d\n\n",s.sn);
printf("Student name:   %s\n\n",s.name);

flag=1;
break;
}
 }

if(flag==0) {
printf("\n\n\nNo such name found!\n");
}
gotoxy(2,24);
printf("press any key to return...\n");
getch();

break;

case '3':

clrscr();

printf("\t\tList all student names\n");
printf("\t\t**********************\n\n\n");

rewind(fp);

while(fread(&s,recsize,1,fp)==1)  {
printf("\n%5d\t%-10s\n",s.sn,s.name);
flag=1;
}

if(flag==0) {
printf("\n\n\nNo name found!\n");
}

printf("\n\n\npress any key to return...\n");
getch();
break;

case '4':

clrscr();

printf("\t\tAll name starting with 'S':\n");
printf("\t\t***************************\n\n\n");

rewind(fp);
while(fread(&s,recsize,1,fp)==1) {

if(strncmp('s',s.name[0])==0) {     /* comparing only first character of \
      name if it is "s" */
printf("\n%5d\t%-10s\n",s.sn,s.name);
flag=1;
}
}

if(flag==0) {
printf("\n\n\nNo name starting with \'S\' found!\n");
}

printf("\n\n\npress any key to return...\n");
getch();
break;

case '0':

fclose(fp);
exit();

}
 }

 }


----------------------------------------------------------------------------------------------------------------

(m) Assume that a Master file contains two fields, Roll no. and name of the student. At the end of the year, a set of students join the class and another set leaves. A Transaction file contains the roll numbers and an appropriate code to add or delete a student.
Write a program to create another file that contains the updated list of names and roll numbers. Assume that the Master file and the Transaction file are arranged in ascending order by roll numbers. The updated file should also be in ascending order by roll numbers.

Solution:

Note:- This program ( all the 3 ) are ideally for single. After you have ran it once, check the results and delete the updated list file before running it again. Assign roll number in ascending orders by roll numbers. And process data according to ascending nature.

1- first program will let you save data in masterfile.
2- second program will let you add or delete data and will generate an updated list in text mode.
3- obtain the updated list and check it ( assuming you have processed data as instructed).


1. program to creat master file.


#include<stdio.h>
#include<conio.h>
#include<string.h>

void main() {

FILE *fp;
struct student {
int rl;
char name[50];
}s;
char ch,another;
clrscr();

fp=fopen("MASTERFILE.DAT","rb+");

if(fp==NULL) {

fp=fopen("MASTERFILE.DAT","wb+");

if(fp==NULL)
puts("cannot open master file!");
exit();
}


while(1) {

clrscr();

gotoxy(30,2);
printf("Masterfile\n");
gotoxy(30,3);
printf("**********\n\n\n");
gotoxy(20,6);
printf("1: Enter student data: ");
gotoxy(20,8);
printf("2: Read student data: ");
gotoxy(20,10);
printf("0: Exit: ");

gotoxy(2,24);
printf("Your choice: ");
fflush(stdin);

ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

clrscr();

gotoxy(2,24);
printf("NOTE: assign roll numbers in ascending order");
gotoxy(20,5);
printf("Enter roll number: ");
scanf("%d",&s.rl);

gotoxy(20,7);
printf("Enter name: ");
fflush(stdin);
gets(s.name);

fwrite(&s,sizeof(s),1,fp);



gotoxy(20,10);
printf("Add more data(Y/N): ");
fflush(stdin);

another=getche();

}

break;

case '2':

clrscr();

gotoxy(30,2);
printf("Student data");
gotoxy(30,3);
printf("************\n\n");

rewind(fp);

while(fread(&s,sizeof(s),1,fp)==1) {

printf("\n%d\t%s\n",s.rl,s.name);

}

printf("\n\npress any key to return...");
getch();

break;

case '0':

fclose(fp);
exit();

}
}


}

2. program to creat transaction file and generate updated list


#include<stdio.h>
#include<conio.h>
#include<string.h>
#define N 100

void main() {

FILE *ft,*fu,*fm,*ftemp;

struct student {
int rl;
char name[50];
}s,ss[N],temp;

struct transaction {
   char stats;
   int rl;
   char name[50];
   }t;

int flag=0;
char ch,another;
clrscr();

fm=fopen("MASTERFILE.DAT","rb+");

if(fm==NULL) {

printf("Masterfile doesn't exist!");

}

ft=fopen("TRANSACTION.DAT","rb+");

if(ft==NULL) {

ft=fopen("TRANSACTION.DAT","wb+");

if(ft==NULL)
puts("cannot open transactions file!");
exit();
}

fu=fopen("UPDATELIST.TXT","w+");

if(fu==NULL) {

puts("cannot open target file!");
exit();
}

while(1) {

clrscr();

gotoxy(30,2);
printf("Transaction-File\n");
gotoxy(30,3);
printf("****************\n\n\n");
gotoxy(20,6);
printf("1: ADD/DELETE student data from master list: ");
gotoxy(20,8);
printf("2: Read transaction data: ");
gotoxy(20,10);
printf("3: Creat updated list: ");
gotoxy(20,12);
printf("0: Exit:");

gotoxy(2,24);
printf("Your choice: ");
fflush(stdin);

ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(ft,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

clrscr();

gotoxy(2,23);
printf("NOTE: data to be deleted should match master list");
gotoxy(2,24);
printf("NOTE: data to be added should follow the ascending nature of master list");
gotoxy(20,5);
printf("ADD/DELETE student(A/D): ");
scanf("%c",&t.stats);
gotoxy(20,7);
printf("Enter roll number: ");
scanf("%d",&t.rl);
gotoxy(20,9);
printf("Enter name: ");
fflush(stdin);
gets(t.name);

fwrite(&t,sizeof(t),1,ft);

gotoxy(20,12);
printf("Add more data(Y/N): ");
fflush(stdin);

another=getche();

}

break;

case '2':

clrscr();

gotoxy(30,2);
printf("Student data");
gotoxy(30,3);
printf("************\n\n");

rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

printf("\n");

if(t.stats=='a' || t.stats=='A') {
printf("ADD");
}

else {
printf("DELETE");
}
printf("\t%d\t%s\n",t.rl,t.name);

}

printf("\n\npress any key to return...");
getch();

break;

case '3':

clrscr();

gotoxy(30,2);
printf("make updated list");
gotoxy(30,3);
printf("*****************\n\n");


rewind(fm);

while(fread(&s,sizeof(s),1,fm)==1) {

flag=0;

rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

if(t.rl==s.rl ) {

if(t.stats=='d' || t.stats=='D') {
flag=1;
}

}

}

if(flag==0)

fprintf(fu,"\n%d\t%-s\n",s.rl,s.name);


}


rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

if(t.stats=='a' || t.stats=='A') {

fprintf(fu,"\n%d\t%-s\n",t.rl,t.name);

}

}

ftemp=fopen("TEMP.DAT","wb+");

fclose(ftemp);
fclose(ft);

remove("TRANSACTION.DAT");
rename("TEMP.DAT","TRANSACTION.DAT");

ft=fopen("TRANSACTION.DAT","rb+");

gotoxy(2,24);
printf("press any key to continue...");
getch();

break;
case '0':

fclose(fm);
fclose(ft);
fclose(fu);
exit();

}
}


}

-----------------------------------------------------------------------------------------------------------------

(n) In a small firm employee numbers are given in serial numerical order, that is 1, 2, 3, etc.
− Create a file of employee data with following information: employee number, name, sex, gross salary.
− If more employees join, append their data to the file.
− If an employee with serial number 25 (say) leaves, delete the record by making gross salary 0.
− If some employee’s gross salary increases, retrieve the record and update the salary.
Write a program to implement the above operations.

Solution:


#include<stdio.h>
#include<conio.h>
void main() {

struct emp {
  int empno;
  char name[30];
  char sex;
  float gs;
  } e;
FILE *fp,*ft;
int long recsize;
int empn,flag=0;
float new_sal;
char another,ch;
clrscr();

recsize=sizeof(e);

fp=fopen("EMP.DAT","rb+");

if(fp==NULL) {

fp=fopen("EMP.DAT","wb+");
if(fp==NULL)

exit();

}

while(1) {

clrscr();

printf("\t\tEmployee database management\n");
printf("\t\t****************************\n");
printf("\n\n\t1: Add another employee: ");
printf("\n\n\t2: Add salary information of employee: ");
printf("\n\n\t3: List all records: ");
printf("\n\n\t4: Delete employee with 0 salary: ");
printf("\n\n\t0: Exit:");

gotoxy(2,24);
printf("your choice: ");
fflush(stdin);
ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);  /* seeking cursor to reach at the end of file */

another='Y';

while(another=='Y' || another=='y') {

printf("\n\tEnter new employee information\n");
printf("\t******************************\n\n\n");

printf("\nEnter employee number: ");
scanf("%d",&e.empno);

printf("\n\nEnter employee name: ");
scanf("%s",e.name);

printf("\n\nEnter sex(M/F/O): ");
scanf(" %c",&e.sex);

printf("\n\nEnter gross salary: ");
scanf("%f",&e.gs);

/* writing new information at the end of file */

fwrite(&e,recsize,1,fp);

printf("\n\n\n\nAdd another employee(Y/N): ");
fflush(stdin);
another=getche();

clrscr();

}

break;

case '2':

clrscr();

another='Y';

while(another=='Y' || another=='y') {

printf("\n\tEnter salary information\n");
printf("\t************************\n\n");


gotoxy(2,23);    /* showing message at the bottom of the screen */

printf("NOTE: to delete an employee, mark his/her salary 0\n");
printf("       then use option 4 from main menu.");

gotoxy(3,5);     /* returning cursor back from the bottom */
printf("Enter employee number: ");
scanf("%d",&empn);  /* asking for employee number to search */

rewind(fp);

while(fread(&e,recsize,1,fp)==1) {

if(e.empno-empn==0) {    /* if employee number matches with structure */

flag=1;              /* condition indicator for printing further messages */

printf("\n\nEnter new salary for employee:  ");

scanf("%f",&e.gs);

e.empno=e.empno;            /* rest information should be same except only\
salary */
e.sex=e.sex;

e.name[30]=e.name[30];

fseek(fp,-recsize,SEEK_CUR);  /* seeking the correct location of data within\
structure in the file */
fwrite(&e,recsize,1,fp);    /* writing data at correct position */

break;

}
}

if(flag==0)       /* conditional indicator used above */
printf("\n\n\n\tinformation does not exist!\n");


printf("\n\nenter another information(Y/N): ");
another=getche();

clrscr();

}

break;

case '4':

clrscr();

printf("\n\n\tDelete employee\n");
printf("\t***************\n\n");

ft=fopen("TEMP.DAT","w");    /* opening new temporary file */

rewind(fp);     /* taking cursor back to the very beginning of file */

while(fread(&e,recsize,1,fp)==1)  { /* matching each salary  */


if(e.gs!=0.0 || e.gs!=0) {      /* if salary is not 0 then data will be written to new
    file */

flag=1;

fwrite(&e,recsize,1,ft);

}
}
fclose(fp);
fclose(ft);

remove("EMP.DAT");      /* removing original file with 0 salary and renaming\
  temporary without 0 salary as the original file */

rename("TEMP.DAT","EMP.DAT");

fp=fopen("EMP.DAT","rt+");  /* opening the new file, it opens because it has
      not been opened before */
   /* a file cannot be opened twice during
      execution as you know */

if(flag>0) {
printf("\n\n\nall records with 0 gross salary have been deleted. \n");
}


gotoxy(2,24);
printf("\n\n\npress any key to return...");
getch();

break;

case '0':

fclose(fp);
exit();

case '3':

clrscr();

printf("\t\tList all employees\n");
printf("\t\t******************\n\n\n");

rewind(fp);

while(fread(&e,recsize,1,fp)==1)  {

flag=1;

printf("%2d\t%6s\t%c\t%.2f\n\n",e.empno,e.name,e.sex,e.gs);

}

if(flag==0)

printf("\n\n\tNo records exist!\n\n");

printf("\n\npress any key to return... ");

getch();    /* this is very important place, if we don't stop screen here \
      after reading and printing the list,we won't be able to see it
      and it will disappear and will return to main menu because
      of "break" statement. */
break;

    }
  }


}
linkfloat() {  /* function to avoid possible errors because of floats */
float a=0,*b;
b=&a;
a=*b;
return 0;
}

-----------------------------------------------------------------------------------------------------------------

(o) Given a text file, write a program to create another text file deleting the words “a”, “the”, “an” and replacing each one of them with a blank space.

Solution:

NOTE: Make a file "FILE.TXT" in bin directory and write/paste something in it, then run the program, you will get another file as "NEW.TXT" as result of the program.

#include<stdio.h>

#include<conio.h>

#include<string.h>



void replace();



void main() {

FILE *fp,*ft;
char str[80],target[80];
clrscr();

fp=fopen("FILE.TXT","r");

if(fp==NULL) {

puts("cannot open source file!");
exit();
}

ft=fopen("NEW.TXT","w");

if(ft==NULL) {

puts("cannot open target file!");
exit();
}

while(fgets(str,79,fp)!=NULL) {

replace(str,&target);

fputs(target,ft);

}

fclose(fp);
fclose(ft);

printf("\nTask completed!");
getch();

}


void replace(char *s, char *s1) {

int i=0,j=0,k=0;
char temp[100],temp2[100],main[100],*t=temp,*m=main;


/* copying to temporary string */

while(*s!='\0') {

*t=*s;

t++;
s++;

}

*t='\0';

/**********************/
/* checking each word */
/**********************/


while(temp[i]!='\0') {

temp2[j]=temp[i];

if(temp[i]==' ') {

temp2[j]='\0';

if(strcmpi(temp2,"the")==0) {

strcpy(temp2," ");
}

else if(strcmpi(temp2,"an")==0) {

strcpy(temp2," ");

}

else if(strcmpi(temp2,"a")==0) {

strcpy(temp2," ");

}

j=0;

while(temp2[j]!='\0') {

main[k]=temp2[j];

k++;
j++;

}

main[k]=' ';  /* adding space after each word is copied */

k++;     /* increment so that the next word won't replace the space */

j=-1;

}

i++;
j++;
}

temp2[j]='\0';              /* last word terminated */

if(strcmpi(temp2,"the")==0){    /* checking last word too */

strcpy(temp2," ");
}

else if(strcmpi(temp2,"an")==0) {

strcpy(temp2," ");
}

else if(strcmpi(temp2,"a")==0) {

strcpy(temp2," ");
}

/***************************/
/* last word of the string */
/***************************/

else {

j=0;

while(temp2[j]!='\0') {

main[k]=temp2[j];

k++;
j++;
}

main[k]='\0';   /* new string is completely ready */

}

while(*m!='\0') {

*s1=*m;

s1++;
m++;

}

*s1='\0';

}

-----------------------------------------------------------------------------------------------------------------

(p) You are given a data file EMPLOYEE.DAT with the following record structure:
struct employee {
int empno ;
char name[30] ;
int basic, grade ;
} ;
Every employee has a unique empno and there are supposed to be no gaps between employee numbers. Records are entered into the data file in ascending order of employee number, empno. It is intended to check whether there are missing employee numbers. Write a program segment to read the data file records sequentially and display the list of missing employee numbers.

Solution:

NOTE: assign employee numbers in ascending order only.

#include<stdio.h>

#include<conio.h>

void main() {



struct employee {

int empno;

char name[30];
int basic,grade;
}e;
FILE *fp;
int num=0;
long recsize;
char another,ch;
clrscr();

fp=fopen("EMPLOYEE.DAT","rb+");
if(fp==NULL) {
fp=fopen("EMPLOYEE.DAT","wb+");

if(fp==NULL)
exit();
}

recsize=sizeof(e);

while(1) {

clrscr();

printf("\t\tEmployee number database:\n");
printf("\t\t*************************\n\n");
printf("\n\t1: Add employee information:\n");
printf("\n\t2: List employee information:\n");
printf("\n\t3: Check missing employee numbers:\n");
printf("\n\t0: Exit:\n\n");

gotoxy(2,24);
printf("your choice: ");
fflush(stdin);
ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd employee information:\n");
printf("\t\t*************************\n\n");

printf("Note: employee numbers should be given in ascending order\n\n");

printf("\nEnter employee number: ");
scanf("%d",&e.empno);
printf("\n\nEnter employee name: ");
scanf("%s",e.name);
printf("\n\nEnter employee basic salary: ");
scanf("%d",&e.basic);
printf("\n\nEnter employee grade(1/2/3): ");
scanf("%d",&e.grade);

fwrite(&e,recsize,1,fp);

gotoxy(2,24);
printf("Add another employee information(Y/N): ");
fflush(stdin);
another=getche();

clrscr();

}

break;

case '2':

clrscr();

printf("\t\tList employee information:\n");
printf("\t\t**************************\n\n\n");

rewind(fp);
while(fread(&e,recsize,1,fp)==1) {

printf("\n%3d\t%8s\t%5d\t%d\n",e.empno,e.name,e.basic,e.grade);

}

printf("\n\npress any key to return...\n");
getch();

break;

case '3':

clrscr();

printf("\t\tMissing employee numbers:\n");
printf("\t\t*************************\n\n");

rewind(fp);
while(fread(&e,recsize,1,fp)==1) {
num=e.empno;  /* assigning the value of first employee number */
break;
}

rewind(fp);  /* again rewinding the file to read from beginning */

while(fread(&e,recsize,1,fp)==1) {

if(num!=e.empno) {    /* if assigned number is smaller than employee number
we will print all the number between them */
while(num<e.empno) {

printf("%4d ",num);

num++;
}
num=e.empno+1;

}

 /* we will assign greater value than employee number
    to make sure that both don't match until another
    greater employee number is found     */

else

num=e.empno+1;

}

printf("\n\n press any key to return...");
getch();

break;

case '0':

fclose(fp);
exit();

}
}
}

-----------------------------------------------------------------------------------------------------------------

(q) Write a program to carry out the following:
− To read a text file “TRIAL.TXT” consisting of a maximum of 50 lines of text, each line with a maximum of 80 characters.
− Count and display the number of words contained in the file.
− Display the total number of four letter words in the text file.
Assume that the end of a word may be a space, comma or a full-stop followed by one or more spaces or a newline character.

Solution:

NOTE: Make a file "TRIAL.TXT" in bin directory and write something in it ,then run the program.

#include<stdio.h>

#include<conio.h>

void main() {



FILE *fp;

char s[80];

int twd,fwd,tw=0,fw=0;
void word();
clrscr();

fp=fopen("TRIAL.TXT","r");
if(fp==NULL) {

exit();
}

while(fgets(s,79,fp)!=NULL)  {
word(s,&twd,&fwd);
tw=tw+twd;
fw=fw+fwd;
}

fclose(fp);

printf("\nTotal number of words in text file = %d\n",tw);
printf("\n\nTotal number of 4 letter words = %d\n",fw);

getch();
}

void word(char ss[80],int *tw, int *fw) {

int i=0,tot_wd=0,tot_4_wd=0;

while(ss[i]!='\0') {

/************************/
/* to cound total words */
/************************/

if(ss[i]>=65 && ss[i]<=90 || ss[i]>=97 && ss[i]<=122) {

if(ss[i+1]==' ' || ss[i+1]=='.' || ss[i+1]==',' || ss[i+1]=='\n' ) {

tot_wd++;
}
}



/*********************************/
/* to count total 4 letter words */
/*********************************/

if(ss[i]==' ' || ss[i]==',' || ss[i]=='.')  {

if(ss[i+1]>=65 && ss[i+1]<=90 || ss[i+1]>=97 && ss[i+1]<=122) {

if(ss[i+2]>=65 && ss[i+2]<=90 || ss[i+2]>=97 && ss[i+2]<=122) {

if(ss[i+3]>=65 && ss[i+3]<=90 || ss[i+3]>=97 && ss[i+3]<=122) {

if(ss[i+4]>=65 && ss[i+4]<=90 || ss[i+4]>=97 && ss[i+4]<=122)  {

if(ss[i+5]==' ' || ss[i+5]==',' || ss[i+5]=='.' || ss[i+5]=='\n') {

tot_4_wd++;
     }
    }
   }
  }
 }
}

if(ss[i]>=65 && ss[i]<=90 || ss[i]>=97 && ss[i]<=122) {

if(ss[i+1]>=65 && ss[i+1]<=90 || ss[i+1]>=97 && ss[i+1]<=122) {

if(ss[i+2]>=65 && ss[i+2]<=90 || ss[i+2]>=97 && ss[i+2]<=122) {

if(ss[i+3]>=65 && ss[i+3]<=90 || ss[i+3]>=97 && ss[i+3]<=122)  {

if(ss[i+4]==' ' || ss[i+4]==',' || ss[i+4]=='.' || ss[i+4]=='\n') {

    }
   }
  }
 }
}


i++;

}

*tw=tot_wd;
*fw=tot_4_wd;

}

-----------------------------------------------------------------------------------------------------------------

(r) Write a program to read a list of words, sort the words in alphabetical order and display them one word per line. Also give the total number of words in the list. Output format should be:
Total Number of words in the list is _______
Alphabetical listing of words is:
------
-----
Assume the end of the list is indicated by ZZZZZZ and there are maximum in 25 words in the Text file.

Solution:

NOTE: Make a file as "trial.txt" in bin directory and write some words in it. Words should be in the form of a list. One below another,then run the program.

#include<stdio.h>
#include<conio.h>
#define N 100


/* make a list of words, every words should be written under previous one to
   make sure it's a list of words. */


/* upper case letters will be arranged before small case letter, so it is
   recommended to use the list of either Capital letter or small case letters
   but not both together. */
struct word {
    char wrd [30];
    };

void main() {

struct word w[N];

FILE *fp;
char s1[30];
int i=0,count=0;
void srt_wrd();   /* function to sort and print list */

clrscr();

fp=fopen("TRIAL.TXT","rb+");

while(fgets(s1,30,fp)!=NULL) {
strcpy(w[i].wrd,s1);  /* copying each word in array of structure */
i++;
count++;         /* count of all the words */
}

printf("Total words if file = %3d\n",count);


printf("\t\tList in alphabetical order:\n");
srt_wrd(&w,count);  /* function for sorting and printing list */


fclose(fp);
getch();

}

void srt_wrd( struct word *w, int n) {

int i,j,k=0;
struct word temp;

/***************************************/
/* sorting words in alphabetical order */
/***************************************/

for(i=0;i<=n;i++) {

for(j=i+1;j<n;j++) {


/* testing the first alphabets of two words */

if(w[i].wrd[0] > w[j].wrd[0]) {

temp=w[i];
w[i]=w[j];
w[j]=temp;
}


/* testing the first two alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1] > w[j].wrd[1]) {

temp=w[i];
w[i]=w[j];
w[j]=temp;
}


/* testing first three alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1]==w[j].wrd[1]) {

if(w[i].wrd[2]>w[j].wrd[2]) {

temp=w[i];
w[i]=w[j];
w[j]=temp;
}
}

/* testing first four alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1]==w[j].wrd[1]) {

if(w[i].wrd[2]==w[j].wrd[2] && w[i].wrd[3]>w[j].wrd[2]) {

temp=w[i];
w[i]=w[j];
w[j]=temp;
}
}

 }
}

/*****************************/
/* printing the sorted words */
/*****************************/

for(i=0;i<n;i++) {

printf("%-s\n",w[i].wrd);

k++;

if(k==10) {

printf("\n\npress any key to go to next page...");
getch();

k=1;
clrscr();
}
}


}

--------------------------------------------------------------------------------------------------------------

(s) Write a program to carry out the following:
(a) Read a text file ‘INPUT.TXT’
(b) Print each word in reverse order
Example,
Input: INDIA IS MY COUNTRY
Output: AIDNI SI YM YRTNUOC
Assume that each word length is maximum of 10 characters and each word is separated by newline/blank characters.

Solution:

NOTE: Make a file "INPUT.TXT" in bin directory and write something in it, then run the program.

#include<stdio.h>
#include<conio.h>
#include<string.h>

void main() {


FILE *fs;
char s[80];
void rev();

clrscr();

fs=fopen("INPUT.TXT","r");

if(fs==NULL) {

printf("cannot open file!");
exit();
}


while(fgets(s,79,fs)!=NULL)
rev(s);

fclose(fs);

getch();

}

void rev(char s1[80]) {

char s2[80];
int i=0,j=0;

while(s1[i]!='\0') {

s2[j]=s1[i];

if(s1[i]==' ' || s1[i]=='\0') {

s2[j]='\0';

strrev(s2);

printf("%s ",s2);

j=-1;

}

i++;
j++;
}

s2[j]='\0';

printf("%s",strrev(s2));


}

-----------------------------------------------------------------------------------------------------------------

(s) Write a C program to read a large text file ‘NOTES.TXT’ and print it on the printer in cut-sheets, introducing page breaks at the end of every 50 lines and a pause message on the screen at the end of every page for the user to change the paper.

Solution:

NOTE: Make a file as "NOTES.TXT" in bin directory and write/paste some text in it, then run the program.

#include<stdio.h>

#include<conio.h>

#include<string.h>



void print();



void main() {

FILE *fp;

char s[80];
int x=4,y=4,c=0,pg=0;
clrscr();

fp=fopen("NOTES.TXT","r");

if(fp==NULL) {

puts("cannot open file!");
exit();
}

while(fgets(s,74,fp)!=NULL) {

gotoxy(30,1);         /* printing page number */
printf("Page No: %3d",pg);

print(s,x,y,c);  /* function to print */

c++;
y++;

if(c>51) {           /* checking for page end */

pg++;

c=0;
gotoxy(2,24);
printf("press any key to change paper...");
getch();

clrscr();

}

if(y>22) {      /* checking for total lines */

gotoxy(2,24);
printf("press any key to go to next page...");
getch();
y=5;
clrscr();
}

}

fclose(fp);
}

void print(char *s,int x, int y, int c) {

 
 /*    page border    */

int i,bdr,bdr2;

gotoxy(1,2);
printf("%c",218);
for(bdr=3;bdr<23;bdr++) {

gotoxy(1,bdr);
printf("%c",179);

gotoxy(79,bdr);
printf("%c",179);

}

gotoxy(79,2);
printf("%c",191);

gotoxy(79,23);
printf("%c",217);

gotoxy(1,23);
printf("%c",192);

for(bdr2=2;bdr2<=78;bdr2++) {

gotoxy(bdr2,2);
printf("%c",196);

}

gotoxy(x,y);

puts(s);

if(c>50) {

for(i=2;i<79;i+=2) {

gotoxy(i,23);

printf("-");
}
}
}

____________________________________________________

Let Us C / Chapter 7 (The C Pre-processor)

                               Exercise [C] (a) Write down macro definitions for the following: 1. To test whether a character ente...