Friday, September 16, 2011

Deleting a File in C

Here is the program to delete a file in C......
#include <stdio.h>
#include<stdio.h>
#include<errno.h>
int main(void)
{
   char file[80];
   int i;
   clrscr();
   printf("File to delete: ");
   gets(file);
   i=remove(file);
   if(i==0)
   {
   printf("file removed");
   }
   else
   {
   if(errno==ENOENT)
   printf("\nNo such file exists");
   if(errno==EACCES)
   printf("\nPermission denied");
   }
   getch();
   return 0;
}
Feel Free to Comment if any point is not clear.........

Tuesday, September 13, 2011

Renaming a file in c

In this post we will find how to rename and move a file in the same drive using c language....
This can be done in c using the rename() function..The prototype of rename is:
int rename(const *char oldname,const *char newname);
On sucess--it returns 0,
On error---it returns -1;
Let us take an example:

#include <stdio.h>
#include<conio.h>
#include<errno.h>
int main(void)
{
   char oldname[80], newname[80];
   int i;
   clrscr();
   printf("Enter File to rename: ");
   gets(oldname);
   printf("\nEnter New name: ");
   gets(newname);
   i=rename(oldname, newname);
     if(i==0)
     {
     printf("rename done");
     }
     else
     {
     if(errno==ENOENT){printf("no such file/directory exists");}
     if(errno==EACCES){printf("access denied");}
     if(errno==ENOTSAM){printf("Drive is not same");}
     }
getch();
   return 0;
}
Let us find the output for different inputs
output:
Enter  File to rename:c:\test.txt
Enter New name:c:\go.txt
rename done
Explanation:it will sucessfully rename the file test to go in the c drive

output:
Enter  File to rename:d:\test.txt
Enter New name:c:\go.txt
Drive is not same
Explanation:Using rename function u can only work within a drive

output:
Enter  File to rename:d:\test.txt
Enter New name:d:\moveinthis\go.txt
rename done
Explanation:You can move the file from one directory to another directory using rename but the condition is that the directories must be in the same drive......

output:
Enter  File to rename:d:\ex.txt
Enter New name:d:\moveinthis\go.txt
no such file/directory exists
Explanation:This message will come if there is no file named as ex.txt present in the d drive......

output:
Enter  File to rename:c:\temp
Enter New name:c:\check
rename done
Explanation:We can rename also a directory  using the rename function,but still the condition is we must work in the same drive.....

Thursday, September 8, 2011

The difference between pointer to array and pointer to its first element

In the previous Post,We have seen that the address of array and the address of its first element is same,so,the question was what is the difference between Pointer to array and the Pointer to the first element of array while both contains the same address as proved in this Post....
That is if write something like this--
int (*ptr)[5];
ptr=&a;
and a pointer to first element of the array that is....
int *ptr1;

ptr1=a;
Then,What's the Difference between ptr and ptr1??????

To Get the difference between we have just to recall the concept of pointer arithmetic that is what happens if we add some number to a pointer??...
As we know whenever we add any number to the pointer the pointer appends to the memory location which is equal to the sizeof datatype*number....
For example:if a pointer is pointing to an int and its value is 65588 then if we add 1 to the pointer then it goes to 65590 that is (sizeof int *num) that is 2*1=2,so 2 gets added to the pointer and now it points to 65590 memory location...

So,Having the concept of pointer arithmetic in mind when we declare a pointer to an array and increments it the value of the pointer get incremented by sizeof array*datatype size*number...

For example:
if we write int a[5]={1,2,3,4,5};
the sizrof array is 5,
datatype size is 2 for int(16-bit assumed),
and number is 1,
int(*ptr)[5];
ptr=&a;
ptr=ptr+1;or ptr++;
if in address of array is 65516 that is ptr is 65516 in the beginning then after ptr=ptr+1 or ptr++;
The value of ptr is 65516+(5*2*1)=65516+10=65526
This is what happens if ptr is the pointer to array and if the ptr is the pointer to the first elements of the array then as the first element is an int so when we increments the ptr the value get incremented by sizeof int that is it points to the next element...
let us write a program 
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5]={1,2,3,4,5};
int(*ptr1)[5];
int *ptr2;
ptr1=&a;//pointer to an array
ptr2=&a[0];//pointer to first element of array
printf("The address of array is:%u",ptr1);
printf("\nThe address of first element of array is:%u",ptr2);
ptr1++;
printf("\nNow the value of ptr1 is:%u",ptr1);
ptr2++;
printf("\nNow the value of ptr2 is:%u"",ptr2);
}
output:
The address of array is:65516
The address of first element of array is:65516
Now the value of ptr1 is:65526
Now the value of ptr2 is:65518


