08 March, 2014

Bytestuff

Bytestuff Receiver

#include<stdio.h>
#include<fcntl.h>

struct frame
{
    char cbit;
    char *info;
}f;

main()
{
    int fd,i,file1,no,k,flag,j;
    char ch,tmp[10];

    if((fd=open("testfile",O_RDONLY))<0)
        perror("File open failed");

    if((file1=open("outputfile",O_WRONLY))<0)
        perror("Output file open failed");

    for(;;)
    {
        flag=0,k=0;

        read(fd,&f.cbit,1);
        printf("\ncbit:%c",f.cbit);

        for(;;)
        {
           
            if((i=read(fd,&ch,1))>0)
            {
                if(ch=='@')
                {
                    read(fd,&ch,1);
                    tmp[k]=ch;
                    k++;
                   
                }
                else if(ch=='#')
                {
                    break;
                }
                else
                {
                    tmp[k]=ch;
                    k++;
                }
               
            }
            else
            {
                flag=1;
                break;
            }
        }
        tmp[k]=NULL;
        //printf("\nMsg is : %s",tmp);
       
        f.info=(char *)malloc(sizeof(char)*k);

        for(i=0;i<k;i++)
        {
            f.info[i]=tmp[i];
        }

        printf("\nMsg is: %s",f.info);
        if(flag==1)
            break;
    }
}


Bytestuff Sender

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

struct frame
{
    char cbit;
   
}f;

main()
{
    int fd,i,file1,j;
    int no=0,flag=0;
    char ch,tmp='@';

    if((fd=open("testfile",O_WRONLY))<0)
    {
        perror("File cannot opend");
    }

    if((file1=open("inputfile",O_RDONLY))<0)
    {
        perror("Input file open failed");
    }

    for(;;)
    {
        flag=0;
        no=rand()%10;       

        f.cbit='#';

        printf("\nRno: %d\n",no);
       
        write(fd,&f.cbit,1);

            for(j=0;j<no;j++)
            {
                if(read(file1,&ch,1)<=0)
                {
                    flag=1;
                    break;
                }       
                if(ch=='#' || ch=='@')
                {
                    write(fd,&tmp,1);
                   
                }
                if((i=write(fd,&ch,1))<=0)
                    perror("Message write failed");

                printf("%c",ch);
            }
        write(fd,&f.cbit,1);

            if(flag==1)
                break;       
    }

}