Saturday, March 21, 2009

//Use of Buffer

#include \
#include \
#include \
#include \
#include \
#include \

int main(void)
{
char a[3][50];
int i=0,resp=1,sel,lock[3]={0,0,0},dlock[3]={0,0,0};
char f1[3][100];
int fd[3],ia=0,ib=0,ic=0,s[3],f;
int bptr[3];//the buffer offsets
int buf_rem,fsz[3],t[3];

printf("\nEnter the 3 file names\n");
for(i=0;i<3;i++)
{
printf("\nFile %d : ",i+1);
scanf("%s",&f1[i]);
}

for(i=0;i<3;i++)
{
if(strlen(f1[i])==0)
{
lock[i]=1;
}
}

for(sel=0;sel<3;sel++)
{
if(lock[sel]==0)
{
fd[sel]=open(f1[sel],O_RDONLY);
fsz[sel]=lseek(fd[sel],0,SEEK_END);
lseek(fd[sel],0,SEEK_SET);
}
}
sel=0;

BEGIN:

printf("\nFile IDs :\n");
for(i=0;i<3;i++)
{
if(lock[i]==1)
{
continue;
}
printf("%s has fileid %d",f1[i],i);
printf("\n");
}
ide:
printf("\nWhich File do you want to read? (Enter ID)\n");
scanf("%d",&sel);
if(lock[sel]==1)
{
printf("\nThe file name was not entered there\n");
goto ide;
}

if(sel != 0 && sel !=1 && sel != 2)
{
printf("\nReenter the IDs\n");
goto ide;
}


start1:

printf("Enter the bytes to be read\n");
scanf("%d",&s[sel]);
if(bptr[sel] == 0) //first time
{
ia=read(fd[sel],a[sel],50);

t[sel]=s[sel];

while(t[sel] && fsz[sel]!=0)
{
printf("%c",a[sel][bptr[sel]]);//print the output to screen
bptr[sel]++;//increase buffer pointer
t[sel]--; //decrease temporary count of remaining chars
fsz[sel]--; //file size 0?
}
if(fsz[sel]==0)
{
printf("EOF");
goto opt;
}
}
else
{
//buf_rem=50-bptr[sel];
t[sel]=s[sel];
while(t[sel])
{
if(fsz[sel]==0) //file over
{
printf("EOF");
goto opt;
}
if(bptr[sel]>=50) //refilling buffer
{
ia=read(fd[sel],a[sel],50);
bptr[sel]=0;
}
fsz[sel]--;
printf("%c",a[sel][bptr[sel]]); //output the buffer on to screen
bptr[sel]++;
t[sel]--;
}
}
opt: //multi file options
printf("\n0 to continue with this file, 1 to switch file, 2 to exit\n");
scanf("%d",&f);

switch(f)
{
case 0:
goto start1; //to continue with current file
case 1:
goto BEGIN; //change the file
case 2:
goto end1; //Exit the program
default:
printf("\nInvalid Option\n");
goto opt;
}

end1:

return 0;
}

Wednesday, November 26, 2008

Addition in C using a macro

#include
#include

#define add(a,b) a+b //defining the macro

void main()
{

int x,y,sum;
clrscr();
printf("enter the 2 numbers for addition\n");
scanf("%d\n%d",&x,&y);
sum = add(x,y); //using it here
printf("\ntheir sum is %d",sum);
getch();

}

Finding Factorial (Code for Borland C) using recursion

#include
#include
void main()
{
float fact(float),f;

clrscr();

printf("\nEnter the number whose factorial is to be found out\n");
scanf("%f",&f);
printf("\nThe factorial of %f is %f.",f,fact(f));

getch();


}


float fact(float no)
{
float factorial;
if(no==1)
return 1;
else
factorial=no*fact(no-1);
return factorial;

}