I explained to the best of my knowledge,Correct me if there is anything wrong by commenting ,your comments,query and suggestions are invited to raise the level of this blog......
Have a nice time.....

Wednesday, September 7, 2011

Address of array and Address of first element of array

Today we will explore the address of array and the Address of First Element of the same array....
let us first create an array of int containing the 5 elements.
int a[5]={1,2,3,4,5};
Here a is the array of the 5 int data type elements...
As we know we can find the address of the array by applying the & operator with the array name that is "a",so the address of the aray is "&a"...we can print this address using the %u format specifier in the printf..
printf("address of array is:%u",&a);//address of the array
let us write a program..
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={1,2,3,4,5};
clrscr();
printf("The address of array is:%u",&a);
getch();
}
The output is the address of the array...let us say it prints
The address of array is:65516
Now let us find the address the first element of the array,as ww know we can get the first element by a[0],and its address by &a[0]..
so the statement printf("The address of first element is:%u",&a[0]); gives the address of the first element of the array...it prints.
The address of first element is:65516
Further,we also know that the a(the name of the array) is nothing but the pointer to the first element of the array so printing the a will also give the same value....

#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={1,2,3,4,5};
printf("The address of array is:%u",&a);
printf("The address of first element is:%u",&a[0]);
printf("The value of a is:%u",a);
}
output:
The address of array is:65516
The address of first element is:65516
The value of a is:65516

As we can see the result the,The conclusion is...
"The Address of Array and the Address of its first element is Same........".
As for the explanation we can say that array starts from the first element so the address of its first elements is same as the address of itself........

So,the Question arises--
"What's the Difference Between Pointer to array and the pointer to the first element of array if both contains the same address????"
that is:
if we declare int a[5];
and a pointer to array that is...
int (*ptr)[5];
ptr=&a;
and a pointer to first element of the array that is....
int *ptr1;
ptr1=a;
so,What's the Difference between ptr and ptr1??????
Get Answer here.

Sunday, September 4, 2011

MAC address using c

Mac Address-->from Wikipedia
A Media Access Control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment. MAC addresses are used for numerous network technologies and most IEEE 802 network technologies including Ethernet. Logically, MAC addresses are used in the Media Access Control protocol sub-layer of the OSI reference model.
MAC addresses are most often assigned by the manufacturer of a network interface card (NIC) and are stored in its hardware, the card's read-only memory, or some other firmware mechanism. If assigned by the manufacturer, a MAC address usually encodes the manufacturer's registered identification number and may be referred to as the burned-in address. It may also be known as an Ethernet hardware address (EHA), hardware address or physical address. A network node may have multiple NICs and will then have one unique MAC address per NIC.

Now the question is How can we find the Mac Address using C language....
There may be many methods to do that but  i am using the sytem() function which is used to run the DOS command using C and the FILE handling to get the MAC address or pghysical address of the pc...

As we know we can get the physical or MAC address using the DOS command "ipconfig/all" ..u can get the mac address using this command from the dos prompt as shown in the figure below..
As you can se in the figure the Physical Address is 00-1C-C0-1A-6E-C0
Now mout ask is only to show this address as theoutput of our C program....
What firstly Strike in the mind,the idea is :
"To get the ipconfig/all command executed using sytem funtion and redirecting the output to the string or taking the output to the string and then getting the substring form that main string starting from the Physical Address that will be easy and simple....."
I also look for that and tried but was not able to do the same....any help in this regard will be appriciated
now what i have done to get the only MAC address or the physical addres,i just rediredced the output of the system funtion() with the inconfig/all command to a file ,read that file back line by line which is very necessary then search for the substring starting with Physical Address or containg the Physical Address,get that printed and get out of the loop using break....
You can see the code below...
#include <stdio.h>
#include<conio.h>
int main ()
{
  FILE *fp;
  clrscr();
  system ("ipconfig/all>f:\macid.txt");
   fp=fopen("f:\macid.txt","r");
   if(fp!=NULL)
   {
   char line[128];
   while(fgets(line,sizeof line,fp)!=NULL)
   {
   char *nwln=strchr(line,'\n');
   char *ptr;
   if(nwln!=NULL)
   *nwln='\0';
   ptr=strstr(line,"Physical Address");
   if(ptr!=NULL)
   {
   printf("%s\n",ptr);
   break;
   }
  }
   }
  getch();
  return 0;
} 
NOTE:Run the program using DOS Prompt instead of turboc ide....
Your comments and query are invited .....

Dos Command in C

