Thursday, February 19, 2015

Header Files in C and C++ :

Header Files Summary

Header files, also called include files, provide function prototype declarations for library functions. Data types and symbolic constants used with the library functions are also defined in them, along with global variables defined by Parijat's C++ and by the library functions. The Parijat's C++ library
follows the ANSI C standard on names of header files and their contents.

Note:    The middle column indicates C++ header files and header files defined by ANSI C.

alloc.h        Declares memory-management functions (allocation, deallocation, and so on). 

assert.h    ANSI C    Defines the assert debugging macro.

bcd.h    C++    Declares the C++ class bcd and the overloaded operators for bcd and bcd math functions.

bios.h        Declares various functions used in calling IBM-PC ROM BIOS routines.

bwcc.h        Defines the Borland Windows Custom Control interface.

checks.h    C++    Defines the class diagnostic macros.

complex.h    C++    Declares the C++ complex math functions.

conio.h        Declares various functions used in calling the operating system console I/O routines.

constrea.h    C++    Defines the conbuf and constream classes.

cstring.h    C++    Defines the string classes.

ctype.h    ANSI C    Contains information used by the character classification and character conversion macros (such as isalpha and

toascii).

date.h    C++    Defines the date class.

_defs.h        Defines the calling conventions for different application types and memory models.

dir.h        Contains structures, macros, and functions for working with directories and path names.

direct.h        Defines structures, macros, and functions for dealing with directories and path names.

dirent.h        Declares functions and structures for POSIX directory operations.

dos.h        Defines various constants and gives declarations needed for DOS and 8086-specific calls. 

errno.h    ANSI C    Defines constant mnemonics for the error codes.

except.h    C++    Declares the exception-handling classes and functions.

excpt.h        Declares C structured exception support.

fcntl.h        Defines symbolic constants used in connection with the library routine open.

file.h    C++    Defines the file class.

float.h    ANSI C    Contains parameters for floating-point routines.

fstream.h    C++    Declares the C++ stream classes that support file input and output.

generic.h    C++    Contains macros for generic class declarations.

io.h        Contains structures and declarations for low-level input/output routines.

iomanip.h    C++    Declares the C++ streams I/O manipulators and contains templates for creating parameterized manipulators.

iostream.h    C++    Declares the basic C++ streams (I/O) routines.

limits.h    ANSI C    Contains environmental parameters, information about compile-time limitations, and ranges of integral quantities.

locale.h    ANSI C    Declares functions that provide country- and language-specific information.

malloc.h        Declares memory-management functions and variables.

math.h    ANSI C    Declares prototypes for the math functions and math error handlers.

mem.h        Declares the memory-manipulation functions. (Many of these are also defined in string.h.)

memory.h        Contains memory-manipulation functions.

new.h    C++    Access to _new_handler, and set_new_handler.

_nfile.h        Defines the maximum number of open files.

_null.h        Defines the value of NULL.

process.h        Contains structures and declarations for the spawn... and exec... functions.

search.h        Declares functions for searching and sorting.

setjmp.h    ANSI C    Declares the functions longjmp and setjmp and defines a type jmp_buf that these functions use.

share.h        Defines parameters used in functions that make use of file-sharing.

signal.h    ANSI C    Defines constants and declarations for use by the signal and raise functions.

stdarg.h    ANSI C    Defines macros used for reading the argument list in functions declared to accept a variable number of arguments

(such as vprintf, vscanf, and so on).

stddef.h    ANSI C    Defines several common data types and macros.

stdio.h    ANSI C    Defines types and macros needed for the standard I/O package defined in Kernighan and Ritchie and extended

under UNIX System V. Defines the standard I/O predefined streams stdin, stdout, stdprn, and stderr and declares

stream-level I/O routines.

stdiostr.h    C++    Declares the C++ (version 2.0) stream classes for use with stdio FILE structures. You should use iostream.h for

new code.

stdlib.h    ANSI C    Declares several commonly used routines such as conversion routines and search/sort routines.

string.h    ANSI C    Declares several string-manipulation and memory-manipulation routines.

strstrea.h    C++    Declares the C++ stream classes for use with byte arrays in memory.

sys\locking.h        Contains definitions for mode parameter of locking function.

sys\stat.h        Defines symbolic constants used for opening and creating files.

sys\timeb.h        Declares the function ftime and the structure timeb that ftime returns.

sys\types.h        Declares the type time_t used with time functions.

thread.h    C++    Defines the thread classes.

time.h    ANSI C    Defines a structure filled in by the time-conversion routines asctime, localtime, and gmtime, and a type used by the

routines ctime, difftime, gmtime, localtime, and stime. It also provides prototypes for these routines.

typeinfo.h    C++    Declares the run-time type information classes.

utime.h        Declares the utime function and the utimbuf struct that it returns.

values.h        Defines important constants, including machine dependencies; provided for UNIX System V compatibility.

varargs.h        Definitions for accessing parameters in functions that accept a variable number of arguments. Provided for UNIX

compatibility; you should use stdarg.h for new code.

Virtual Functions in C Language :

Virtual Functions :

Virtual functions let derived classes provide different versions of a base class function.
You can declare a virtual function in a base class , then redefine it in any derived class, even if the number and type of arguments are the same . The redefined function overrides the base class function.
You can also declare the functions

  int Base::Function(int)

and

  int Derived::Function(int)

even when they are not virtual.
When you declare virtual functions, keep these guidelines in mind:

    They can only be member functions.
    They can be declared a friend in another class.
    They cannot be a static member.

