Saturday, March 31, 2012

Finding Maximum number of Concurrent processes .

/* Finding Maximum number of Concurrent processes */
# include < stdio.h>
# include < stdlib.h>
# include < unistd.h>
# include < signal.h>
# include < sys/wait.h>

void main()
{
    int cnt,pid;
    for(cnt=0;;cnt++)
    {
        pid = fork();
        if(pid==-1)
        {
        printf("Maximum Number Of Concurrent Process Per User %d
 ",cnt);   
        }
        if(pid!=0)
        {
            wait(0);
            exit(0);
        }
    }
}

Program with a function display(int) to print the integers.

/*
 * Program with a function display(int) to print the integers
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void display(int);

int main(void)
{
        int N;
        printf("
 Enter the Number Of Time You Want To Print : ");
    scanf("%d", &N);

    display(N);
   
    printf("
");
    return(0);
}

void display(int N)
{
        int i;
        for(i = 0; i < N; i++)
      printf("
Unix Programming Lab");
}

Write a program to print stuff to a file reading the number of time for an other file.

/*
 * Write a program to print stuff to a file reading the number of time for an other file
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void writefile(char *);

int main()
{
        int N;
    FILE *inf;
    int i;

    inf = fopen("infile.txt", "r");

    /* Now let us read the number from a file */
    fscanf(inf, "%d", &N);
   
    for(i = 0; i < N; i++)
            writefile("Unix Programming Lab.");

    printf("
");
    fclose(inf);
    return(0);
}

void writefile(char *str)
{
        FILE *outf;
    int i;

    outf = fopen("outfile.txt", "a");
   
    /* Now let us write to the file */
    fprintf(outf, "
%s", str);
   
    fclose(outf);
}

Write a function called display(char *) that displays a message

/*
 * Write a function called display(char *) that displays a message
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void display(char *);

int main(void)
{
        int N;
    int i;

        printf("
 Enter the Number Of Time You Want To Print : ");
    scanf("%d", &N);

    for (i = 0; i < N; i++)
            display("Unix Programming Lab");
   
    printf("
");
    return(0);
}

void display(char *str)
{
      printf("
%s", str);
}

Program to display all the errors in a list

/*
 * Program to display all the errors in a list
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <error.h>
#include <string.h>

int main(void)
{
        int i;
    char *errmsg;
    printf("
Error No : Error Message");
    for (i = 0; i < 125; i++) {
      errmsg = strerror(i);
      printf("
%d    : %s", i, errmsg);
    }

    printf("
");
    return(0);
}

Program to print its Process ID, Parent Process ID and Group ID

/*
 * Program to print its Process ID, Parent Process ID and Group ID
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>

int main()
{
        pid_t pid, ppid;
    gid_t gid;

    /* get the process id */
    if ((pid = getpid()) < 0) {
      perror("
unable to get pid");
    } else {
      printf("
The process id is %d", pid);
    }

    /* get the parent process id */
    if ((ppid = getppid()) < 0) {
      perror("
unable to get the ppid");
    } else {
      printf("
The parent process id is %d", ppid);
    }

    /* get the group process id */
    if ((gid = getgid()) < 0) {
      perror("
unable to get the group id
");
    } else {
      printf("
The group id is %d
", gid);
    }

    return(0);

Program to work on Child Processes.

/* Program to work on Child Processes */

# include <  stdio.h>
# include < stdlib.h>
# include <  unistd.h>
int main()
{
    long limit;
    /* GET THE LIMIT OF THE ARGUMENT */
    if((limit = sysconf(_SC_ARG_MAX)) < 0)
    {
        perror("ARG MAXIMUM LIMIT ERROR

");
    }
    else
    {
        printf("ARGUMENT LIMIT IS %ld

",limit);
    }
    /* GET THE LIMIT OF THE CHILD PROCESS */
    if((limit = sysconf(_SC_CHILD_MAX)) < 0)
    {
        perror("CHILD  MAXIMUM LIMIT ERROR

");
    }
    else
    {
        printf("MAXIMUM CHILD PROCESS %ld

",limit);
    }
    printf("
");
    return(0);
}

A message queue program that shows a client server implementation this is the reciever program using Message Queues.

/*
 * A message queue program that shows a client server implementation
 * this is the reciever program using Message Queues
 */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

struct my_msg_st {
        long int my_msg_type;
        char some_text[BUFSIZ]; };

int main(void)
{
        int running = 1;
    int msgid;
    struct my_msg_st some_data;
    long int msg_to_recieve = 0;

    /* Let us set up the message queue */
    msgid = msgget((key_t)1234, 0666 | IPC_CREAT);

    if (msgid == -1) {
      perror("msgget failed with error");
      exit(EXIT_FAILURE);
    }

    /* Then the messages are retrieved from the queue, until an end message is
     * encountered. lastly the message queue is deleted
     */

    while(running) {
      if (msgrcv(msgid, (void *)&some_data, BUFSIZ,
             msg_to_recieve, 0) == -1) {
        perror("msgcrv failed with error");
        exit(EXIT_FAILURE);
      }
      printf("You wrote: %s", some_data.some_text);
      if (strncmp(some_data.some_text, "end", 3) == 0) {
        running = 0;
      }
    }

    if (msgctl(msgid, IPC_RMID, 0) == -1) {
      perror("msgctl(IPC_RMID) failed");
      exit(EXIT_FAILURE);
    }

    exit(EXIT_SUCCESS);
}

A message queue program that shows a client server implementation this is the sender program using Message Queues

/*
 * A message queue program that shows a client server implementation
 * this is the sender program using Message Queues
 */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_TEXT 512

struct my_msg_st
{
        long int my_msg_type;
        char some_text[MAX_TEXT];
};

int main()
{
     int running = 1;
    int msgid;
    char ender[3] = "end";
    struct my_msg_st some_data;
    char buffer[BUFSIZ];
    system("clear");
    msgid = msgget((key_t)1234, 0666 | IPC_CREAT);
    if (msgid == -1)
    {
      fprintf(stderr,"msgget failed with error : %d
 ", errno);
      exit(EXIT_FAILURE);
    }

 while(running)
 {
printf("Enter some text : ");
fgets(buffer, BUFSIZ, stdin);
    if (strncmp(buffer, ender,3) == 0 )
    { running = 0; }
printf("
 Text sent : %s
", buffer);
some_data.my_msg_type = 1;
strcpy(some_data.some_text, buffer);


    if (msgsnd(msgid, (void *)&some_data, MAX_TEXT, 0) == -1)
    {
     // perror("msgsnd error");
    fprintf(stderr,"msgsnd failed ");
      exit(EXIT_FAILURE);
    }

}   
    exit(EXIT_SUCCESS);
}

Program to work on Semapores.

/* Program to work on Semapores */

# include < unistd.h>
# include < stdlib.h>
# include < stdio.h>
# include < sys/types.h>
# include < sys/ipc.h>
# include < sys/sem.h>
#ifndef _SEMUN_H
#define _SEMUN_H
union semun{
int val;
struct semid_ds * buf;
unsigned short int * array;
struct seminfo *__buf;
};
# endif

static int set_semvalue(void);
static void del_semvalue(void);
static int semaphore_p(void);
static int semaphore_v(void);
static int sem_id;

int main(int argc, char *argv[])
{ int i;
int pause_time;
char  op_char = 'O';
srand((unsigned int) getpid());
sem_id = semget((key_t)1234,1,0666| IPC_CREAT);
    if ( argc > 1 )
    {
        if (!set_semvalue())
        {
            fprintf(stderr, "Failed to initialize semapore
");
            exit(EXIT_FAILURE);
        }
    op_char = 'X';
    sleep(2);
    }

for ( i=0; i<10;i++)
    {
    if (!semaphore_p()) exit(EXIT_FAILURE);
    printf("%c", op_char);fflush(stdout);
    pause_time = rand() % 3;
    sleep(pause_time);
    printf("%c", op_char);fflush(stdout);
    if (!semaphore_p()) exit(EXIT_FAILURE);
    pause_time = rand()  % 2;
    sleep(pause_time);
    }
printf("
 %d - finished 
", getpid());
if (argc >1 )
    {
    sleep(10);
    del_semvalue();
    }
exit(EXIT_SUCCESS);
}

static int set_semvalue(void)
{
    union semun sem_union;
    sem_union.val = 1;
    if (semctl(sem_id,0,SETVAL, sem_union) == -1) return(0);
    return(1);
}

static void del_semvalue(void)
{
    union semun sem_union;
    if (semctl(sem_id,0, IPC_RMID, sem_union) == -1)
    fprintf(stderr, "Failed to delete semaphore
");
}

static int semaphore_p(void)
{
    struct sembuf sem_b;
    sem_b.sem_num = 0;
    sem_b.sem_op = -1;
    sem_b.sem_flg = SEM_UNDO;
    if (semop(sem_id, &sem_b,1) == -1)
    {
        fprintf(stderr, "semaphore_p failed
 ");
        return(0);
    }
    return(1);
}

Program to catch Ctrl+C.

/*
 * A small program that catches the ctrl-c(SIGINT) signal for the first time and prints
 * a output rather but exits on pressing ctrl-c again
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>

void sigfun(int sig)
{
        printf("You have presses Ctrl-C , please press again to exit");
    (void) signal(SIGINT, SIG_DFL);
}

int main()
{
        (void) signal(SIGINT, sigfun);
  
    while(1) {
      printf("Hello World!
");
      sleep(1);
    }

    return(0);
}

cryptography in c on linux

This program takes a text file from guest file and encrypts it.to retain the original text redo the same code.you can make the algorithm more abstruse.try it.for example as key ,which here is taken as i=i+2.you can take a song(dat file) converted to text file.or you can first invert the source text then encrypt.
Code;-

#include<stdio.h>
int main()
{unsigned long int i=0;
 char ch;
 char name1[20],name2[20];
 FILE *fp,*ft;
 printf("ENTER THE SOURCE FILE:");
 gets(name1);
 printf("ENTER THE DESTINATION FILE:");
 gets(name2);
 fp=fopen(name1,"r");
 ft=fopen(name2,"w");
 if(fp==NULL)
 {printf("CAN,T OPEN THE FILE");
  }
 while(!feof(fp))
 {ch=getc(fp);
  ch=~((ch^i));
  i+=2;
  if(i==100000)
  {i=0;
   }
  putc(ch,ft);
  }
  fclose(fp);
  fclose(ft);
  return 0;
}


      

Clear the Screen and Move cursor to (0,0)



This code clears the UNIX prompt and move cursor to (0,0) alike `clear` on UNIX or `cls' on DOS.You can custamize cursor position by changing values 0;0 

  #include<stdio.h>
int main()
{
printf("

String manipulation using shared memory

string manipulation using shared memory....
"A Process say p1 has to create the shared memory to store a line of text.Another Process say p2 has to perform the substring operation and it
is displayed in process p2 itself."

 Process p1
----------

#include<sys/shm.h>
int main()
{
       size_t length;
       struct shmid_ds buff;
       char *ptr,p[50];
       int id,i;
       printf("
            Shared Memory");
       printf("
            ------ ------");
       if((id=shmget((key_t)6234,2,0664|IPC_CREAT))<0)
       {
               printf("Shared Memory Creation Error
");
               exit(1);
       }
       ptr=shmat(id,NULL,0);
       printf("
Enter the string :");
       gets(p);
       puts(p);
       for(i=0;i<strlen(p);i++)
               *ptr++=p[i];
       printf("The Entered String %s was Accepted.
",ptr);
       exit(0);
}


Process p2
----------

#include<stdio.h>
#include<sys/shm.h>
int main()
{
       size_t length;
       struct shmid_ds buff;
       char *ptr,a[50],b[10],c[20];
       int id,i=0,flag=0,j,k=0;
       if((id=shmget((key_t)6234,2,0664|IPC_CREAT))<0)
       {
               printf("Shared Memory Creation Error
");
               exit(1);
       }
       printf("
Shared memory Created : %d",id);
       ptr=shmat(id,NULL,0);
       memset(a,'

A PROG. To Find out the machine is Little or Big endian

Try to know first concept of how data store in little & big endian machine register.Then take the concept of pointer,& try to understand this code.

#include<stdio.h>
int main(void)
{
    int i=1;
    if((*(char*)&i)==1)
         printf("The machine is little endian.
");
    else
         printf("The machine is big endian.
");
    return 0;
}
 

program to implement who command

#include<stdio.h>
#include<sys/utsname.h>
#include<utmp.h>
int main(void)
{
 struct utmp *n;
 char *a;
 int i;
 setutent();
 n=getutent();
 while(n!=NULL)
 {
  if(n->ut_type==7)
  {
   printf("%-9s",n->ut_user);
   printf("%-12s",n->ut_line);
   a=ctime(&n->ut_time);
   printf(" ");
   for(i=4;i<16;i++)
   printf("%c",a[i]);
   printf(" (");
   printf("%s",n->ut_host);
   printf(")
");
  }
  n=getutent();
 }
}

Output of one program is input of another program Using Pipes

#include <unistd.h>
#include <process.h>

/* Pipe the output of program to the input of another. */

int main()
{
  int pipe_fds[2];
  int stdin_save, stdout_save;

  if (pipe(pipe_fds) < 0)
    return -1;

  /* Duplicate stdin and stdout so we can restore them later. */
  stdin_save = dup(STDIN_FILENO);
  stdout_save = dup(STDOUT_FILENO);

  /* Make the write end of the pipe stdout. */
  dup2(pipe_fds[1], STDOUT_FILENO);

  /* Run the program. Its output will be written to the pipe. */
  spawnl(P_WAIT, "/dev/env/DJDIR/bin/ls.exe", "ls.exe", NULL);

  /* Close the write end of the pipe. */
  close(pipe_fds[1]);

  /* Restore stdout. */
  dup2(stdout_save, STDOUT_FILENO);

  /* Make the read end of the pipe stdin. */
  dup2(pipe_fds[0], STDIN_FILENO);

  /* Run another program. Its input will come from the output of the
     first program. */
  spawnl(P_WAIT, "/dev/env/DJDIR/bin/less.exe", "less.exe", "-E", NULL);

  /* Close the read end of the pipe. */
  close(pipe_fds[0]);

  /* Restore stdin. */
  dup2(stdin_save, STDIN_FILENO);

  return 0;
}

Client Server Program using FIFO

client.c
--------
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#define FIFO1 "temp1"
#define FIFO2 "temp2"
#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
void client(int r,int w)
{
int l,n;
char buf[80];
fgets(buf,80,stdin);
l=strlen(buf);
if(buf[l-1]=='
')
 l--;
write(w,buf,l);
while((n=read(r,buf,80))>0)
 write(STDOUT_FILENO,buf,n);
}
int main(int argc,char *argv[])
{
int readfd,writefd;
printf("Enter the File Name to Get:");
writefd=open(FIFO1,O_WRONLY,0);
readfd=open(FIFO2,O_RDONLY,0);
client(readfd,writefd);
close(readfd);
close(writefd);
}



server.c
--------


#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#define FIFO1 "temp1"
#define FIFO2 "temp2"
#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
void server(int r,int w)
{
int fd,n;
char buf[81];
if((n=read(r,buf,80))==0)
{
       return;
}
buf[n]='

vowels counting using vfork

C Program to find the vowels in the given string using vfork

Code:-

#include<stdio.h>
#include<sys/types.h>
int main()
{
       int j,n,a,i,e,o,u;
       char str[50];
       a=e=i=o=u=0;
       pid_t pid;
       if((pid=vfork())<0)
        {
                perror("FORK ERROR");
                exit(1);
        }
        if(pid==0)
        {
                printf("
        Counting Number of Vowels using VFORK");
                printf("
        -------- ------ -- ------ ----- -----");
                printf("
Enter the String:");
                gets(str);
                _exit(1);
        }
        else
        {
                n=strlen(str);
                for(j=0;j<n;j++)
                {
                        if(str[j]=='a' || str[j]=='A')
                                a++;
                        else if(str[j]=='e' || str[j]=='E')
                                e++;
                        else if(str[j]=='i' || str[j]=='I')
                                i++;
                        else if(str[j]=='o' || str[j]=='O')
                                                 o++;
                        else if(str[j]=='u' || str[j]=='U')
                                u++;
                }
                printf("
        Vowels Counting");
                printf("
        ------ --------");
                printf("
Number of A  : %d",a);
                printf("
Number of E  : %d",e);
                printf("
Number of I  : %d",i);
                printf("
Number of O  : %d",o);
                printf("
Number of U  : %d",u);
                printf("
Total vowels : %d
",a+e+i+o+u);
                exit(1);
        }
}

implementation of LN command using system calls

this program implement the ln command in unix using system calls.

Code:-

#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/stat.h>
int main(int argc,char* argv[])
{
int i;
struct stat s;
if (argc<3)
{
 perror("ERROR:Too Few Arguments");
 exit(1);
}
if(argc>4)
{
 perror("ERROR:Too Many Arguments");
 exit(1);
}
if(argc==3)
 i=0;
else
 i=1;

if(i && !(strcmp(argv[1],"-s")==0)) {
 perror("ERROR:Invalid Syntax");
 exit(1);
}

if(access(argv[i+1],F_OK))
{
  perror("ERROR:File name not Found");
  exit(1);
}
if(!access(argv[i+2],F_OK))
{
  perror("ERROR:File Name already exist");
  exit(1);
}
if(stat(argv[i+1],&s)<0)
{
  perror("ERROR:Unable to reterive stat information");
  exit(1);
}
if(!S_ISREG(s.st_mode))
{
  perror("ERROR:Not a Regular File");
  exit(1); }
if(argc==3)
 if(link(argv[i+1],argv[i+2])<0)
 {
  perror("ERROR:Unable to create the Link");
  exit(1);
 }
if(argc==4)
 if(symlink(argv[i+1],argv[i+2])<0)
 {
  perror("ERROR:Unable to create the Link");
  exit(1);
 }
}
 

implementing who am i using system calls

This program is used to implement the who am i program using system calls(utmp struture)

Code:-

#include<stdio.h>
#include<utmp.h>
int main()
{
       char *s,*c;
       struct utmp *u;
       int i;
       c=getlogin();
       setutent();
       u=getutent();
       while(u!=NULL)
       {
          if(u->ut_type==7 && strcmp(u->ut_user,c)==0)
          {
               printf("%-12s",u->ut_user);
               printf("%-9s",u->ut_line);
               s=ctime(&u->ut_time);
               for(i=4;i<16;i++)
               printf("%c",s[i]);
               printf("(%s",u->ut_host);
               printf(")
");
          }
       u=getutent();
       }
}

Implementing cat command using system calls.

this program will implement the cat command using systam calls

#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
int main(int argc,char *argv[])
{
       int f=0,n;
       char l[80];
       struct stat s;
       if(argc!=2)
       {
               printf("Mismatch argument");
               exit(1);
       }
       if(access(argv[1],F_OK))
       {
               printf("File Exist");
               exit(1);
       }
       if(stat(argv[1],&s)<0)
       {
               printf("Stat ERROR");
               exit(1);
       }
       if(S_ISREG(s.st_mode)<0)
       {
               printf("Not a Regular FILE");
               exit(1);
       }
       if(geteuid()==s.st_uid)
               if(s.st_mode & S_IRUSR)
                       f=1;
       else if(getegid()==s.st_gid)
               if(s.st_mode & S_IRGRP)
                       f=1;
       else if(s.st_mode & S_IROTH)
               f=1;
       if(!f)
       {
               printf("Permission denied");
               exit(1);
       }
       f=open(argv[1],O_RDONLY);
       while((n=read(f,l,80))>0)
               write(1,l,n);
}
 

String manipulation using message Queue

This program is used to perform the string manipulation using message Queue.contains 4 programs.one program is used as the header.one
program for used to send the data int the messga queue and other two programs are used to reterive the message.

Queue.h
-------
#include<stdio.h>
#include<errno.h>
#include<sys/ipc.h>
#include<sys/msg.h>
struct queue
{
        long type;
        char msg[50];
};

Queue.c
-------

#include "queue.h"
int main()
{
       struct queue q;
       int mid;
       if((mid=msgget(ftok("string",0x99),0644|IPC_CREAT))<0)
       {
               if(mid!=-1)
               {
                       printf("Message Queue Error
");
                       exit(1);
               }
               else
               {
                       printf("Message Already Exist
");
                       exit(1);
               }
       }
       printf("
Enter the Message Type:");
       scanf("%d",&q.type);
       while(q.type>0)
       {
               printf("
Enter the Message:");
               getchar();
               gets(q.msg);
               if(msgsnd(mid,&q,sizeof(q),IPC_NOWAIT)<0)
               {
                       printf("Message send Error
");
                       exit(1);
               }
               printf("
Enter the Message Type:");
               scanf("%d",&q.type);
       }
return 0;
}


Word.c
------

#include "queue.h"
#include<string.h>
void word(char* str)
{
       int i,n,w=1;
       n=strlen(str);
       for(i=0;i<n;i++)
               if(str[i]==' ' && str[i-1]!=' ')
                       w++;
       printf("Number of Words in "%s" :%d
",str,w);
}

int main()
{
       struct queue q;
       int mid;
       long type;
       if((mid=msgget(ftok("string",0x99),0644 ))<0)
       {
               printf("Message Queue Error
");
               exit(1);
       }
       printf("
Enter the Message Type to Reterive:");
       scanf("%d",&type);
       while(msgrcv(mid,&q,sizeof(q),type,IPC_NOWAIT) && errno!=ENOMSG)
       {
               word(q.msg);
       }
       msgctl(mid,IPC_RMID,NULL);
}

Reverse.c
---------

#include "queue.h"
#include<string.h>
void rev(char* str)
{
       char s[30];
       int i,j,n;
       n=strlen(str);
       printf("Reverse for "%s" :",str);
       for(i=n;i>=0;i--)
               putchar(str[i]);
       printf("
");
}
int main()
{
       struct queue q;
       int mid;
       long type;
       if((mid=msgget(ftok("string",0x99),0644 ))<0)
       {
               printf("Message Queue Error
");
               exit(1);
       }
       printf("
Enter the Message Type to Reterive:");
       scanf("%d",&type);
       while(msgrcv(mid,&q,sizeof(q),type,IPC_NOWAIT) && errno!=ENOMSG)
       {
               rev(q.msg);
       }
}

 

A Program to utilize message queue for implementing the merge sort(Socket Programming)

This program utilises the message queue in order to implement the merge sort program. The client sends the numbers in a batch and the server receives it. The server sorts the numbers of the batch and finally merges the batches.


Code:-

/*Unix Program*/
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/wait.h>
#include<stdlib.h>
#include<stdio.h>
#define MAXLINE 1000

struct mymesg
{
    long mtype;
    int a[4];
};
void Merge(int a[],int mer[],int ct)
{
    if(ct==0)
    {
        ct+=4;
        for(int i=1;i<=ct;i++)
            mer[i]=a[i];
    }
    else
    {
        for(int i=1;i<=4;i++)
        {
            int j=1;
            while(a[i]>mer[j]&&j<=ct)j++;
            if(j>ct)
                mer[j]=a[i];
            else
            {
                for(int k=ct;k>=j;k--)
                    mer[k+1]=mer[k];
                mer[j]=a[i];
            }
            ct++;
        }
    }
}
int main()
{
    int n,pid,mpid,sum,b[17],mer[17],num=16;
    mpid=msgget(12,0666|IPC_CREAT);
    system("clear");
    printf("Elements are...
");
    for(int i=1;i<=num;i++)
    {
        b[i]=rand()%150;
        printf("%d ",b[i]);
    }
    printf("

");
    int i,ct=1,gmax;n=4;sum=0;gmax=4;
    for(i=1;i<=n;i++)
    {
        struct mymesg ptr;
        ptr.mtype=1;
        pid=fork();
        if (pid>0)
        {
            int k=0;
            printf("Group %d: ",i);
            for(int j=ct;j<=ct+gmax-1;j++)
            {
                ptr.a[++k]=b[j];
                printf("%d ",ptr.a[k]);
            }

            printf("
");
            msgsnd(mpid,&ptr,MAXLINE,IPC_NOWAIT);
            waitpid(pid,NULL,0);

            msgrcv(mpid,&ptr,MAXLINE,0,IPC_NOWAIT);

            printf("Sorted Sub-Group %d: ",i);
            for(int j=1;j<=gmax;j++)
                printf("%d ",ptr.a[j]);
            printf("

");

            Merge(ptr.a,mer,ct-1);

            if(ct==num+1-gmax)
                break;
            ct+=gmax;
            continue;
        }
        else
        {
            msgrcv(mpid,&ptr,MAXLINE,0,IPC_NOWAIT);

            for(int j=1;j<=gmax;j++)
            {
                for(int k=1;k<=gmax-j;k++)
                {
                    if(ptr.a[k]>ptr.a[k+1])
                    {
                        int t=ptr.a[k+1];
                        ptr.a[k+1]=ptr.a[k];
                        ptr.a[k]=t;
                    }
                }
            }
            ptr.mtype=2;
            msgsnd(mpid,&ptr,MAXLINE,IPC_NOWAIT);
            exit(0);
        }
    }
    printf("Merged Sorted Group....
");
    for(int i=1;i<=num;i++)
        printf("%d ",mer[i]);
    printf("

");
    return 0;
}
 

Display menu until press 0 by using child process.

Display menu until press 0 by using child process.

Code;-

/*A small program that display menu until press 0*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
main()
{
   int choice;
   do {
      printf("---------------=====00=====---------------");
      printf("

        Main Menu
");
      printf("Please select an option that you need:
");
      printf("    1. Executer ls command
");
      printf("    2. Execute ps command
");
      printf("    3. Execute who command
");
      printf("    0. exit
");
      printf("
Your choice: ");
      scanf("%d", &choice);
      //while (getchar() != '
');
      switch (choice){
          case 1:
               if (fork())
                  wait(0);
                else
                  execlp("ls", "ls", (char *)NULL);
                  break;
          case 2:
               if (fork())
                  wait(0);
               else
                  execlp("ps", "ps", (char *)NULL);
                  break;
          case 3:
               if (fork())
                  wait(0);
               else
                  execlp("who", "who", (char *)NULL);
                  break;
          case 0:
               break;
          default:
               printf("Please enter only 0-3
");
       }
   }
   while (choice != 0);
}
 

Creating menu driven environment in C in Unix.

ItS purpose is to provide a menu driven environment in c & c++ environment in unix platform.

To compile:
cc filename.c-ncurser

Code:-

#include <curses.h>
#include <stdlib.h>
#define ENTER 10
#define ESCAPE 27
void init_curses()
{
        initscr();
        start_color();
        init_pair(1,COLOR_WHITE,COLOR_BLUE);
        init_pair(2,COLOR_RED,COLOR_GREEN);
        init_pair(3,COLOR_RED,COLOR_WHITE);
    init_pair(4,COLOR_BLUE,COLOR_YELLOW);
    init_pair(5,COLOR_BLUE,COLOR_CYAN);
    curs_set(0);
        noecho();
        keypad(stdscr,TRUE);
}
void draw_menubar(WINDOW *menubar)
{
        wbkgd(menubar,COLOR_PAIR(5));
        waddstr(menubar,"File");
        wattron(menubar,COLOR_PAIR(3));
        waddstr(menubar,"(F1)");
        wattroff(menubar,COLOR_PAIR(3));
        wmove(menubar,0,10);
        waddstr(menubar,"Edit");
        wattron(menubar,COLOR_PAIR(3));
        waddstr(menubar,"(F2)");
    wmove(menubar,0,20);
        wattroff(menubar,COLOR_PAIR(3));
    waddstr(menubar,"Search");
    wattron(menubar,COLOR_PAIR(3));
    waddstr(menubar,"(F3)");
    wmove(menubar,0,31);
    wattroff(menubar,COLOR_PAIR(3));
        waddstr(menubar,"Cursor ");
    wattron(menubar,COLOR_PAIR(3));
    waddstr(menubar,"(F4)");
    wmove(menubar,0,43);
    wattroff(menubar,COLOR_PAIR(3));
    waddstr(menubar,"Compile");
    wattron(menubar,COLOR_PAIR(3));
    waddstr(menubar,"(F5)");
        wattroff(menubar,COLOR_PAIR(3));
    wmove(menubar,0,56);
    waddstr(menubar,"Help");
    wattron(menubar,COLOR_PAIR(3));
    waddstr(menubar,"(F6)");
        wattroff(menubar,COLOR_PAIR(3));
    wmove(menubar,0,66);
    waddstr(menubar,"Exit");
    wattron(menubar,COLOR_PAIR(3));
    waddstr(menubar,"(F7)");

}
WINDOW **draw_menu(int start_col)
{
        int i;
        WINDOW **items;
        items=(WINDOW **)malloc(9*sizeof(WINDOW *));
    items[0]=newwin(6,19,1,start_col);
        wbkgd(items[0],COLOR_PAIR(2));
    //    box(items[0],ACS_VLINE,ACS_HLINE);
       //wprintw(items[1],"new");

    items[1]=subwin(items[0],1,17,2,start_col+1);
        items[2]=subwin(items[0],1,17,3,start_col+1);
        items[3]=subwin(items[0],1,17,4,start_col+1);
        items[4]=subwin(items[0],1,17,5,start_col+1);
        items[5]=subwin(items[0],1,17,6,start_col+1);
        items[6]=subwin(items[0],1,17,7,start_col+1);
    ///  items[7]=subwin(items[0],1,17,8,start_col+1);
    //    items[8]=subwin(items[0],1,17,9,start_col+1);
///        for (i=1;i<9;i++)

            wprintw(items[1],"Load",i);
    wprintw(items[2],"New",i);
    wprintw(items[3],"Save");
    wprintw(items[4],"Save as");
    wprintw(items[5],"Printer");
          /// wprintw(items[],"FILE%d",i);
     /// wprintw(item[1],"File%d",i);
   //     wbkgd(items[1],COLOR_PAIR(1));
        wrefresh(items[0]);
        return items;
}
    WINDOW **draw_menu2(int start_col)
{
    int i;
    WINDOW **items;
    items=(WINDOW**) malloc(9*sizeof(WINDOW*));
    items[0]=newwin(5,19,1,start_col);
    wbkgd(items[0],COLOR_PAIR(2));

    items[1]=subwin(items[0],1,17,2,start_col+1);
    items[2]=subwin(items[0],1,17,3,start_col+1);
    items[3]=subwin(items[0],1,17,4,start_col+1);
    items[4]=subwin(items[0],1,17,5,start_col+1);
    items[5]=subwin(items[0],1,17,6,start_col+1);
    items[6]=subwin(items[0],1,17,7,start_col+1);

    wprintw(items[1],"Find");
    wprintw(items[2],"Find and replace");
    wprintw(items[3],"Repeat last find");
    wprintw(items[4],"Goto line number");
    wrefresh(items[0]);
    return items;
}


    WINDOW **draw_menu1(int start_col)
{

    int i;
    WINDOW **items;
       items=(WINDOW**) malloc(9*sizeof(WINDOW*));
       items[0]=newwin(6,19,1,start_col);
       wbkgd(items[0],COLOR_PAIR(2));

        items[1]=subwin(items[0],1,17,2,start_col+1);
    items[2]=subwin(items[0],1,17,3,start_col+1);
    items[3]=subwin(items[0],1,17,4,start_col+1);
    items[4]=subwin(items[0],1,17,5,start_col+1);
        items[5]=subwin(items[0],1,17,6,start_col+1);
        items[6]=subwin(items[0],1,17,7,start_col+1);

    wprintw(items[1],"Undo");
        wprintw(items[2],"Cut");
    wprintw(items[3],"Copy");
        wprintw(items[4],"Paste");
          wprintw(items[5],"Delete");
         wrefresh(items[0]);
return items;
}

WINDOW **draw_menu4(int start_col)
 {
       int i;
       WINDOW **items;
       items=(WINDOW**) malloc(9*sizeof(WINDOW*));
       items[0]=newwin(5,19,1,start_col);
       wbkgd(items[0],COLOR_PAIR(2));

        items[1]=subwin(items[0],1,17,2,start_col+1);
        items[2]=subwin(items[0],1,17,2,start_col+1);
        items[3]=subwin(items[0],1,17,4,start_col+1);
    items[4]=subwin(items[0],1,17,4,start_col+1);
       // items[5]=subwin(items[0],1,17,4,start_col+1);
//    items[6]=subwin(items[0],1,17,4,start_col+1);
    wprintw(items[2],"C Compiler");
    wprintw(items[4],"C++ Compiler");
    wrefresh(items[0]);

return items;
 }


WINDOW **draw_menu5(int start_col)
{
    int i;
    WINDOW **items;
        items=(WINDOW**) malloc(9*sizeof(WINDOW*));
        items[0]=newwin(4,19,1,start_col);
        wbkgd(items[0],COLOR_PAIR(2));


        items[1]=subwin(items[0],1,17,2,start_col+1);
        items[2]=subwin(items[0],1,17,2,start_col+1);
        items[3]=subwin(items[0],1,17,2,start_col+1);
        items[4]=subwin(items[0],1,17,4,start_col+1);
//    items[5]=subwin(items[0],1,17,4,start_col+1);
 //       items[6]=subwin(items[0],1,17,4,start_col+1);

    wprintw(items[2],"Key words");
//    wprintw(items[4]," perator");
    wprintw(items[4],"Operator");
       // wprintw(items[6],"Help");
    wrefresh(items[0]);

return items;

}

void delete_menu(WINDOW **items,int count)
{
        int i;
        for (i=0;i<count;i++)
                delwin(items[i]);
        free(items);
}
int scroll_menu(WINDOW **items,int count,int menu_start_col)
{
        int key;
        int selected=0;
        while (1) {
                key=getch();
                if (key==KEY_DOWN || key==KEY_UP) {
                        wbkgd(items[selected+1],COLOR_PAIR(2));
                        wnoutrefresh(items[selected+1]);
                        if (key==KEY_DOWN) {
                                selected=(selected+1) % count;
                        } else {
                                selected=(selected+count-1) % count;
                        }
                        wbkgd(items[selected+1],COLOR_PAIR(1));
                        wnoutrefresh(items[selected+1]);
                        doupdate();
                } else if (key==KEY_LEFT || key==KEY_RIGHT) {
                        delete_menu(items,count+1);
                        touchwin(stdscr);
                        refresh();
                        items=draw_menu(60-menu_start_col);
                        return scroll_menu(items,5,60-menu_start_col);
                } else if (key==ESCAPE) {
                        return -1;
                } else if (key==ENTER) {
                        return selected;
                }
        }
}
int main()
{
    int key,t;
    WINDOW *menubar,*messagebar,*window;
    init_curses();
    bkgd(COLOR_PAIR(1));
    window=subwin(stdscr,1,80,24,0);
    wbkgd(window,COLOR_PAIR(4));
    menubar=subwin(stdscr,1,80,0,0);
    messagebar=subwin(stdscr,1,79,23,1);
    draw_menubar(menubar);
    move(2,1);
    printw("Press F1 or F2 to open the menus. ");
    printw("F9 quits.");
  ///  window=newwin(2,68,23,8);
   /// wbkgd(window,COLOR_PAIR(4));
    ///t=wgetch(window);
    refresh();

    do {
        int selected_item;
        WINDOW **menu_items;
        key=getch();
        werase(messagebar);
        wrefresh(messagebar);
        if (key==KEY_F(1))
{
            menu_items=draw_menu(0);
            selected_item=scroll_menu(menu_items,5,0);
            delete_menu(menu_items,9);

        if (selected_item<0)
                wprintw(messagebar,
    "You haven't selected any item.");
            else
                wprintw(messagebar, "You have selected menu item %d.",selected_item+1);
            touchwin(stdscr);
            refresh();
 }         else if (key==KEY_F(2))
{
            menu_items=draw_menu1(10);
            selected_item=scroll_menu(menu_items,5,10);
            delete_menu(menu_items,9);

        if (selected_item<0)
                wprintw(messagebar,"You haven't selected any item.");
            else
                wprintw(messagebar, "You have selected menu item %d.",selected_item+1);
           // touchwin(stdscr);
           /// window=newwin(2,68,23,12);
        ///wbkgd(window,COLOR_PAIR(4));
       /// t=wgetch(window);
        touchwin(stdscr);
        refresh();
}
    else if(key==KEY_F(3))
{
    menu_items=draw_menu2(20);
    selected_item=scroll_menu(menu_items,5,20);
    delete_menu(menu_items,9);

    if(selected_item<0)
    wprintw(messagebar,"don't select any item");
    else
    wprintw(messagebar, "You have select menu item %d",selected_item+1);
    touchwin(stdscr);
    refresh();
}
    else if(key==KEY_F(5))
{
  menu_items=draw_menu4(40);
  selected_item=scroll_menu(menu_items,5,40);
  delete_menu(menu_items,9);

  if(selected_item<0)
  wprintw(messagebar, "No item is selected");
  else
  wprintw(messagebar, "You have selected menu %d",selected_item+1);
  touchwin(stdscr);
  refresh();
}
    else if(key==KEY_F(6))
{
    menu_items=draw_menu5(55);
    selected_item=scroll_menu(menu_items,5,55);
    delete_menu(menu_items,9);

    if(selected_item<0)
    wprintw(messagebar,
    " No item is selected");
    else
    wprintw(messagebar, "You have selected menu %d",selected_item+1);
    touchwin(stdscr);
    refresh();
}

    else if(key==KEY_F(7))
{
 menu_items=draw_menu4(60);
 selected_item=scroll_menu(menu_items,5,60);
 delete_menu(menu_items,9);

 if(selected_item<0)
       wprintw(messagebar, "No item is selected");
 else
    wprintw(messagebar, "You have to select  menu %d",selected_item+1);

 touchwin(stdscr);
 refresh();
}
 } while (key!=KEY_F(9));

    delwin(menubar);
    delwin(messagebar);
    delwin(window);
    endwin();
    return 0;
}

Program for counting number of Parity Bits in an integer.

Program for counting number of Parity Bits in an integer.

main()
{
       int num, cnt = 0;

       printf("enter the no :");
       scanf("%d",&num);

       while (num != 0)
       {
             num = num & (num - 1);
             cnt++;
       }

       printf("
 number of parity bits = %d ",cnt);
}

complete single linked list program

    Single linked list inplementation using different functions

1.INSERT A NUMBER AT THE BEGINNING;

2.INSERT A NUMBER AT LAST

3.INSERT A NUMBER AT A PARTICULAR LOCATION IN LIST

4.PRINT THE ELEMENTS IN THE LIST

5.PRINT THE TOTAL NUMBER OF ELEMENTS IN THE LIST

6.DELETE A NODE IN THE LINKED LIST:

7.REVERSE A LINKED LIST :

8.GET OUT OF LINKED LIST (BYEE BYEE):

CODE:-

Code :

     /* PROGRAM IMPLEMENTATION OF SINGLE LINKED LIST */

  #include"stdio.h"
  //#define NULL 0
  /* STRUCTURE CONTANING A DATA PART AND A LINK PART */

   struct node
 {
   int data;
   struct node *next;
 }*p;

  /* P IS A GLOBAL POINTER CONTAINS THE ADRESS OF THE FIRST NODE IN
LIST
*/

 /*THIS FUNCTION DELETES A NODE */

     delnode(int num)
 {
     struct node *temp, *m;
temp=p;
      while(temp!=NULL)
    {
       if(temp->data==num)
       {
           if(temp==p)
           {
              p=temp->next;
              free(temp);
              return;
           }
           else
         {
           m->next=temp->next;
           free(temp);
           return;
         }
      }else
        {
           m=temp;
          temp= temp->next;
        }

}
    printf("
 ELEMENT %d NOT FOUND
 ", num);
}/*THIS FUNCTION ADDS A NODE AT THE LAST OF LINKED LIST */

    append( int num )
 {
     struct node *temp,*r;
     /* CREATING A NODE AND ASSIGNING A VALUE TO IT */

       temp= (struct node *)malloc(sizeof(struct node));
       temp->data=num;
       r=(struct node *)p;

      if (p == NULL) /* IF LIST IS EMPTY CREATE FIRST NODE */
     {
    p=temp;
         p->next =NULL;
     }
  else
     {        /* GO TO LAST AND ADD*/

             while( r->next != NULL)
       r=r->next;
       r->next =temp;
       r=temp;
       r->next=NULL;
     }
  }/* ADD A NEW NODE AT BEGINNING  */

       addbeg( int num )
   {
        /*  CREATING A NODE AND INSERTING VALUE TO IT  */

   struct node *temp;
        temp=(struct node *)malloc(sizeof(struct node));
        temp->data=num;

       /* IF LIST IS NULL ADD AT BEGINNING  */
        if ( p== NULL)
       {
          p=temp;
          p->next=NULL;
       }

   else
      {
          temp->next=p;
          p=temp;
      }
   }

 /*  ADD A NEW NODE AFTER A SPECIFIED NO OF NODES */

 addafter(int num, int loc)
  {
     int i;
     struct node *temp,*t,*r;
     r=p;       /* here r stores the first location */
      if(loc > count()+1 || loc <= 0)
   {
         printf("
 insertion is not possible :
 ");
            return;
   }
        if (loc == 1)/* if list is null then add at beginning */
         {
           addbeg(num);
           return;
         }
      else
 {
       for(i=1;i<loc;i++)
          {
             t=r;   /* t will be holding previous value */
             r=r->next;
          }
         temp=(struct node *)malloc(sizeof(struct node));
         temp->data=num;
         t->next=temp;
         t=temp;
         t->next=r;
        return;
       }
}/* THIS FUNCTION DISPLAYS THE CONTENTS OF THE LINKED LIST */

  display(struct node *r)
  {
      r=p;
      if(r==NULL)
     {
       printf("NO ELEMENT IN THE LIST :");
       return;
     }
       /* traverse the entire linked list */
       while(r!=NULL)
    {
      printf(" -> %d ",r->data);
      r=r->next;
    }
     printf("
");
  }
//THIS FUNCTION COUNTS THE NUMBER OF ELEMENTS IN THE LIST
count()
 {
   struct node *n;
   int c=0;
   n=p;
    while(n!=NULL)
   {
     n=n->next;
     c++;
   }
  return(c);
 }
//THIS FUNCTION REVERSES A LINKED LIST
reverse(struct node *q)
{
   struct node *m, *n,*l,*s;
   m=q;
   n=NULL;
  while(m!=NULL)
 {
   s=n;
   n=m;
  m=m->next;
  n->next=s;
 }
   p=n;
}


/* THIS IS THE MAIN PROGRAM  */

  main()
 {
        int i;
   p=NULL;
   while(1) /* this is an indefinite loop */
 {
    printf("
 1.INSERT A NUMBER AT BEGINNING;
");
    printf("
 2.INSERT A NUMBER AT LAST:
");
    printf("
 3.INSERT A NUMBER AT A PARTICULAR LOCATION INlIST:
");
    printf("
 4.PRINT THE ELEMENTS IN THE LIST :
");
    printf("
 5.PRINT THE NUMBER OF ELEMENTS IN THE LIST 
");
    printf("
 6.DELETE A NODE IN THE LINKED LIST:
");
    printf("
 7.REVERSE A LINKED LIST :
");
    printf("
 8.GET OUT OF LINKED LIST (BYEE BYEE):
");
    printf("
 PLEASE, ENTER THE NUMBER:");

    scanf("%d",&i); /* ENTER A VALUE FOR SWITCH  */

      switch(i)
    {
         case 1:
      {
        int num;
        printf("
 PLEASE ENTER THE NUMBER :-");
        scanf("%d",&num);
        addbeg(num);
        break;
      }
          case 2:
       {
         int num;
         printf("
 PLEASE ENTER THE NUMBER :-");
         scanf("%d",&num);
         append(num);
         break;
       }

   case 3:
     {
      int num, loc,k;
      printf("
 PLEASE ENTER THE NUMBER :-");
      scanf("%d",&num);
      printf("
PLEASE ENTER THE LOCATION NUMBER :-");
      scanf("%d",&loc);
      addafter(num,loc);
      break;
    }  case 4:
      {
         struct node *n;
         printf("

   THE  ELEMENTS IN THE LIST ARE :
");
         display(n);
         break;
      }

      case 5:
   {
      struct node *n;
      display(n);
      printf(" TOTAL NO OF ELEMENTS IN THE LSIT ARE %d",count());
      break;
   } case 6:
    {
            int    num;
      printf("
 PLEASE ENTER A NUMBER FROM THE LIST :");
      scanf("%d",&num);
      delnode(num);
     break;
    }
   case 7:
    {
      reverse(p);
        display(p);
        break;
    }
  case 8:
 {
  exit();
 }
    }/* end if switch */
 }/* end of while */
}/* end of main */

SOUTHERN RAILWAY (TRAIN DETAILS MANAGEMENT )

 It is about the train details like adding a new train , its name,no. ect and reserving tickets ect,edit train details etc,

 Code:

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<process.h>
#include<graphics.h>
#include<dos.h>

struct emp
{
    char rno[10];
    char tname[10];
    char from[10];
    char to[10];
    int st;
}a;
struct emp1
{
    char rno[10];
    char tdate[8];
    int st;
}b;

FILE *fp1,*fp2,*fp3;
char fname[20],fname1[20];
void add();
void edit();
void disp();
void dele();
void res();
void grap();
void main()
{

    int ch=0,r1;
    grap();
    while(ch!=6)
    {
    clrscr();
    printf("
                    SOUTHERN RAILWAYS");
    printf("
                    ^^^^^^^^^^^^^^^^^");
    printf("

                         1.Add Train details");
    printf("
                         2.Delete Train details");
    printf("
                         3.Updata Train details");
    printf("
                         4.Display List");
    printf("
                         5.Reservation");
    printf("
                         6.Exit");
    printf("
                          ");
    printf("
                         Enter the choice : ");
    scanf("%d",&ch);
    switch(ch)
    {
        case 1:
            add();
            break;
        case 2:

            dele();
            break;
        case 3:
            edit();
            break;
        case 4:
            disp();
            break;
        case 5:
            res();
            break;
        case 6:
            exit(0);
    }
    }
}
void add()
{
    char yesno='y';
    clrscr();
    fp1=fopen("rwl.dat","a");
   //    printf("ADD  FILES");
    while(yesno=='y'||yesno=='y')
    {
        printf("
                    SOUTHERN RAILWAYS");
        printf("
                    ^^^^^^^^^^^^^^^^^");
        printf("
                    Enter the train Number :");
        scanf("%s",a.rno);
        printf("
                    Enter the Train name   :");
        scanf("%s",a.tname);
        printf("
                    Enter the Arrival station   :");
        scanf("%s",a.from);
        printf("
                    Enter the Departure station :");
        scanf("%s",a.to);
        printf("
                    Enter the Total Seats     : ");
        scanf("%d",&a.st);
        fprintf(fp1,"%s %s %s %s %d
",a.rno,a.tname,a.from,a.to,a.st);
        printf("
        do u want to continue[y/n]");
        yesno=getchar();
        fflush(stdin);
    }

    fclose(fp1);
}
void edit()
{
    char empno1[4];
    clrscr();
    printf("
                    SOUTHERN RAILWAYS");
    printf("
                    ^^^^^^^^^^^^^^^^^");
    printf("
                   Enter the train Number to edit :");
    scanf("%s",empno1);
    fp1=fopen("rwl.dat","r");
    fp2=fopen("trwl.dat","w");
    strcpy(fname,"rwl.dat");
    strcpy(fname1,"trwl.dat");
    while(!feof(fp1))
    {
        fscanf(fp1,"%s %s %s %s %d
",a.rno,a.tname,a.from,a.to,&a.st);
      //        printf(" %s ",a.rno);
        if(strcmp(a.rno,empno1)==0)
        {
        printf("
                    Enter the train Number :");
        scanf("%s",a.rno);
        printf("
                    Enter the Train Name     :");
        scanf("%s",a.tname);
        printf("
                    Enter the Arrival station   :");
        scanf("%s",a.from);
        printf("
                    Enter the Departure station :");
        scanf("%s",a.to);
        printf("
                    Enter the Total Seats    :");
        scanf("%d",&a.st);
        fprintf(fp2,"%s %s %s %s %d
",a.rno,a.tname,a.from,a.to,a.st);
       //    break;
        }
        else
        fprintf(fp2,"%s %s %s %s %d
",a.rno,a.tname,a.from,a.to,a.st);
    }
    fclose(fp1);
    fclose(fp2);
    unlink(fname);
    rename(fname1,fname);

}

void disp()
{
    clrscr();
    printf("
                    SOUTHERN RAILWAYS");
    printf("
                    ^^^^^^^^^^^^^^^^^
");
    printf("             TRAIN-NO    NAME        DEP      ARR     SEATS
");
    printf("             --------    ----        ----    -----    ------
");
    fp1=fopen("rwl.dat","r");
    while(!feof(fp1))
    {
        fscanf(fp1,"%s %s %s %s %d
",a.rno,a.tname,a.from,a.to,&a.st);
        printf("        %s    %s        %s     %s    %d
",a.rno,a.tname,a.from,a.to,a.st);
    }
    fclose(fp1);
   getch();
}

void dele()
{
    char empno1[4];int i=0;
    clrscr();
    printf("
                    SOUTHERN RAILWAYS");
    printf("
                    ^^^^^^^^^^^^^^^^^");
    printf("
                   Enter the train Number to delete :");
    scanf("%s",empno1);
    fp1=fopen("rwl.dat","r");
    fp2=fopen("trwl.dat","w");
    strcpy(fname,"rwl.dat");
    strcpy(fname1,"trwl.dat");
    while(!feof(fp1))
    {
        fscanf(fp1,"%s %s %s %s %d
",a.rno,a.tname,a.from,a.to,&a.st);
        if(strcmp(a.rno,empno1)!=0)
        {
        fprintf(fp2,"%s %s %s %s %d
",a.rno,a.tname,a.from,a.to,a.st);
        }
        else
        { i=1;
        printf("
                   TRAIN DETAILS DELETED SUCCESSFULLY      ");

        }
    }
    if(i==0)
    {
    printf("
                   SORRY -> INVALID TRAIN NUMBER      ");

    }
    fclose(fp1);
    fclose(fp2);
    unlink(fname);
    rename(fname1,fname);
    getch();

}

void res()
{
    char empno1[4],tdate[8];
    int i=0,n;
    clrscr();
    printf("
                    SOUTHERN RAILWAYS");
    printf("
                    ^^^^^^^^^^^^^^^^^");
    printf("
                    Enter the train Number :");
    scanf("%s",empno1);
    printf("
                    Enter the Date        :");
    scanf("%s",tdate);
    {
    fp1=fopen("res.dat","r");
    fp2=fopen("trwl.dat","w");
    strcpy(fname,"res.dat");
    strcpy(fname1,"trwl.dat");
    while(!feof(fp1))
    {
        fscanf(fp1,"%s %s %d
",b.rno,b.tdate,&b.st);
        if((strcmp(b.rno,empno1)==0) && (strcmp(b.tdate,tdate)==0))
        {
        i=1;
        printf("
                   Total seats Available : ");
        printf("%d",b.st);
        printf("
                   Enter the Number of Seats:");
        scanf("%d",&n);
        if(n > b.st)
        {
            printf("
                   SORRY,LIMIT EXCEEDED            ");
        }
        else
        {    b.st=b.st-n;
            printf("
                   TICKETS BOOKED SUCCESSFULLY      ");
        }
        fprintf(fp2,"%s %s %d
",b.rno,b.tdate,b.st);
        }
        else
        {
        fprintf(fp2,"%s %s %d
",b.rno,b.tdate,b.st);
        }
    }
    rewind(fp1);
    fclose(fp1);
    fclose(fp2);
//    printf(" %d ",i);
//    getch();
    if (i==1)
    {
    getch();
    unlink(fname);
    rename(fname1,fname);
    }

       }

    if (i==0)
    {
    fp1=fopen("rwl.dat","r");
    while(!feof(fp1))
    {
        fscanf(fp1,"%s %s %s %s %d
",a.rno,a.tname,a.from,a.to,&a.st);
//        printf("%s",a.rno);
        if(strcmp(a.rno,empno1)==0)
        { i= 2;
          n=a.st;
        }
    }
    fclose(fp1);
    if (i==2)
    {
    fp1=fopen("res.dat","a");
    {
     /*    printf("
Enter the train Number -> ");
        scanf("%s",b.rno);
        printf("
Enter the Date -> ");
        scanf("%s",b.tdate); */
        strcpy(b.rno,empno1);
        strcpy(b.tdate,tdate);
        printf("
                   Total Seats Available : %d ",n);
        printf("
                   Enter Number of seats : ");
        scanf("%d",&b.st);
        if( n < b.st)
        {
        printf("
                   SORRY,LIMIT EXCEEDED            ");
        b.st=n;
        }
        else
        {b.st=n-b.st;
        printf("
                   TICKETS BOOKED SUCCESSFULLY      ");
        }
        fprintf(fp1,"%s %s %d
",b.rno,b.tdate,b.st);
        //fflush(stdin);
    }
    rewind(fp1);
    fclose(fp1);
    getch();
    }
    else
    {
      clrscr();
      printf("
                    SOUTHERN RAILWAYS");
      printf("
                    ^^^^^^^^^^^^^^^^^");
      printf("
               Enter the Valid Train Number ");
      getch();
     }
      }
}

void grap()
{
    int gdriver = EGA, gmode = EGAHI;
   int bkcol, maxcolor, x, y,i;
   char msg[80];

   /* initialize graphics and local variables */
   initgraph(&gdriver, &gmode, "");

//'    settextstyle(3,0,12);
//    outtextxy(200,20,"RMD");


     for (i=1;i<=70;i++)
   {
    setcolor(7);
    circle(i,20+i,i);
   circle(i,220-i,i);
   circle(620-i,220-i,i);
   circle(620-i,20+i,i);
   delay(100);

    }

    settextstyle(3,0,12);
    outtextxy(200,20,"RMD");
    settextstyle(3,0,4);
    outtextxy(155,160,"ENGINEERNG COLLEGE");
    delay(3000);
   for (i=1;i<=90;i++)
   {
    setcolor(1);
    line(155,60+i,470,60+i);
    line(155,200-i,470,200-i);
     delay(20);
    setcolor(0);
    line(155,60+i,470,60+i);
    line(155,200-i,470,200-i);

    }
   for (i=1;i<=270;i++)
   {
    setcolor(1);
    line(312-i,10,312-i,250);
    line(309+i,10,309+i,250);
   delay(10);
    setcolor(0);
    line(312-i,10,312-i,250);
    line(309+i,10,309+i,250);

    }
    setcolor(15);
    settextstyle(3,0,4);
    outtextxy(200,100,"WELCOME TO");
    settextstyle(3,0,4);
    outtextxy(90,150,"RAILWAY TICKET RESERVATION");
    delay(1000);
   getch();
    closegraph();
}