This example will show how to use the DOS command in C and rediret its output to a file..
#include <stdio.h>
#include<conio.h>
void main ()
{
  FILE *fp;
  clrscr();
  printf ("Checking if processor is available...");
  if (system(NULL))
  {
  puts ("Ok");
  }
  else
  {
  printf("Processor is not available");
  getch();
  exit (1);
  }
  system ("dir>c:\dirlist.txt");
  printf("Done!!File created");
getch();
}
output:will create the file with name dirlist in the "c:\" drive..........

Tuesday, August 30, 2011

Check whether the processor is available or not

This program will check whether the processor is available or not..
#include<stdio.h>
#include<conio.h>
void main()
{
printf ("Checking if processor is available...");
if (system(NULL))
printf("Processor is available");
else
printf("Processor is not available");
getch();
}

Running a DOS command using C

To Run a DOS command using C we use the system() function present in process.h and stdlib.h
The prototype of the function is:
int system(const char *command);
On Success returns 0
On Error returns -1
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i;
printf("This program will execute the DOS command");
i=system("dir");
if(i==0)
printf("completed successfully");
else
printf("error in executing the command");
getch();
}
If you are using turboc3 and run this using Ctrl+F9 you will not see the error , to run this go to cmd prompt and then execute the exe file created after compiling the program form the DOS prompt.you will easily get the output..if you are having any problem...just mail me at milankmr2011@gmail.com

Reading a file line by line in C

This post will help you in reading a file line by line...
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp=fopen("c:\milan.c","r");
clrscr();
   if(fp!=NULL)
   {
   char line[128];
   while(fgets(line,sizeof line,fp)!=NULL)
   {
   char *nwln=strchr(line,'\n');
   if(nwln!=NULL)
   *nwln='\0';
   printf("%s\n",line);
   }
   }
  getch();
}

Tuesday, August 23, 2011

sorting the strings

#include<conio.h>
#include<string.h>
void main()
{
char *names[]={"zzz","aaa","ccc","yyy"};
int i=0,j=0;
char *temp;
for(i=0;i<4;i++)
{
for(j=i;j<4-i-1;j++)
{
if(strcmp(names[j],names[j+1])>0)
{
temp=names[j];
names[j]=names[j+1];
names[j+1]=temp;
}
}
}

for(i=0;i<4;i++)
{
puts(names[i]);
}
getch();
}

String valid or not

#include<stdio.h>
#include<conio.h>
#define SIZE 100
struct stack
{
int top;
char items[SIZE];
};
void push(struct stack*,char);
char pop(struct stack*);
int empty(struct stack*);
void main()
{
struct stack s;
struct stack *ps;
char *str;
int valid=1;
ps=&s;
s.top=-1;
clrscr();
printf("enter a string to check its validity\n");
printf("String::");
scanf("%s",str);
printf("\nString is %s",str);
while(*str!='\0')
{
char ch;
char temp;
ch=*str;

//printf("\n character taken from string is %c",ch);

if(ch=='(' || ch=='{' || ch=='[')
push(ps,ch);
if(ch==')' || ch=='}' || ch==']')
{
if(empty(ps))
{
valid=0;
break;
}
else
{
temp=pop(ps);
if(temp=='('&& ch==')' || temp=='{'&& ch=='}' || temp=='['&& ch==']')
{
valid=1;
}
else
{valid=0;break;}
}
}
str++;
}//end while

if(!empty(ps))
valid=0;

if(valid)
printf("\nString is valid");
else
printf("\nString is not valid");

getch();
}//end main

void push(struct stack *ps,char ch)
{
ps->items[++(ps->top)]=ch;
}
char pop(struct stack *ps)
{
return(ps->items[(ps->top)--]);
}
int empty(struct stack *ps)
{
if(ps->top==-1)
return 1;
return 0;
}
output:
enter a string to check its validity
String::a+b(-2+3))
String is a+b(-2+3))
String is not valid

Sleep function in C

#include <dos.h>
#include <stdio.h>
#include<conio.h>
void main()
{
char s[]="milan";
int i;
for(i=0;i<5;i++)
{
printf("%c",s[i]);
sleep(1);
}
getch();
}

Breaking the string

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *s;
int len,i,j;
clrscr();
printf("enter a string:");
gets(s);
len=strlen(s);
for(i=0;i<len;i++)
{
for(j=0;j<=i;j++)
{
printf("%c",*(s+j));
}
printf("\n");
}
getch();
}

Generating the Random number

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
 int i;
printf("Ten random numbers from 0 to 99\n\n");
for(i=0; i<10; i++)
printf("%d\n", rand() % 100);
getch();
return 0;
}

busy process....

#include<stdio.h>
#include<conio.h>
#include<dos.h>
main()
{
    int m,kbhit(void);
    clrscr();
    while(!kbhit())
    {
        printf("\b\\");
        delay(100);
        printf("\b|");  
        delay(100);
        printf("\b/");
        delay(100);
        printf("\b-");
        delay(100);
    }
return;
}