The base class version is available to derived class objects via scope override. If they are virtual, only the function associated with the actual type of
the object is available.
If two functions with the same name and have different arguments, C++ considers them different, and the virtual function mechanism is ignored.

virtual void gork(void) = 0;

is a pure virtual function. This makes the class an abstract type. gork() must be defined by derived classes or re-declared as pure.
Generally, when redefining a virtual function, you cannot change just the function return type. To redefine a virtual function, the new definition (in some
derived class) must exactly match the return type and formal parameters of the initial declaration. If two functions with the same name have different
formal parameters, C++ considers them different, and the virtual function mechanism is ignored.
However, for certain virtual functions in a base class, their overriding version in a derived class can have a return type that is different from the
overridden function. This is possible only when both of the following conditions are met:

    The overridden virtual function returns a pointer or reference to the base class.
    The overriding function returns a pointer or reference to the derived class.

If a base class B and class D (derived publicly from B) each contain a virtual function vf, then if vf is called for an object d of D, the call made is
D::vf(), even when the access is via a pointer or reference to B. For example,

struct X {};          // Base class.
struct Y : X {};      // Derived class.

struct B {
   virtual void vf1();
   virtual void vf2();
   virtual void vf3();
   void f();
   virtual X* pf();   /* Return type is a pointer to base. */
                      /* This can be overridden. */
   };

class D : public B {
public:
   virtual void vf1(); /* Virtual specifier is legal but redundant. */
   void vf2(int);      /* Not virtual, since it's using a different */
                       /* arg list. This hides B::vf2(). */

   // char vf3();
   // Illegal: return-type-only change!
   void f();
   Y*   pf();          /* Overriding function differs only  */
                       /* in return type. Returns a pointer */
                       /* to the derived class.             */
   };

    void extf() {
    D d;            /* Instantiate D */
    B* bp = &d;     /* Standard conversion from D* to B*             */
                    /* Initialize bp with the table of functions     */
                    /* provided for object d. If there is no entry   */

                    /* for a function in thed-table, use the         */
                    /* function in the B-table.                      */
    bp->vf1();      /* Calls D::vf1 */
    bp->vf2();      /* Calls B::vf2 since D's vf2 has different args */
    bp->f();        /* Calls B::f (not virtual)                      */

          X* xptr = bp->pf();   /* Calls D::pf() and converts the result
                                   to a pointer to X. */

       D* dptr = &d;
       Y* yptr = dptr->pf();  /* Calls D::pf() and initializes yptr. */

                              /* No further conversion is done.      */
       }

The overriding function vf1 in D is automatically virtual . The virtual specifier can be used with an overriding function declaration in the derived class. If other classes will be derived from D, the virtual keyword is required . If no further classes will be derived from D, these of virtual is redundant.
The interpretation of a virtual function call depends on the type of the object it is called for; with nonvirtual function calls, the interpretation depends only on the type of the pointer or reference denoting the object it is called for .
virtual functions exact a price for their versatility: each object in the. derived class needs to carry a pointer to a table of functions in order to select the correct one at run time (late binding) .


Learning C Functions : delay ( Dos Only )

C Programming :
Function
:
delay

Syntax


#include <dos.h>
void delay(unsigned milliseconds);

Description

With a call to delay, the current program is suspended from execution for the number of milliseconds specified by the argument milliseconds. It is no
longer necessary to make a calibration call to delay before using it. delay is accurate to a millisecond.

Return Value

None.

Example :
/* delay example */

/* emits a 440-Hz tone for 500 milliseconds */
#include <dos.h>

int main(void)
{
   sound(440);
   delay(500);
   nosound();
   return 0;
}

Learning C Functions : coreleft ( Dos Only )

C Programming :
Function
:
coreleft

Syntax
#include <alloc.h>

In the tiny, small, and medium models:

unsigned coreleft(void);

In the compact, large, and huge models:

unsigned long coreleft(void);

Description

coreleft returns a measure of RAM memory not in use. It gives a different measurement value, depending on whether the memory model is of the small
data group or the large data group .

Return Value

In the small data models, coreleft returns the amount of unused memory between the top of the heap and the stack. In the large data models, coreleft
returns the amount of memory between the highest allocated block and the end of available memory.

Learning C Functions : brk ( Dos Only )

C Programming :
Function
:
brk

Syntax

#include <alloc.h>
int brk(void *addr);

Description

brk dynamically changes the amount of space allocated to the calling program's heap. The change is made by resetting the program's break value,
which is the address of the first location beyond the end of the data segment. The amount of allocated space increases as the break value increases.
brk sets the break value to addr and changes the allocated space accordingly.
This function will fail without making any change in the allocated space if such a change would allocate more space than is allowable.

Return Value

Upon successful completion, brk returns a value of 0. On failure, this function returns a value of -1 and the global variable errno is set to

ENOMEM    Not enough memory

Example :
/* brk example */

#include <stdio.h>
#include <alloc.h>

int main(void)
{
   char *ptr;

   printf("Changing allocation with brk()\n");
   ptr = (char *) malloc(1);
   printf("Before brk() call: %lu bytes free\n", coreleft());
   brk(ptr+1000);
   printf(" After brk() call: %lu bytes free\n", coreleft());
   return 0;
}

Learning C Functions : biosprint ( Dos Only )

C Programming :
Function
:
biosprint

Example    Portability

Syntax

#include <bios.h>
int biosprint(int cmd, int abyte, int port);

Description

biosprint performs various printer functions on the printer identified by the parameter port using BIOS interrupt 0x17.
A port value of 0 corresponds to LPT1; a port value of 1 corresponds to LPT2; and so on.
The value of cmd can be one of the following:

0    Prints the character in abyte.
1    Initializes the printer port.
2    Reads the printer status.

The value of abyte can be 0 to 255.

Return Value

The value returned from any of these operations is the current printer status, which is obtained by ORing these bit values together:

Bit 0    0x01    Device time out
Bit 3    0x08     I/O error
Bit 4    0x10     Selected
Bit 5    0x20     Out of paper
Bit 6    0x40     Acknowledge
Bit 7    0x80     Not busy

Example :
/* biosprint example */

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

int main(void)
{
   #define STATUS  2    /* printer status command */
   #define PORTNUM 0    /* port number for LPT1 */

   int status, abyte=0;

   printf("Please turn off your printer. Press any key to continue\n");
   getch();
   status = biosprint(STATUS, abyte, PORTNUM);
   if (status & 0x01)
      printf("Device time out.\n");
   if (status & 0x08)
      printf("I/O error.\n");

   if (status & 0x10)
      printf("Selected.\n");
   if (status & 0x20)
      printf("Out of paper.\n");

   if (status & 0x40)
      printf("Acknowledge.\n");
   if (status & 0x80)
      printf("Not busy.\n");

   return 0;
}

Learning C Functions : bioskey ( Dos Only )

C Programming :
Function
:
bioskey

Syntax

#include <bios.h>
int bioskey(int cmd);

Description

bioskey performs various keyboard operations using BIOS interrupt 0x16. The parameter cmd determines the exact operation.

Return Value

The value returned by bioskey depends on the task it performs, determined by the value of cmd:

0    If the lower 8 bits are nonzero, bioskey returns the ASCII character for the next keystroke waiting in the queue or the next key pressed at the keyboard. If the lower 8 bits are zero, the upper 8 bits are the extended keyboard codes defined in the IBM PC Technical Reference Manual.
1    This tests whether a keystroke is available to be read. A return value of zero means no key is available. The return value is 0xFFFFF (-1) if Ctrl-Brk
has been pressed. Otherwise, the value of the next keystroke is returned. The keystroke itself is kept to be returned by the next call to bioskey that has a cmd value of zero.
2    Requests the current shift key status. The value is obtained by ORing the following values together:

Bit 7    0x80    Insert on
Bit 6    0x40    Caps on
Bit 5    0x20    Num Lock on
Bit 4    0x10    Scroll Lock on
Bit 3    0x08    Alt pressed
Bit 2    0x04    Ctrl pressed
Bit 1    0x02    Left arrow + Shift pressed
Bit 0    0x01    Right arrow + Shift pressed
 
Example :

/* bioskey example */

#include <stdio.h>
#include <bios.h>
#include <ctype.h>

#define RIGHT  0x01
#define LEFT   0x02
#define CTRL   0x04
#define ALT    0x08

int main(void)
{
   int key, modifiers;

   /* function 1 returns 0 until a key is pressed */
   while (bioskey(1) == 0);

   /* function 0 returns the key that is waiting */
   key = bioskey(0);

   /* use function 2 to determine if shift keys were used */
   modifiers = bioskey(2);
   if (modifiers)
   {
      printf("[");
      if (modifiers & RIGHT) printf("RIGHT");
      if (modifiers & LEFT)  printf("LEFT");
      if (modifiers & CTRL)  printf("CTRL");
      if (modifiers & ALT)   printf("ALT");
      printf("]");
   }
   /* print out the character read */
   if (isalnum(key & 0xFF))
      printf("'%c'\n", key);
   else
      printf("%#02x\n", key);
   return 0;
}

Learning C Functions : biosdisk ( Dos Only )

C Programming :
Function
:
biosdisk

Syntax

#include <bios.h>
int biosdisk(int cmd, int drive, int head, int track, int sector, int nsects, void *buffer);

Description

biosdisk uses interrupt 0x13 to issue disk operations directly to the BIOS.
drive is a number that specifies which disk drive is to be used: 0 for the first floppy disk drive, 1 for the second floppy disk drive, 2 for the third, and
so on. For hard disk drives, a drive value of 0x80 specifies the first drive, 0x81 specifies the second, 0x82 the third, and so forth.
For hard disks, the physical drive is specified, not the disk partition. If necessary, the application program must interpret the partition table
information itself.
cmd indicates the operation to perform. Depending on the value of cmd, the other parameters may or may not be needed.
Here are the possible values for cmd for the IBM PC, XT, AT, or PS/2, or any compatible system:

0    Resets disk system, forcing the drive controller to do a hard reset. All other parameters are ignored.
1    Returns the status of the last disk operation. All other parameters are ignored.
2    Reads one or more disk sectors into memory. The starting sector to read is given by head, track, and sector. The number of sectors is given
by nsects. The data is read, 512 bytes per sector, into buffer.
3    Writes one or more disk sectors from memory. The starting sector to write is given by head, track, and sector. The number of sectors is given
by nsects. The data is written, 512 bytes per sector, from buffer.
4    Verifies one or more sectors. The starting sector is given by head, track, and sector. The number of sectors is given by nsects.
5    Formats a track. The track is specified by head and track. buffer points to a table of sector headers to be written on the named track. See the
Technical Reference Manual for the IBM PC for a description of this table and the format operation.

The following cmd values are allowed only for the XT, AT, PS/2, and compatibles:

6    Formats a track and sets bad sector flags.
7    Formats the drive beginning at a specific track.
8    Returns the current drive parameters. The drive information is returned in buffer in the first 4 bytes.
9    Initializes drive-pair characteristics.
10    Does a long read, which reads 512 plus 4 extra bytes per sector.
11    Does a long write, which writes 512 plus 4 extra bytes per sector.
12    Does a disk seek.
13    Alternates disk reset.
14    Reads sector buffer.
15    Writes sector buffer.
16    Tests whether the named drive is ready.
17    Recalibrates the drive.
18    Controller RAM diagnostic.
19    Drive diagnostic.
20    Controller internal diagnostic.

biosdisk operates below the level of files on raw sectors. It can destroy file contents and directories on a hard disk.

Return Value
biosdisk returns a status byte composed of the following bits:

0x00    Operation successful.
0x01    Bad command.
0x02    Address mark not found.
0x03    Attempt to write to write-protected disk.
0x04    Sector not found.
0x05    Reset failed (hard disk).
0x06    Disk changed since last operation.
0x07    Drive parameter activity failed.
0x08    Direct memory access (DMA) overrun.
0x09    Attempt to perform DMA across 64K boundary.
0x0A    Bad sector detected.
0x0B    Bad track detected.
0x0C    Unsupported track.
0x10    Bad CRC/ECC on disk read.
0x11    CRC/ECC corrected data error.
0x20    Controller has failed.
0x40    Seek operation failed.
0x80    Attachment failed to respond.
0xAA    Drive not ready (hard disk only).
0xBB    Undefined error occurred (hard disk only).
0xCC    Write fault occurred.
0xE0    Status error.
0xFF    Sense operation failed.
0x11    is not an error because the data is correct. The value is returned to give the application an opportunity to decide for itself.

Example :
/*  biosdisk example  */

#include <bios.h>
#include <stdio.h>

int main(void)
{
   #define CMD    2    /*  read sector command */
   #define DRIVE  0    /*  drive number for A: */
   #define HEAD   0    /*  disk head number */
   #define TRACK  1    /*  track number */
   #define SECT   1    /*  sector number */
   #define NSECT  1    /*  sector count */

   int result;
   char buffer[512];
   printf("Attempting to read from drive A:\n");
   result = biosdisk(CMD, DRIVE, HEAD, TRACK, SECT, NSECT, buffer);
   if (result == 0)
      printf("Disk read from A: successful.\n");
   else
      printf("Attempt to read from drive A: failed.\n");
   return 0;
}

Learning C Functions :bioscom ( Dos Only )

C Programming :
Function :
bioscom

Syntax

#include <bios.h>
int bioscom(int cmd, char abyte, int port);

Description

bioscom performs various RS-232 communications over the I/O port given in port.
A port value of 0 corresponds to COM1, 1 corresponds to COM2, and so forth.
The value of cmd can be one of the following:

Value    Meaning

0    Sets the communications parameters to the value in abyte.
1    Sends the character in abyte out over the communications line.
2    Receives a character from the communications line.
3    Returns the current status of the communications port.



abyte is a combination of the following bits (one value is selected from each of the groups):

0x02    7 data bits    0x00    110 baud
0x03    8 data bits    0x20    150 baud
        0x40    300 baud
0x00    1 stop bit    0x60    600 baud
0x04    2 stop bits    0x80     1200 baud
0x00    No parity    0xA0    2400 baud
0x08    Odd parity    0xC0     4800 baud
0x18    Even parity    0xE0     9600 baud

For example, a value of 0xEB (0xE0|0x08|0x00|0x03) for abyte sets the communications port to 9600 baud, odd parity, 1 stop bit, and 8 data bits.
bioscom uses the BIOS 0x14 interrupt.

Return Value

For all values of cmd, bioscom returns a 16-bit integer, of which the upper 8 bits are status bits and the lower 8 bits vary, depending on the value of
cmd. The upper bits of the return value are defined as follows:

Bit 15    Time out
Bit 14    Transmit shift register empty
Bit 13    Transmit holding register empty
Bit 12    Break detect
Bit 11    Framing error
Bit 10    Parity error
Bit 9    Overrun error
Bit 8    Data ready

If the abyte value could not be sent, bit 15 is set to 1. Otherwise, the remaining upper and lower bits are appropriately set. For example, if a framing
error has occurred, bit 11 is set to 1.
With a cmd value of 2, the byte read is in the lower bits of the return value if there is no error. If an error occurs, at least one of the upper bits is set
to 1. If no upper bits are set to 1, the byte was received without error.
With a cmd value of 0 or 3, the return value has the upper bits set as defined, and the lower bits are defined as follows:

Bit 7    Received line signal detect
Bit 6    Ring indicator
Bit 5    Data set ready
Bit 4    Clear to send
Bit 3    Change in receive line signal detector
Bit 2    Trailing edge ring detector
Bit 1    Change in data set ready
Bit 0    Change in clear to send



Learning C Functions :_bios_serialcom ( Dos Only )

C Programming :
Function :
_bios_serialcom

Syntax

#include <bios.h>
unsigned _bios_serialcom(int cmd, int port, char abyte);

Description

_bios_serialcom performs various RS-232 communications over the I/O port given in port.
A port value of 0 corresponds to COM1, 1 corresponds to COM2, and so forth.
The value of cmd can be one of the following values (defined in bios.h):

_COM_INIT    Sets the communications parameters to the value in abyte.
_COM_SEND    Sends the character in abyte out over the communications line.
_COM_RECEIVE    Receives a character from the communications line. The abyte argument is ignored.
_COM_STATUS    Returns the current status of the communications port. The abyte argument is ignored.

When cmd is _COM_INIT, abyte is a OR combination of the following bits:
Select only one of these:

_COM_CHR7    7 data bits
_COM_CHR8    8 data bits

Select only one of these:

_COM_STOP1    1 stop bit
_COM_STOP2    2 stop bits

