Thursday, July 14, 2011

C Program to Invoke DOS Command!



Today we will see how to get the System date and time as well as execute some DOS command through your ‘C’ program.

getdate() / setdate() -  Gets or sets DOS system date

 Declaration:
getdate(struct dosdate_t *datep);
setdate(struct dosdate_t *datep);
 
/* Example  of getdate() / setdate() */

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

    void main()
    {
       struct date dt;
       struct date nd;
       clrscr();
       getdate(&dt);  //Getting the date from System
       printf("\n\t\tSystem Date : %2d-%2d-%4d ",dt.da_day,dt.da_mon,dt.da_year);
       nd.da_year = 2011;
       nd.da_day = 10;
       nd.da_mon = 7;
       setdate(&nd);    //Setting a New Date
       printf("\n\t\tNew Date : %2d-%2d-%4d ",nd.da_day,nd.da_mon,nd.da_year);
       getch();
   }

Output :
                System Date : 10- 7-2011
                New Date : 10- 7-2011

 gettime() / settime() - Get and set system time

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

  void main()
    {
       struct time tm;
       struct time nt;
       clrscr();
       gettime(&tm);  //Getting the Time from System
       printf("\n\t\tSystem time : %2d:%2d:%2d ",tm.ti_hour,tm.ti_min,tm.ti_sec);
       nt.ti_hour = 13;
       nt.ti_min = 40;
       nt.ti_sec = 15;
       settime(&nt);    //Setting a New Time
       printf("\n\t\tNew Time : %2d:%2d:%2d ",nt.ti_hour,nt.ti_min,nt.ti_sec);
       getch();
   }

output:

                System time : 13:40:16
                New Time : 13:40:15

DOS – Use <dir.h> header file in addition to others for following DOS commands.

chdir() -  Changes current directory. chdir causes the directory specified by path to become the current working, such as chdir("c:\TC\MY"). Given Directory path, must specify an existing directory.
getdcwd() - Gets the current working directory for specified drive.
getcurdir() - Gets current directory for specified drive.
mkdir() -  creates a directory
rmdir() - Remove a existing directory present in current directory or given path.
perror() - Prints a System error message. perror prints to the stderr stream (normally the console) the system error message for the last library routine that produced the error.

/* Example  of above DOS commansds */

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

 void main()
    {
          char dir[12];
          char ndir[12];
          char buf[MAXPATH];
          int chk;
          clrscr();
          getcwd(buf, MAXPATH);
          printf("The current Working Directory directory is: %s\n", buf);
          //Printing Current Directory Name
          if (getcurdir(0, dir))
                   {
                             perror("getcurdir()");
                             exit(1);
                   }
          printf("Current directory is: \\%s\n", dir);
          //Creating a New Directory
          printf("\nEnter A New Directory Name : ");
          gets(ndir);
          chk = mkdir(ndir);
          if (!chk)
                   {
                             printf("Directory created\n");
                   }
          else
                   {
                             printf("Unable to create directory\n");
                             getch();
                             exit(0);
                   }
          if (chdir(ndir))
                   {
                             perror("chdir()");
                             exit(1);
                   }
          if (getcurdir(0, ndir))
                   {
                             perror("getcurdir()");
                             exit(1);
                   }
          printf("Current directory is now: \\%s\n", ndir);
          printf("\nChanging back to original directory: \\%s\n", dir);
          if (chdir("\\"))
                   {
                             perror("chdir()");
                             exit(1);
                   }
          getcurdir(0, dir);
          printf("Current directory is: \\%s\n", dir);
          chk = rmdir(ndir);
          if (!chk)
                   {
                             printf("\nDirectory deleted\n");
                   }
          else
                   {
                             perror("\nUnable to delete directory\n");
                   }
          getch();
}

Output:

The current Working Directory directory is: D:\
Current directory is: \

Enter A New Directory Name : TEMP
Directory created
Current directory is now: \TEMP

Changing back to original directory: \
Current directory is: \

Directory deleted

 findfirst() / findnext()  - findfirst and findfirst search a disk directory for files

/* findfirst and findnext example */

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

 void main()
   {
          struct ffblk ffb;
          int chk;
          clrscr();
          printf("Directory listing of *.*\n");
          chk = findfirst("*.*",&ffb,0);
          while (!chk)
                   {
                             printf("  %s\n", ffb.ff_name);
                             chk = findnext(&ffb);
                   }

       getch();
    }

Output

Directory listing of *.*
  ACCHOLD.CPP
  AD.CPP
  ADD.CPP
  ADJMAT.C
  ADMTOL.C
  ADMTOL.CPP
  AINS.C
  DT.C
  NT.C
  TC0000.SWP
  TMP.C


There are thousands of built-in-functions available in ‘C’ and ‘C++’, it is not possible to cover all. I tried some useful or mostly used one. Next blog we will move to some other thing.

Thursday, July 7, 2011

Data Conversion and some other function in C


#include <stdlib.h> header file must be included for following function.

max(), min() : max returns the larger of two values and min returns the smaller of two values. max and min are macros that generate inline code to find the maximum or minimum value of two values.

Declaration:
  (type) max(a, b);
  (type) min(a, b);

 /* Example of max/min */

 #include <stdlib.h>
 #include <conio.h>
 #include <stdio.h>
 
void main()
  {
      int x,y,z;
      printf("\nEnter two Numbers : ");
      scanf("%d%d",&x,&y);
      clrscr();
      z = max(x, y);
      printf("The larger between %d and %d is %d\n", x,y,z);
      z=min(x,y);
      printf("The smaller between %d and %d is %d\n", x,y,z);
      getch();
  }

  Output :
 