left padding a digit

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n=7;
printf("%.10d",n);//padding with zeroes technique
} 

Number Pattern7

1
01
101
0101
10101
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=0;i<5;i++)
{
for(j=i+1;j<=(2*i+1);j++)
{
if(j%2==0)
{
printf("0");
}
else
{
printf("1");
}
}
printf("\n");
}
getch();
}

Number Pattern7

5              5
54          45
543      345
5432  2345
543212345
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=5;j>=i;j--)
{
printf("%d",j);
}
for(j=1;j<i;j++)
{
printf(" ");
}
for(j=2;j<i;j++)
{
printf(" ");
}
for(j=i;j<=5;j++)
{
if(j==1)
j++;
printf("%d",j);
}
printf("\n");
}
getch();
}

Number Pattern6

5
44
333
2222
11111
2222
333
44
5
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=1;j<i;j++)
{
printf("");
}
for(j=5;j>=i;j--)
{
printf("%d",i);
}
printf("\n");
}
for(i=2;i<=5;i++)
{
for(j=1;j<i;j++)
{
printf("");
}
for(j=5;j>=i;j--)
{
printf("%d",i);
}
printf("\n");
}
getch();
}

Number Pattern5

1111
  222
    33
      4
    33
  222
1111
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=4;i++)
{
for(j=2;j<=i;j++)
{
printf(" ");
}
for(j=4;j>=i;j--)
{
printf("%d",i);
}
printf("\n");
}

for(i=3;i>=1;i--)
{
for(j=i;j>=2;j--)
{
printf(" ");
}
for(j=4;j>=i;j--)
{
printf("%d",i);
}
printf("\n");
}
getch();
}

Number Pattern4

        5
      54
    543
  5432
54321
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
printf(" ");
}
for(j=5;j>=i;j--)
{
printf("%d",j);
}
printf("\n");
}
getch();
}

Number Pattern3

        1
      21
    321
  4321
54321
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=4;j>=i;j--)
{
printf(" ");
}
for(j=i;j>=1;j--)
{
printf("%d",j);
}
printf("\n");
}
getch();
}

Number Pattern2

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63 64 65 66
67 68 69 70 71 72 73 74 75 76 77 78
79 80 81 82 83 84 85 86 87 88 89 90 91 
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,x;
clrscr();
x=1;
while(x<=12)
{
for(i=1;i<=79;)
{
for(j=i;j<i+x;j++)
{
printf("%d ",j);
}
printf("\n");
i=i+x;
x++;
}
}
getch();
}

star pattern2

        *
      **
    ***
  ****
*****
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
    {
        for(j=4;j>=i;j--)
        {
        printf(" ");
        }

    for(j=1;j<=i;j++)
    {
    printf("*"
    );
    }
printf("\n");
}
getch();
}

Number Pattern1

54321
5432
543
54
5
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
{
printf("%d",j);
}
printf("\n");
}
getch();
}

Star pattern1

*****
****
***
**
*
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
{
printf("*");
}
printf("\n");
}
getch();
}

Saturday, August 20, 2011

a tricky printf again...........

Here is a question which i am going to explore best to my concepts and knowledge,you can judge for yourself whether i am right or wrong..
int main()
{
int val=10;
printf(":%d",val+1,"-%d",val--);
return(0); 
}

Before evaluating this ques let us first evaluate the following printf statement
print(":%d",val+1,"-%d",val+2);


output for this printf:
:11
Explanation::As we know that printf first take the format string and according to the format specifiers in the format string it prints the arguments supplied to that..In this statement:
Format string is :%d
and the variable list id:val+a,"=%d",val+2
So this prints the val+1 that is 11 for the %d and leaves the another variables....

Now what if we want to print the remaining variables.......that so simple as we can see that the 2nd variable is a string and the third argument is an integer in the variable list so we should have the format string as given below:
format string----->:%d%s%d
and variables list is----->val+1, "-%d",val+2


so the output for this will be------>:11-%d12 
that is -%d is the string in this variable list so we have to use the %s format specifier to print this....


Now coming back to the real question,in the real question the printf statement is :
printf(":%d",val+1,"-%d",val--); 
If strictly speaking the result of this is undefined as you can read the sequence point post ,
No doubt the evaluation will be from right to left but we can't assure the result...but let us suppose everything goes according to our will or thinking that is smooth evaluation form right or left then first val-- will be evaluated that will decrement the val to 9 then val+1 which lead to print 10 as the output
so the output will be----->:10
To prove the evaluation is  from right to left let us print the value of val--;
printf(":%d%s%d",val+1,"-%d",val--);
output--->:10-%d10