Select only one of these:

_COM_NOPARITY    No parity
_COM_ODDPARITY    Odd parity
_COM_EVENPARITY     Even parity

Select only one of these:

_COM_110    110 baud
_COM_150    150 baud
_COM_300    300 baud
_COM_600    600 baud
_COM_1200    1200 baud
_COM_2400    2400 baud
_COM_4800    4800 baud
_COM_9600    9600 baud

For example, a value of ( _COM_9600 | _COM_ODDPARITY | _COM_STOP1 |_COM_CHR8 ) for abyte sets thecommunicationsportto9600
baud,oddparity,1 stop bit, and 8 data bits. _bios_serialcom uses the BIOS 0x14 interrupt.
For all values of cmd, _bios_serialcom returns a 16-bit integer of which the upper 8 bits are status bits and the lower 8 bits vary, depending on the
value of cmd. The upper bits of the return value are defined as follows:

Bit 15    Time out
Bit 14    Transmit shift register empty
Bit 13    Transmit holding register empty
Bit 12    Break detect
Bit 11    Framing error
Bit 10    Parity error
Bit    9 Overrun error
Bit    8 Data ready

If the abyte value could not be sent, bit 15 is set to 1. Otherwise, the remaining upper and lower bits are appropriately set. For example, if a framing
error has occurred, bit 11 is set to 1.
 With a cmd value of _COM_RECEIVE, the byte read is in the lower bits of the return value if there is no error. If an error occurs, at least one of the
upper bits is set to 1. If no upper bits are set to 1, the byte was received without error. With a cmd value of _COM_INIT or COM_STATUS, the return
value has the upper bits set as defined, and the lower bits are defined as follows:

Bit 7    Received line signal detect
Bit 6    Ring indicator
Bit 5    Data set ready
Bit 4    Clear to send
Bit 3    Change in receive line signal detector
Bit 2    Trailing edge ring detector
Bit 1    Change in data set ready
Bit 0    Change in clear to send





Example :

/* _bios_serialcom example (for COM1)  */

/*
     This example can be used to communicate between
     two PCs via a null modem cable.
     This example is specific to COM1. 
*/
#include  <bios.h>
#include  <conio.h>
#include  <dos.h>

#define DTR         0x01    // Data Terminal Ready
#define RTS         0x02    // Ready To Send       
#define COM1PORT    0x0000  // Pointer to Location of COM1 port
#define COM2PORT    0x0002  // Pointer to Location of COM2 port
#define COM1        0
#define COM2        1
#define DATA_READY  0x100
#define FALSE       0
#define TRUE        !FALSE

#define SETTINGS ( 0xE0 | 0x00 | 0x02 | 0x00)  // 9600,N,7,1

int main( void )
{
  int in,
    out,
    status,
    DONE    = FALSE,
    far *RS232_Addr;

  /*   Determine port location of COM1.
    0x40:0x00 = COM1 I/O port address
    0x40:0x02 = COM2 I/O port address
 */
  RS232_Addr = MK_FP( 0x0040, COM1PORT );
  if( !*RS232_Addr )
   return -1;

  _bios_serialcom( 0, COM1, SETTINGS );
  cprintf( "... BIOSCOM [ESC] to exit ...\n" );

  while( !DONE )
  {
   /*  Reset DTR and RTS to prepare for send/receive of  next character */
   outportb( *RS232_Addr + 4, DTR | RTS );

   /*  Get status of com port */
   status =  _bios_serialcom( 3, COM1, 0 );

   if( status & DATA_READY )

    /*  There's a character on the port.  Get it and echo. */
   if(( out =_bios_serialcom( 2, COM1, 0 ) & 0x7F) != 0)
      putch( out );

   if( kbhit() )

    /*  Key has been struck.  Get it and send to port */
   if( (in = getch()) == '\x1B' )

      /* User pressed ESCAPE.  Don't send to port  */
      DONE = TRUE;

    else

      /*  Send character to com port. */
    _bios_serialcom( 1, COM1, in );
  }
  return 0;
}

Learning C Functions : _bios_printer ( Dos Only )

C Programming :
Function :
_bios_printer

Syntax

#include <bios.h>
unsigned _bios_printer(int cmd, int port, int abyte);

Description

_bios_printer performs various printer functions on the printer identified by the parameter port using BIOS interrupt 0x17.
A port value of 0 corresponds to LPT1; a port value of 1 corresponds to LPT2; and so on.
The value of cmd can be one of the following values (defined in bios.h):

_PRINTER_WRITE    Prints the character in abyte. The value of abyte can be 0 to 255.
_PRINTER_INIT    Initializes the printer port. The abyte argument is ignored.
_PRINTER_STATUS    Reads the printer status. The abyte argument is ignored.

Return Value

The value returned from any of these operations is the current printer status, which is obtained by ORing these bit values together:

Bit 0    0x01    Device time out
Bit 3    0x08     I/O error
Bit 4    0x10     Selected
Bit 5    0x20     Out of paper
Bit 6    0x40     Acknowledge
Bit 7    0x80     Not busy

Example :
 
/* _bios_printer example */

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

int main(void)
{
   unsigned PortNum = 0x1;  /* LPT1 -> 0, LPT2 -> 1 */
  unsigned status, abyte = 0;
  printf("Please turn off your printer.\n\
        Press any key to continue\n");
  getch();
  status = _bios_printer(_PRINTER_STATUS, PortNum, abyte);
   if (status & 0x01)
      printf("Device time out.\n");
   if (status & 0x08)
      printf("I/O error.\n");
   if (status & 0x10)
      printf("Selected.\n");
   if (status & 0x20)
      printf("Out of paper.\n");
   if (status & 0x40)
      printf("Acknowledge.\n");
   if (status & 0x80)
      printf("Not busy.\n");
   return 0;
}