The larger between 12 and 56 is 56
 
The smaller between 12 and 56 is 12

random() : random returns a random number between 0 and (num-1).

rand() :  is a multiplicative congruential random number generator.

randomize () : randomize initializes the random number generator with a random value. Because randomize is implemented as a macro that calls the time function prototyped in TIME.H, you should include TIME.H. Unless you use randomize(), you will get same value keep retuning by random() function.

/* Example of rand() / random() / randomize() */

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

 /* prints a random number in the range 0 to 55 */
   void main()
      {
           randomize();
           clrscr();
           printf("Random number in the 0-55 range: %d\n", random (56));
           getch();
      }

Output :

Random number in the 0-55 range: 17

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

void main()
      {
          int i;
           randomize();
           clrscr();
           printf("Five random numbers from 0 to 55\n\n");
           for(i=0; i<5; i++)
           printf("%d\n", rand() % 56);
           getch();
      }


Output :
Five random numbers from 0 to 55

19
36
53
18
31

atof() : atof converts a string to a floating point. In atof, the first unrecognized character ends the conversion. atold converts a string to a long double.

/* Exmaple of atof() */

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

  void main()
      {
           float num;
           char *str = "8945.95";
           clrscr();
           num = atof(str);
           printf("String = %s Converted to float = %8.2f\n", str,num);
           getch();
      }

Output :

String = 8945.95 Converted to float =  8945.95

atoll() :   Converts a string to a long

 /* Example of atol() */

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

 void main()
 {
   long num;
   char *lstr = "98765432";
   clrscr();
   num = atol(lstr);
   printf("string = %s integer = %ld\n", lstr, num);
   getch();
 }

Output :

string = 98765432 integer = 98765432


itoa() :  itoa converts an integer to a string. itoa, ltoa, and ultoa convert value to a null-terminated string and store the result in string. If radix is 10 then conversion will be in decimal numbers and you can use 2, 8, 16 for conversion to binary, octal or in Hexa.

/* Example of itoa() */

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

void main()
{
  int number = 75;
  char string[25];
  clrscr();
  itoa(number, string, 10);
  printf("integer = %d string(Decimal) = %s\n", number, string);
  itoa(number, string, 2);
  printf("integer = %d string(Binary) = %s\n", number, string);
  itoa(number, string, 8);
  printf("integer = %d string(Octal) = %s\n", number, string);
  itoa(number, string, 16);
  printf("integer = %d string(Hexadecimal) = %s\n", number, string);
  getch();
}

Output :

integer = 75 string(Decimal) = 75
integer = 75 string(Binary) = 1001011
integer = 75 string(Octal) = 113
integer = 75 string(Hexadecimal) = 4b

div : divides two integers and returns both the quotient and the remainder, ldiv divides two longs

 Declaration:
  div_t  div(int numer, int denom);

/* Example of div) */

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

div_t x;

void main()
{
  x = div(10,3);
  clrscr();
  printf("10 div 3 = %d remainder %d\n",
  x.quot, x.rem);
  getch();

}

Output :

10 div 3 = 3 remainder 1

free() :  free deallocates a memory block allocated by a previous call to calloc, use farfree to release a large block of memory. Tiny model program can't use farfree.

/* Example of free) */

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

void main()
{
  char *str;
  str = (char *) malloc(20);  // allocate memory to string
  clrscr();
  printf("\nEnter a string upto 20 characters : ");
  gets(str);
  printf("\nString is %s\n", str);
  free(str);
  getch();
   return 0;
}

Output;

Enter a string upto 20 characters : Freezing Memory

String is Freezing Memory

Following functions are part of  #include <process.h>, used to execute certain system commands.

system() :   Issues a DOS command. system invokes the DOS command interpreter file from inside an executing C program to execute a DOS command, batch file, or other program. To execute these programs, you have to run it directly from DOS prompt by executing your .EXE files.

/* Example of free) */

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

void main()
{
  clrscr();
  printf("Run a DOS command, show the current directory list\n");
  system("dir");
  getch();

}

Output :

 Run a DOS command, show the current directory list
 Volume in drive D is Application
 Volume Serial Number is C88E-DBD1
 Directory of D:\

A                     C                     153                  07/03/11          1:41p
A                     TXT                 4394                06/05/11          8:48a
M                     TXT                 41166              06/19/11          10:28a
M1                   TXT                 22754              06/19/11          3:46p
PROGRA~1   <dir>                                        06/22/08          7:53p
SS                    TXT                 5828                05/22/11          2:28p
T                      C                     175                  07/03/11          3:07p
X                     TXT                 1016                05/22/11          2:12p
        8 file(s)      75486 bytes
                  1023932928 bytes free


abort() :  Abnormally terminates a process, abort writes a termination message on stderr ("Abnormal program termination")

/* Example of abort() */

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

 void main()
 {
   clrscr();
   printf("\Aborting\n\n ");
   abort();
   printf("Never reached statement");
   getch();
 }

Output :

Aborting

 Abnormal program termination


exit() : terminates the program. exit terminates the calling process. Before termination, exit does the
  
/* Example of exit() */

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

void main()
{
  int a,b,c;
  clrscr();
  printf("Enter two no. : ");
  scanf("%d%d",&a,&b);
  c=a+b;
  printf("\n%d + %d = %d",a,b,c);
  exit(0);
  //Exit program and following statements are unreachable
  c=a*b;
  printf("\n%d * %d = %d",a,b,c);
  getch();
}


Output :

Enter two no. : 55
67

55 + 67 = 122


Next week it will be functions that can run DOS commands and the functions that gives you system date and times.