You might not be satisfied with the prove of right to left evaluation so just change the val-- to --val because above example shows the postfix property that is printing before decrementing

printf(":%d%s%d",val+1,"-%d",--val);
output--->:10-%d9
Now i thing it will be cleared to you....

 May be i am wrong,so please do comment whether you agree with me or not????
if not give the explanation..... 

Tuesday, August 16, 2011

Saving Password in a file

#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
char pw[100];
char *ptr;
int i=0;
FILE *fp;
clrscr();
printf("Enter the password:\n");
ch=getch();
while(ch!=13)
{
if(ch==8)
{
printf("\b");
putch(NULL);
printf("\b");
pw[i]='\0';
--i;
}
else
{
printf("%c",ch);
putch('\b');
printf("*");
pw[i++]=ch;
}
ch=getch();
}
pw[i]='\0';
ptr=pw;
fp=fopen("c:\milan.txt","w");
while(*ptr!='\0')
{
fputc(*ptr,fp);
ptr++;
}
printf("\nPassword successfully saved in the file");
getch();
}

Comparing the password

#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
char ch;
char pw[100];
char pswd[]="password";
int i=0;
clrscr();
printf("Enter the password:\n");
ch=getch();
while(ch!=13)
{
if(ch==8)
{
printf("\b");
putch(NULL);
printf("\b");
pw[i]='\0';
--i;
}
else
{
printf("%c",ch);
putch('\b');
printf("*");
pw[i++]=ch;
}
ch=getch();
}
pw[i]='\0';
printf("\npassword is:%s",pw);
if(strcmp(pswd,pw)==0)
{
printf("\n password matched");
}
else
{
printf("\n password in wrong");
}
getch();
}

Saving the password in an array

#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
char ch;
char pw[100];
int i=0;
clrscr();
printf("Enter the password:\n");
ch=getch();
while(ch!=13)
{
if(ch==8)
{
printf("\b");
putch(NULL);
printf("\b");
pw[i]='\0';
--i;
}
else
{
printf("%c",ch);
putch('\b');
printf("*");
pw[i++]=ch;
}
ch=getch();
}
pw[i]='\0';
printf("\npassword is:%s",pw);
getch();
}

Delay in Password view

#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
char ch;
clrscr();
printf("Enter the Password:\n");
ch=getch();
while(ch!=13)
{
if(ch==8)
{
printf("\b");
putch(NULL);
printf("\b");
}
else
{
printf("%c",ch);
delay(500);
putch('\b');
printf("*");
}
ch=getch();
}
}

A program to implement the password view

This program will print the * whenever you press any digit and will also omit the last character after pressing the backspace..
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
ptintf("enter the password:\n");
ch=getch();
while(ch!=13)
{
if(ch==8)
{
putch('\b');
putch(NULL);
putch('\b');
}
else
{
printf("%c",ch);
putch('\b');
printf("*");
}
ch=getch();
}
}

Thursday, March 24, 2011

difference between far and huge pointers

as we know by default the pointers are near for example int *p is a near pointer... size of near pointer is 2 bytes in case of 16 bit compiler........ n we already know very well size varies compiler to compiler...... They only store the offset of the address the pointer is referencing. . An address consisting of only an offset has a range of 0 - 64K bytes.... i think there is no need to discuss near pointers anymore.... so come to the main point..... that is far and huge pointers......

far and huge pointers:
Far and huge pointers have a size of 4 bytes. They store both the segment and the offset of the address the pointer is referencing. thn what is the difference between them ...........

Limitation of far pointer:

We cannot change or modify the segment address of given far address by applying any arithmetic operation on it. That is by using arithmetic operator we cannot jump from one segment to other segment. If you will increment the far address beyond the maximum value of its offset address instead of incrementing segment address it will repeat its offset address in cyclic order. this is also called wrapping.....i.e. if offset is 0xffff and we add 1 then it is 0x0000 and similarly if we decrease 0x0000 by 1 then it is 0xffff and remember there is no change in the segment....

Now i am going to compare huge and far pointers..........

1.
When a far pointer is incremented or decremented ONLY the offset of the pointer is actually incremented or decremented but in case of huge pointer both segment and offset value will change.....
like if we have

int main()
{
char far* f=(char far*)0x0000ffff;
printf("%Fp",f+0x1);
return 0;
}

then the output is:
0000:0000

as we see there is no change in segment value.......

and in case of huge........

int main()
{
char huge* h=(char huge*)0x0000000f;
printf("%Fp",h+0x1);
return 0;
}

then the o/p is:
0001:0000

it shows bcoz of increment operation not only offset value but segment value also change.......... that means segment will not change in case of far pointers but in case of huge it can move from one segment to another ......