Learning C Functions :_bios_keybrd ( Dos Only )

C Programming :
Function :
_bios_keybrd

Syntax

#include <bios.h>
unsigned _bios_keybrd(unsigned cmd);

Description


_bios_keybrd performs various keyboard operations using BIOS interrupt 0x16. The parameter cmd determines the exact operation .

Return Value

The value returned by _bios_keybrd depends on the task it performs, determined by the value of cmd (defined in bios.h):

_KEYBRD_READ    If the lower 8 bits are nonzero, _bios_keybrd returns the ASCII character for the next keystroke waiting in the queue
or the next key pressed at the keyboard. If the lower 8 bits are zero, the upper 8 bits are the extended keyboard codes defined in the IBM PC Technical Reference Manual.
_NKEYBRD_READ    Use this value instead of _KEYBRD_READY to read the keyboard codes for enhanced keyboards, which have additional cursor and function keys.
_KEYBRD_READY    This tests whether a keystroke is available to be read. A return value of zero means no key is available. The return value is 0xFFFF (-1) if Ctrl-Brk has been pressed. Otherwise, the value of the next keystroke is returned, as described in _KEYBRD_READ (above). The keystroke itself is kept to be returned by the next call to _bios_keybrd
that has a cmd value of _KEYBRD_READ or _NKEYBRD_READ   
_NKEYBRD_READY    Use this value to check the status of enhanced keyboards, which have additional cursor and function keys.

_KEYBRD_SHIFTSTATUS    Requests the current shift key status. The value will contain an OR of zero or more of the following values:

     Bit 7    0x80    Insert on
     Bit 6    0x40    Caps on
     Bit 5    0x20    Num Lock on
     Bit 4    0x10    Scroll Lock on
     Bit 3    0x08    Alt pressed
     Bit 2    0x04    Ctrl pressed
     Bit 1    0x02    Left Shift pressed
     Bit 0    0x01    Right Shift pressed

_NKEYBRD_SHIFTSTATUS    Use this value instead of _KEYBRD_SHIFTSTATUS to request the full 16-bit shift key status for enhanced
keyboards. The return value will contain an OR of zero or more of the bits defined above in
_KEYBRD_SHIFTSTATUS, and additionally, any of the following bits:

     Bit 15    0x8000    Sys Req pressed
     Bit 14    0x4000    Caps Lock pressed
     Bit 13    0x2000    Num Lock pressed
     Bit 12    0x1000    Scroll Lock pressed
     Bit 11    0x0800    Right Alt pressed
     Bit 10    0x0400    Right Ctrl pressed
     Bit 9    0x0200    Left Alt pressed
     Bit 8    0x0100    Left Ctrl pressed

Example :

/*  _bios_keybrd example  */

#include <stdio.h>
#include <bios.h>
#include <ctype.h>

#define RIGHT  0x01
#define LEFT   0x02
#define CTRL   0x04
#define ALT    0x08

int main(void)
{
   int key, modifiers;

   /*  Wait until a key is pressed  */
   while (_bios_keybrd(_KEYBRD_READY) == 0);

   /*  Fetch the key that is waiting  */
   key = _bios_keybrd(_KEYBRD_READ);

   /*  Determine if shift keys are used  */
   modifiers = _bios_keybrd(_KEYBRD_SHIFTSTATUS);
   if (modifiers){
      printf("[");
      if (modifiers & RIGHT) printf("RIGHT");
      if (modifiers & LEFT)  printf("LEFT");
      if (modifiers & CTRL)  printf("CTRL");
      if (modifiers & ALT)   printf("ALT");
      printf("]");
   }

   /*  print out the character read  */
   if (isalnum(key & 0xFF))
      printf("'%c'\n", key);
   else
      printf("%#02x\n", key);
   return 0;
}

Learning C Functions :_bios_disk ( Dos Only )

C Programming :
Function :
_bios_disk

Syntax :

#include <bios.h>
unsigned _bios_disk(unsigned cmd, struct diskinfo_t *dinfo);

Description :

_bios_disk uses interrupt 0x13 to issue disk operations directly to the BIOS . The cmd argument specifies the operation to perform, and dinfo points
to a diskinfo_t structure that contains the remaining parameters required by the operation .
The diskinfo_t structure (defined in bios.h) has the following format :

struct diskinfo_t {
    unsigned drive, head, track, sector, nsectors;
    void far *buffer;
};

drive is a number that specifies which disk drive is to be used: 0 for the first floppy disk drive, 1 for the second floppy disk drive, 2 for the third, and
so on. For hard disk drives, a drive value of 0x80 specifies the first drive, 0x81 specifies the second, 0x82 the third, and so forth.
For hard disks, the physical drive is specified, not the disk partition. If necessary, the application program must interpret the partition table
information itself.
Depending on the value of cmd, the other parameters in the diskinfo_t structure may or may not be needed.
The possible values for cmd (defined in bios.h) are the following :