2.
When relational operators are used on far pointers only the offsets are compared.In other words relational operators will only work on far pointers if the segment values of the pointers being compared are the same. and in case of huge this will not happen, actually comparison of absolute addresses takes place...... lets understand with the help of an example...
in far...............................

int main()
{
char far * p=(char far*)0x12340001;
char far* p1=(char far*)0x12300041;
if(p==p1)
printf("same");
else
printf("different");
return 0;
}

Output:
different

in huge.......................

int main()
{
char huge * p=(char huge*)0x12340001;
char huge* p1=(char huge*)0x12300041;
if(p==p1)
printf("same");
else
printf("different");
return 0;
}

Output:
same

Explanation:
as we see the absolute address for both p and p1 is 12341 (1234*10+1 or 1230*10+41) but they are not considered equal in 1st case becoz in case of far pointers only offsets are compared i.e. it will check whether 0001==0041.... that we know is false.... and know see what will happen in case of huge.....the comparison operation is performed on absolute addresses that are equal as i already told......

3.
A far pointer is never noramlized but a huge pointer is normalized . A normalized pointer is one that has as much of the address as possible in the segment, meaning that the offset is never larger than 15.
suppose if we have 0x1234:1234 then the normalized form of it is 0x1357:0004(absolute address is 13574).......
A huge pointer is normalized only when some arithmetic operation is performed on it ... and not noramlized during assignment....

int main()
{
char huge* h=(char huge*)0x12341234;
char huge* h1=(char huge*)0x12341234;
printf("h=%Fp\nh1=%Fp",h,h1+0x1);
return 0;
}

Output:
h=1234:1234
h1=1357:0005

Explanation:
as i said above huge is not normalized in case of assignment......but if an arithmetic operation is performed on it ..... it will be normalized.... so h is 1234:1234 and h1 is 1357:0005..........that is normalized.......

4.
The offset of huge pointer is less than 16 because of normalization and not so in case of far pointers...................

lets take an example to understand what i want to say.....
int main()
{
char far* f=(char far*)0x0000000f;
printf("%Fp",f+0x1);
return 0;
}

Output:
0000:0010

in case of huge
int main()
{
char huge* h=(char huge*)0x0000000f;
printf("%Fp",h+0x1);
return 0;
}

Output:
0001:0000

Explanation:
as we increment far pointer by 1 it will be 0000:0010...... and as we increment huge pointer by 1 thn it will be 0001:0000 bcoz its offset cant be greater than 15 in other words it will be normalized............

i tried my best to explain this...... if any query and suggestion plz comment here.........

Friday, March 18, 2011

difference between typedef and #define

lets have a look at whats the difference between typedef and #define.....

A typedef is just a new name for an already existing type and defines are handled by the preprocessor while typedefs are handled by the C compiler itself.
#define can be used to rename anything not just a type like typedef.................for e.g.

#define AND && and we cant use typedef for that like typedef && AND; its not possible with typedef...... some more examples like #define PRINT printf("hello") or #define sum(a,b) (a+b)....all this is not possible with typedef...................

we all know this very well so i am not going to explain this but what will happen if we use #define to rename a type................

suppose if we have
typedef char * ptr;
#define PTR char *

both of them are looking similar......


lets understand the difference with the help of an example............

typedef char * ptr;
#define PTR char *
int main()
{
ptr a,b,c;
PTR x,y,z;
printf( "sizeof a:%u\n" ,sizeof(a) );
printf( "sizeof b:%u\n" ,sizeof(b) );
printf( "sizeof c:%u\n" ,sizeof(c) );
printf( "sizeof x:%u\n" ,sizeof(x) );
printf( "sizeof y:%u\n" ,sizeof(y) );
printf( "sizeof z:%u\n" ,sizeof(z) );
return 0;
}

Output:
sizeof a:2
sizeof b:2
sizeof c:2
sizeof x:2
sizeof y:1
sizeof z:1

Explanation:
in case of turbo C compiler the size of pointer is 2 and in other compilers it is different it may be 4 like in dev compiler .........thats not our point of discussion.....we have to discuss why is there such output.........

Note that y and z do not have the same size as the x whereas a,b and c are consistent. Why is this? Simple: we used a macro for x y and z.

Look at what the macro actually does:

#define PTR char *

PTR x,y, z;
This is in turn converted (by simple text substitution) to:
char *x ,y, z;
That line does not define three pointer variables. It defines three variables with a base type of "char" one of which x is a pointer. It is the same as writing:
char *x;
char y;
char z;
The typedef dont fail this way because when we defined the new type we defined it specifically as a pointer type meaning that any variable defined with the new type will in fact be a pointer variable.......

\xhh hexadecimal number

lets understand the use of \xhh escape sequence with the help of some interesting examples
here hh is one or more hexadecimal digits(0....9,a...f,A...F).......firstly understand the meaning of one or more characters...it means there can be any no. of hexadecimal digits after \x.....

1.
int main()
{
char *s="A\x3a";
printf("%s",s);
return 0;
}

Output:
A:

Explanation:
here '\x3a' is a hexadecimal number n it is a single char....... firstly it will get converted in to decimal notation i.e. 58 and it is the ASCII value of char ':' hence at the place of \x3a there is :........................ so the output is A:............

2.
int main()
{
char *s="A\x003a";
printf("%s",s);
return 0;
}

Output:
A:

Explanation:
decimal notation of 003a is 58.................here i m trying to show there can b any no. of hexadecimal digits after \x...............

3.
#define new '\xa'
int main()
{
printf("A%c",new);
return 0;
}

Explanation:
here the output is A n the cursor is in the next line bcoz as we know the ascii value of new line character is 10.................so very interesting there is one more escape sequence to do the work of new line character..................

\ooo octal number

lets understand the use of \ooo escape sequence with the help of some interesting examples
here ooo is one to three octal digits(0....7) means there must be atleast one octal digit after \ and maximum three..........
1.
int main()
{
char *s="A\0655";
printf("%s",s);
return 0;
}

Output:
A55

Explanation:
its very interesting to know the reason behind such output.......here 065 is the octal notation....... firstly it will get converted in to decimal notation i.e. 53 and it is the ASCII value of char '5' hence at the place of \065 there is 5........................ so the output is A55............

okay,lets understand it with 1 more example.....

2.
int main()
{
char *s="A\035B";
printf("%s",s);
return 0;
}

Output:
A<->B

Explanation:
decimal notation of 035 is 29.................n it is the ASCII value of '<->' char.......... hence the output is A<->B........................

2.
int main()
{
char *s="A\33A";
printf("%s",s);
return 0;
}

Output:
A<-A

Explanation:
decimal notation of 33 is 27.................n it is the ASCII value of '<-' char.......... hence the output is A<-A........................it shows octal number can have two octal digits also.............similarly there can be only 1 octal digit.................

try for different strings......its really amazing.................

Thursday, March 17, 2011

getche() vs getchar()........

let us try to u nderstand this by the help of an example.....just write a program to enter you name and print that on the screen.....everyone can write that program so easily.....

void main()
{
char c[15];
printf("enter your name:");
scanf("%s",c);
printf("\nyour name is:%s",c);
getche();
}

output:
enter yourname:milan
your name is :milan

this runs fine ,and wait for the character on the getche() function call as expected....

Now,chnage the getche() to getchar()

void main()
{
char c[15];
printf("enter your name:");
scanf("%s",c);
printf("\nyour name is:%s",c);
getchar();
}

after running with getchar() you willl find that it does not wait for the character and output screen goes away....
why it is so????
Explanation:
this happens because the mechanism of getche() and getchar() is different..
1.)getche() directly takes the input directly from the input stream and getchar() reads that from the input buffer....
2.)getche() does not wait for the enter key and getchar() wait for hte enter key....

Now we enter our name and press enter that enter goes as the input for the getchar() function....let us prove this.......
void main()
{
char c[15],d;
 printf("enter your name:");
scanf("%s",c);
printf("\nyour name is:%s",c);
d=getchar();
printf("the ASCII value of enter key is %d and it is true",d);
getch();
}

output:
enter your name:milan
your name is:milan
the ASCII value of enter key is 10 and it is true.....

so u can see the enter pressed after entering the name goes as the input to the getchar() function.....

solution to this problem:
use the fflush function withe the input stream from where you are reading the data that is generally stdin (standard input).....it will clear the input stream buffer and now getchar() will wait ......
check this:
void main()
{
char c[15];
printf("enter your name:");
scanf("%s",c);
printf("\nyour name is:%s",c);
fflush(stdin);
getchar();
}


another example which proves that getchar() waits for the enter key and takes the first character int the buffer after pressing the enter........

#include<stdio.h>
#include<conio.h>
void main()
{
char a,b,c;
clrscr();
printf("Enter a charater-->");
a=getche();
printf("\nThe character pressed is :%c",a);
printf("\nNow enter the another charater-->");
b=getchar();
printf("Now the character pressed is:%c",b);
getch();
}

output:
Enter a character-->m /*here you can enter only one character coz getch directly interact with input device*/
The character pressed is:m
Now enter the another character-->milan  /*here you can ebter any number of character ,all get stored int he buffer and after pressing enter the first character is taken as the input to the gatchar()*/
Now the character pressed is:m


Monday, March 14, 2011

successful input means...........