_DISK_RESET    Resets disk system, forcing the drive controller to do a hard reset. All diskinfo_t parameters are ignored .
_DISK_STATUS    Returns the status of the last disk operation. All diskinfo_t parameters are ignored.
_DISK_READ    Reads one or more disk sectors into memory. The starting sector to read is given by head, track, and sector. The number of
sectors is given by nsectors. The data is read, 512 bytes per sector, into buffer. If the operation is successful, the high byte of
the return value will be 0 and the low byte will contain the number of sectors. If an error occurred , the high byte of the return
value will have one of the following values :

     0x01    Bad command .
     0x02    Address mark not found .
     0x03    Attempt to write to write-protected disk .
     0x04    Sector not found .
     0x05    Reset failed (hard disk) .
     0x06    Disk changed since last operation .
     0x07    Drive parameter activity failed .
     0x08    Direct memory access (DMA) overrun .
     0x09    Attempt to perform DMA across 64K boundary .
     0x0A    Bad sector detected .
     0x0B    Bad track detected .
     0x0C    Unsupported track .
     0x10    Bad CRC/ECC on disk read .
     0x11    CRC/ECC corrected data error .
     0x20    Controller has failed .
     0x40    Seek operation failed .
     0x80    Attachment failed to respond .
     0xAA    Drive not ready (hard disk only).
     0xBB    Undefined error occurred (hard disk only).
     0xCC    Write fault occurred .
     0xE0    Status error .
     0xFF    Sense operation failed .
     0x11    is not an error because the data is correct. The value is returned to give the application an opportunity to decide for tself .

_DISK_WRITE    Writes one or more disk sectors from memory. The starting sector to write is given by head, track, and sector . The number of
sectors is given by  nsectors . The data is written, 512 bytes per sector, from buffer. See _DISK_READ (above) for a description of the return value.
_DISK_VERIFY    Verifies one or more sectors. The starting sector is given by head, track, and sector. The number of sectors is given by nsectors.
See _DISK_READ (above) for a description of the return value.
_DISK_FORMAT    Formats a track. The track is specified by head and track. buffer points to a table of sector headers to be written on the named track. See the Technical Reference Manual for the IBM PC for a description of this table and the format operation.

Return Value

_bios_disk returns the value of the AX register set by the INT 0x13 BIOS call.


Example :

/*  _bios_disk example  */

#include <bios.h>
#include <stdio.h>

int main(void)
{
  struct diskinfo_t dinfo;
  int result;
  static char dbuf[512];

  dinfo.drive =  0;        /*  drive number for A: */
  dinfo.head  =  0;       /*  disk head number */
  dinfo.track =  0;        /*  track number */
  dinfo.sector  =  1;     /*  sector number */
  dinfo.nsectors =  1;   /*  sector count */
  dinfo.buffer = dbuf;  /*  data buffer */

  printf("Attempting to read from drive A:\n");
  result = _bios_disk(_DISK_READ, &dinfo);
  if ((result & 0xff00) == 0)
  {
    printf("Disk read from A: successful.\n");
    printf("First three bytes read are 0x%02x 0x%02x 0x%02x\n",
      dbuf[0] & 0xff, dbuf[1] & 0xff, dbuf[2] & 0xff);
  }
  else
    printf("Cannot read drive A, status = 0x%02x\n", result);

  return 0;
}

Learning C Functions : allocmem, _dos_allocmem ( Dos Only )

C Programming :
Function :
allocmem, _dos_allocmem

Syntax :

#include <dos.h>
int allocmem(unsigned size, unsigned *segp);
unsigned _dos_allocmem(unsigned size, unsigned *segp);

Description :

allocmem and _dos_allocmem use the DOS system call 0x48 to allocate a block of free memory and return the segment address of the allocated block .
size is the desired size in paragraphs (a paragraph is 16 bytes). segp is a pointer to a word that will be assigned the segment address of the newly
allocated block .
For allocmem, if not enough room is available, no assignment is made to the word pointed to by segp.
For _dos_allocmem, if not enough room is available, the size of the largest available block will be stored in the word pointed to by segp.
All allocated blocks are paragraph-aligned.
allocmem and _dos_allocmem cannot coexist with malloc.

Return Value:

allocmem returns -1 on success. In the event of error, allocmem returns a number indicating the size in paragraphs of the largest available block.
_dos_allocmem returns 0 on success. In the event of error, _dos_allocmem returns the DOS error code and sets the word pointed to by segp to the
size in paragraphs of the largest available block.
An error return from allocmem or _dos_allocmem sets the global variable _doserrno and sets the global variable errno to:

ENOMEM    Not enough memory

 Example :





/*   _dos_allocmem example    */

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

int main(void)
{
  unsigned int size, segp, err, maxb;
  size = 64; /* (64 x 16) = 1024 bytes */
  err = _dos_allocmem(size, &segp);
  if (err == 0)
    printf("Allocated memory at segment: %x\n", segp);
  else {
    perror("Unable to allocate block ");
    printf("Maximum no. of paragraphs available is %u\n", segp);
    return 1;
  }
  if (_dos_setblock(size * 2, segp, &maxb) == 0)
    printf(" Expanded memory block at segment: %X\n", segp);
  else {
    perror("Unable to expand block ");
    printf("Maximum no. of paragraphs  available is %u\n", maxb);
  }
  _dos_freemem(segp);
  return 0;
}

Learning C Functions :abswrite ( Dos Only )

C Programming :
Function : abswrite


Syntax :

#include <dos.h>
int abswrite(int drive, int nsects, long lsect, void *buffer);

Description :

abswrite writes specific disk sectors. It ignores the logical structure of a disk and pays no attention to files, FATs, or directories .
If used improperly , abswrite can overwrite files, directories, and FATs .
abswrite uses DOS interrupt 0x26 to write specific disk sectors .

drive    drive number to write to (0 = A, 1 = B, etc.)
nsects    number of sectors to write to
lsect    beginning logical sector number
buffer    memory address where the data is to be written

The number of sectors to write to is limited to 64K or the size of the buffer, whichever is smaller .