as i said in my what scanf() returns????? post................. scanf returns the number of successful inputs.................... here i am going to explain what is the meaning of successful inputs..........

It return the number of input items successfully matched (means read attempt is unsuccessful if the input characters cannot be converted according to the given format code) and assigned......................
the return value does not include fields that were read but not assigned.....
A return value of zero indicates that no fields were assigned.

lets understand with the help of some examples............

int main()
{
int i;
char *s;
printf("Enter the string:");
i=scanf("%[012356789]",s);
printf("i=%d",i);
return 0;
}

Output:
Enter the string:hello
i=0

Explanation:
in the above example the string s can take only numbers and not any other character...............so when we input hello ............ scanf reads the characters but nothing is assigned to string s, hence scanf returns 0 at the place of 1......................


int main()
{
int i,j;
printf("Enter the number:");
i=scanf("%d",&j);
printf("i=%d",i);
return 0;
}

Output:
Enter the number:h
i=0

Explanation:
scanf is trying to read an int, but it receives the letter 'h' at the place of some number, hence it will return 0 at the place of 1............... and it doesn't mean nothing is assigned to i..............

Saturday, March 12, 2011

Reading and discarding characters in scanf()

Reading and discarding characters from the input stream

1.
int main()
{
int month,day,year;

printf( "Enter a date in the form mm-dd-yyyy: " );
scanf( "%d%*c%d%*c%d", &month, &day, &year );

printf( "month = %d day = %d year = %d\n\n", month, day, year );
return 0;
}

Output:
Enter a date in the form mm-dd-yyyy:03-12-2011
month = 03 day = 12 year = 2011

Explanation:
as we write the input:03-12-2011
scanf discards the character - because we used %*c to discard that character...there can be any character at the place of -...............

2.
int main()
{
int i,j;

printf( "Enter the numbers: " );
scanf( "%d/*/%d", &i,&j );

printf( "%d %d", i,j);
return 0;

}

output:
Enter the numbers:4/*/5
4 5

Explanation:
now we enter the numbers in this format 4/*/5 because scanf( "%d/*/%d", &i,&j ) consist /*/, and it discards this................ so i = 4 and j = 5..............

*****************************************

lets take one more example with field width and *

int main()

{

int a,b;

scanf("%d%*4c%d",&a,&b);

printf("a=%d,b=%d",a,b);

return 0;

}

/*before discussing its output.....firstly understand wht %*4c will do.......it will discard the 4 characters from the input string........*/

OUTPUT:

12abcd34

a=12

b=34

Explanation:

as the input string is 12abcd34.....the scanf start reading the characters 1..2..a.. as 'a' comes it start discarding the characters......n discard 4 characters continuously and then remaining characters i.e. 34 are in b variable....n suppose if d input string is 12abcde thn b has some garbage value........bcoz 'e' will not match with %d................

%[] explored

%[] consists a set of characters
The left bracket is followed by a set of characters and a right square bracket. The characters between the brackets define a set of characters making up the string. If the first character is not a circumflex (^), the input field consists of all subsequent input characters until the function finds a character not in the character set within the brackets.

void main()
{
char *s;
printf("enter the string:");
scanf("%[0123456789]",s);
printf("%s",s);
}

output:
enter the string:345y678
345

Explanation:
the var s consists 345 because y is not in the character set hence dont take no more characters from y. the above program shows the string can contain only the numbers.....

**********************
If the first character inside the square brackets is a circumflex, the input field consists of all subsequent input characters until the function finds a character that is in the bracketed character set. Thus
lets understand it with the help of an example:
void main()
{
char *s;
printf("enter the string:");
scanf("%[^0123456789]",s);
printf("%s",s);
}

output:
enter the string:sheetal7garg
sheetal

Explanation:
in the above program, string s can't contain any number......... it takes the characters until a number comes.......as in the example input is sheetal7garg and in character set there is [^0123456789] hence take the characters until 7 comes........... hence s contains sheetal.................
**************************************
One more example to understand it......

void main()
{
char *s1,*s2;
printf("enter the string:");
scanf("%5[^abc]%s",s1,s2);
printf("s1=%s\ns2=%s",s1,s2);
}

lets see different outputs....
1.
enter the string:welcome
s1=welco
s2=me

2.
enter the string:india
s1=indi
s2=a

Explanation:
in
scanf("%5[^abc]%s",s1,s2);
%5[^abc] means string s1 can store max 5 characters and does not take a,b or c characters as shown in 1st output s1 consist welco and also the remaining characters i.e. 'm','e' go in s2 string.........................similarly,in 2nd output s1 take characters i,n,d,i and stop when 'a' comes, then 'a' character is in s2 and if there are more characters after 'a' , all these also in s2...........