Return Value :
If it is successful, abswrite returns 0 .
On error, the routine returns -1 and sets the global variable errno to the value of the AX register returned by the system call .

Wednesday, February 18, 2015

Learning C Functions : absread ( Dos Only )


C Programming :
Function : absread 

Syntax :
 #include <dos.h>
int absread(int drive, int nsects, long lsect, void *buffer);

Description :
 absread reads specific disk sectors. It ignores the logical structure of a disk and pays no attention to files , FATs, or directories .
absread uses DOS interrupt 0x25 to read specific disk sectors.

drive      drive number to read (0 = A, 1 = B, etc.)
nsects   number of sectors to read
lsect       beginning logical sector number
buffer   memory address where the data is to be read

The number of sectors to read is limited to 64K or the size of the buffer, whichever is smaller .
Return Value
If it is successful, absread returns 0 .

Example :

On error, the routine returns -1 and sets the global variable errno to the value returned by the system call in the AX register.
/*  absread example  */

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

#define SECSIZE 512

int main(void)
{
   unsigned char buf[SECSIZE];
   int i, j, sector, drive;
   char str[10];
   printf("Enter drive letter: ");
   gets(str);
   drive = toupper(str[0]) - 'A';
   printf("Enter sector number to read: ");
   gets(str);
   sector = atoi(str);
   if (absread(drive, 1, sector, &buf) != 0) {
       perror("Disk error");
       exit(1);
   }
   printf("\nDrive: %c   Sector: %d\n", 'A' + drive, sector);
   for (i = 0; i < SECSIZE; i += 16) {
      if ((i / 16) == 20) {
         printf("Press any key to continue...");
         getch();
         printf("\n");

      }
      printf("%03d: ", i);
      for (j = 0; j < 16; j++)
         printf("%02X ", buf[i+j]);
      printf("\t");
      for (j = 0; j < 16; j++)
         if (isprint(buf[i+j]))
            printf("%c", buf[i+j]);
         else printf(".");
      printf("\n");
   }
   return 0;
}

Tuesday, February 17, 2015

How does your WebCam / CCD work ?

Principle of WebCam
A WebCam is a compact digital camera you can hook up to your computer to broadcast video images in real time process ( as they happen ) . Just like a digital camera , it captures light through a small lens at the front using a tiny grid of light-detectors , known as a charge-coupled device / CCD . As we shall see in a moment , the CCD (charge-coupled devices) converts the picture in front of the camera into digital format — a string of zeros and ones ( Binary Digits ) that a computer knows how to handle . Unlike a digital camera , a webcam has no built-in memory chip or memory card : it doesn't need to "remember" pictures because it is designed to capture and transmit them immediately to a computer or Laptop .

 Principle of a WebCam / CCD (charge-coupled devices) :

After removing outer case of a webcam you'll find it's little more than a plastic lens mounted directly onto a tiny electronic circuit board underneath . The lens screws in and out to increase its focal length , controlling the focus of your WebCam :
 
After Removing Case
 Now taking the lens off and you can see the light sensitive CCD chip , which is head of your webcam : it's the square thing in the middle of this circuit. Only the little , central part is light - sensitive : the rest of the CCD chip is concerned with connecting the light detector to the bigger circuit that surrounds it :

Micro Chip

How does a CCD convert an image to digital form?


When you capture a digital photo or stare into your webcam , light zooms into the cam lens . This incoming "picture" hits the CCD , which breaks it up into individual pixels . The CCD measures how much light is hitting at each pixel . This information is turned into a number that can be stored on a memory chip inside the camera . Thus , taking a digital photograph converts the picture you see into a very long string of binary numbers . Each number describes one pixel in the image - how bright or dark and which color it is .

Steps :

  1. Light from the object (in this case ,here is a bicycle) enters in the camera lens .
  2. The CCD inside the camera splits the image up into millions of pixels (squares). An LCD(Liquid Cristal Display) display on the back of the camera shows you a image that the CCD is capturing -- not an image of the object seen through a series of lenses ( as with a conventional camera ) , but a redrawn , computerized version of the original object displayed on a screen .
  3. The CCD measures the color and brightness of each pixel .
  4. The color and brightness are stored as binary numbers , patterns of zeros and ones , in the camera's flash memory card . When you connect your camera to a computer , these numbers are transmitted instantly down the wire . 

 The CCD was invented in the year 1969 by Canadian-born Willard S. Boyle  and American George E. Smith , two colleagues working at Bell Laboratories.

The scientific theory behind the CCD (turning light energy into electrical energy) dates back much further - to 1905. Known as the photoelectric effect , it was the first major scientific discovery by Albert Einstein .

Camcorders :

What is Camcorders ?
Camcorders

What is Camcorders

When video recording was invented , photographic film was replaced by the magnetic videotape , which was simpler , cheaper , and needed no photographic developing before you could view the things you would recorded . Modern electronic Camcorders use digital video
Instead of recording photographic images , they use a light sensitive microchip called a charge-coupled device (CCD) to convert what the lens sees into digital (numerical) format . In other words , each frame is not stored as a photograph , but as a long string of numbers . So a movie recorded with a digital camcorder is a series of frames , each stored in the form of some numbers . In some camcorders , the digital information is recorded onto videotape ; in others , you record onto a DVD/CD ; and in still others, you record onto a hard drive or flash memory , Called USB . The advantage of storing movies in digital format is that you can edit them on your computer or Laptop ,  upload them onto web sites , and view them on all kinds of different devices (by converting from cellphones and MP3 players to computers and tv). 
Try doing that with a silent movie from the 20th Century !