home *** CD-ROM | disk | FTP | other *** search
Text File | 2013-11-08 | 6.2 MB | 214,544 lines |
Text Truncated. Only the first 1MB is shown below. Download the file for the complete contents.
- Microsoft C Optimizing Compiler - v6.0
-
-
- CHRTDEMO.C
- CD-ROM Disc Path: \SAMPCODE\C\MSC60\CHRTDEMO.C
-
- #include <stdlib.h>
- #include <stdio.h>
- #include <conio.h>
- #include <string.h>
- #include <graph.h>
- #include <pgchart.h>
- #include "chrtdemo.h"
-
- /* Structures for system configuration and chart environment. */
- struct videoconfig vc;
- chartenv ce;
-
- /* Category variables. */
- short cCat;
- char _far *aCat[MAXVALUES];
-
- /* Series variables. */
- short cSeries;
- short _far acSeries[MAXSERIES];
- char _far *aSeriesName[MAXSERIES];
-
- /* Temporary holding array for all data. Data values for multi-series
- * bar, column, and line charts remain here. Data for other kinds of
- * charts are transferred to the arrays below.
- */
- float _far aValue[MAXSERIES][MAXVALUES];
-
- /* Data values for single-series charts. First array is used for
- * bar, column, line, and pie. First and second are both used for
- * single-series scatter.
- */
- float _far axValue[MAXVALUES];
- float _far ayValue[MAXVALUES];
-
- /* Data values for multi-series scatter charts. */
- float _far axValueMS[MAXVALUES][MAXVALUES];
- float _far ayValueMS[MAXVALUES][MAXVALUES];
-
- /* Exploded flags for pie chart. */
- short _far aExplode[MAXVALUES];
-
- /* Variable used to track control and screen position. */
- struct SCREENINFO si;
-
- /* Colors of menus and prompts. */
- struct tagColor co;
-
- /* Flags to indicate whether to use imported or default data. */
- BOOL fDefault = TRUE;
-
- /* Arrays of strings used by the Menu function. The first string is the
- * menu title. The next non-null strings are the menu selections. A null
- * string indicates the end of the list.
- */
- char *pszChartOpt[] =
- { "Options", "Screen Mode", "Windows", "Titles",
- "Axis (X and Y)", "Legend", "Fonts", "Reset", "" };
-
- char *pszChartType[] =
- { "Type", "Bar", "Column", "Line", "Scatter", "Pie", "" };
-
- char *pszMainMenu[] =
- { "Main Menu", "Demo", "View Chart", "Chart Type", "Options",
- "Show Chart Data", "Quit", "" };
-
- /* Sample data. */
- #define O_JUICE 0
- #define I_TEA 1
- #define H_CHOC 2
- #define TEMPERATURE 3
-
- char _far *aQuarters[] =
- { "First", "Second", "Third", "Fourth" };
-
- char _far *aMonths[] =
- { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
-
- float _far aSales[3][12] =
- {
- { 3.6F, 3.2F, 3.3F, 3.4F, 3.1F, 2.9F,
- 3.0F, 3.6F, 3.2F, 3.3F, 3.5F, 3.9F },
- { 1.0F, 1.3F, 1.4F, 1.7F, 2.2F, 2.9F,
- 2.9F, 3.1F, 2.6F, 1.8F, 1.1F, 1.2F },
- { 2.4F, 2.3F, 2.0F, 1.6F, 1.3F, 1.0F,
- 0.9F, 0.8F, 1.1F, 1.4F, 1.9F, 2.5F }
- };
-
- float _far aTemperature[12] =
- { 2.9F, 3.2F, 3.9F, 4.8F, 6.0F, 6.5F,
- 7.0F, 7.2F, 6.0F, 4.7F, 4.1F, 3.0F };
-
- char _far *aSalesTitles[] =
- { "Orange Juice Sales", "Iced Tea Sales", "Hot Chocolate Sales" };
-
- char *TempTitle = "Average Temperature";
-
- int main()
- {
- Initialize();
- MainMenu();
-
- /* Reset the video mode and screen colors prior to leaving. */
- _setvideomode( _DEFAULTMODE );
- _settextcolor( co.InfoColor );
- _clearscreen( _GCLEARSCREEN );
-
- return 0;
- }
-
- /* ChartOptions - Gets chart options.
- *
- * Params: None
- */
- void ChartOptions()
- {
- int iChoice;
-
- PushTitle( pszChartOpt[0] );
- while( (iChoice = Menu( pszChartOpt )) != ESCAPE )
- {
-
- /* Get chart options. */
- switch( iChoice )
- {
-
- /* Branch to the appropriate menu. */
- case 1:
- ScreenMode();
- break;
-
- case 2:
- Windows();
- break;
-
- case 3:
- Titles();
- break;
-
- case 4:
- Axes();
- break;
-
- case 5:
- Legend();
- break;
-
- case 6:
- FontOptions();
- break;
-
- case 7:
- ResetOptions();
- break;
-
- }
- }
- PopTitle();
- }
-
- /* ChartType - Gets chart type.
- *
- * Params: None
- */
- void ChartType()
- {
- int iChoice;
-
- /* Get chart type. */
- PushTitle( pszChartType[0] );
- iChoice = Menu( pszChartType );
-
- if( iChoice != ESCAPE )
- {
- /* Set the chart type, and get the chart style. */
- ce.charttype = iChoice;
- switch( iChoice )
- {
-
- case 1:
- case 2:
- iChoice = BlankMenu( "Style", "Plain Bars", "Stacked Bars" );
- break;
-
- case 3:
- case 4:
- iChoice = BlankMenu( "Style", "Lines-Points", "Points Only" )
- break;
-
- case 5:
- iChoice = BlankMenu( "Style", "Percent", "No Percent" );
- }
-
- if( iChoice != ESCAPE)
- ce.chartstyle = iChoice;
-
- /* Set default data without changing environment defaults. */
- DefaultData( ce.charttype, ce.chartstyle, FALSE );
- PopTitle();
- }
- PopTitle();
- }
-
- /* ClearData - Clears category and value data.
- *
- * Params: fConfirm - flag specifying whether to query for confirmation
- */
- void ClearData( BOOL fConfirm )
- {
- char chResponse = 'Y';
- int iCat;
-
- WrtForm( 18 );
-
- /* Query for confirmation. */
- if( fConfirm )
- chResponse = InputCh( "Are you sure? ", "YN\x1b" );
-
- if( chResponse == 'Y' )
- {
-
- /* Clear all relevant data. */
- for( iCat = 0; iCat < cCat; iCat++ )
- aCat[iCat] = NULL;
- cCat = 0;
- cSeries = 0;
- }
- }
-
- /* DefaultData - Initializes default data for each kind of chart.
- *
- * Params: iType - Chart type to be initialized
- * iStyle - Chart style
- * fClear - Signal to clear all defaults
- */
- void DefaultData( short iType, short iStyle, BOOL fClear )
- {
- int iCat, iValue, iSubValue, iSeries;
-
- /* Call default chart to clear old values. */
- if( fClear )
- _pg_defaultchart( &ce, iType, iStyle );
-
- /* Initialize category titles. */
- cCat = 12;
- for( iCat = 0; iCat < cCat; iCat++ )
- aCat[iCat] = aMonths[iCat];
-
- switch( ce.charttype )
- {
-
- /* Initialize data for each chart type. */
- case _PG_BARCHART:
-
- strcpy( ce.maintitle.title, "Orange Juice and Iced Tea Sales" );
- cSeries = 2;
- for( iSeries = 0; iSeries < cSeries; iSeries++ )
- {
- aSeriesName[iSeries] = aSalesTitles[iSeries];
- acSeries[iSeries] = cCat;
- for( iValue = 0; iValue < cCat; iValue++ )
- aValue[iSeries][iValue] = (float)aSales[iSeries][iValue]
- }
- break;
-
- case _PG_COLUMNCHART:
-
- strcpy( ce.maintitle.title, "Orange Juice Sales" );
- cSeries = 1;
- for( iSeries = 0; iSeries < cSeries; iSeries++ )
- {
- aSeriesName[iSeries] = aSalesTitles[iSeries];
- acSeries[iSeries] = cCat;
- for( iValue = 0; iValue < cCat; iValue++ )
- aValue[iSeries][iValue] = (float)aSales[iSeries][iValue]
- }
- break;
-
- case _PG_LINECHART:
-
- strcpy( ce.maintitle.title, "Beverage Sales" );
- cSeries = 3;
- for( iSeries = 0; iSeries < cSeries; iSeries++ )
- {
- aSeriesName[iSeries] = aSalesTitles[iSeries];
- acSeries[iSeries] = cCat;
- for( iValue = 0; iValue < cCat; iValue++ )
- aValue[iSeries][iValue] = (float)aSales[iSeries][iValue];
- }
- break;
-
- case _PG_SCATTERCHART:
-
- strcpy( ce.maintitle.title,
- "Average Temperature Compared to Beverage Sales" );
- /* ce.chartstyle = _PG_POINTONLY; */
- cSeries = 4;
-
- aSeriesName[0] = aSalesTitles[I_TEA];
- aSeriesName[2] = aSalesTitles[H_CHOC];
- acSeries[0] = acSeries[1] = acSeries[2] = acSeries[3] = 12;
- for( iValue = 0; iValue < 12; iValue++ )
- {
- aValue[0][iValue] = (float)aSales[I_TEA][iValue] ;
- aValue[1][iValue] = (float)aSales[TEMPERATURE][iValue] ;
- aValue[2][iValue] = (float)aSales[H_CHOC][iValue] ;
- aValue[3][iValue] = (float)aSales[TEMPERATURE][iValue] ;
- }
- break;
-
- case _PG_PIECHART:
- default:
-
- strcpy( ce.maintitle.title, "Iced Tea Sales" );
- cCat = 4;
- for( iCat = 0; iCat < cCat; iCat++ )
- aCat[iCat] = aQuarters[iCat];
-
- cSeries = 1;
- aSeriesName[0] = aSalesTitles[I_TEA];
- acSeries[0] = cCat;
-
- for( iValue = 0; iValue < cCat; iValue++ )
- {
- aValue[0][iValue] = 0.0;
- for( iSubValue = 0; iSubValue < 3; iSubValue++ )
- aValue[0][iValue] += (float)aSales[I_TEA][iSubValue * iVa
- }
- aExplode[3] = 1;
- break;
- }
- }
-
- /* Demo - Displays a series of sample charts.
- *
- * Params: None
- */
- void Demo()
- {
- int cValue;
- palettetype palette_struct;
-
- /* Display the sample data in spreadsheet form. */
- ShowSampleData();
-
- DefaultData( _PG_PIECHART, _PG_NOPERCENT, TRUE );
-
- /* Set video mode and draw charts. For each chart, set default
- * data and modify any desired environment fields. If error,
- * terminate demo.
- */
- _setvideomode( si.mode );
-
- cValue = 4;
- strcpy( ce.subtitle.title, "Default Pie Chart" );
- if( ViewChart() )
- return;
- else
- _clearscreen( _GCLEARSCREEN );
-
- strcpy( ce.subtitle.title, "Customized Pie Chart" );
- ce.chartstyle = _PG_PERCENT;
- ce.legend.place = _PG_BOTTOM;
- if (si.fColor)
- {
- ce.maintitle.titlecolor = ce.subtitle.titlecolor = 0;
- ce.chartwindow.background = 1;
- ce.datawindow.background = ce.legend.legendwindow.background = 6;
- ce.legend.textcolor = 1;
- }
- if( ViewChart() )
- return;
- else
- _clearscreen( _GCLEARSCREEN );
-
- cValue = 12;
- DefaultData( _PG_BARCHART, _PG_PLAINBARS, TRUE );
- strcpy( ce.subtitle.title, "Default Bar Chart" );
- if( ViewChart() )
- return;
- else
- _clearscreen( _GCLEARSCREEN );
-
- strcpy( ce.subtitle.title, "Customized Stacked Bar Chart" );
- strcpy( ce.xaxis.axistitle.title, "Sales in Thousands" );
- strcpy( ce.yaxis.axistitle.title, "Month" );
- ce.chartstyle = _PG_STACKEDBARS;
- ce.legend.place = _PG_RIGHT;
- ce.xaxis.ticdecimals = 2;
- if (si.fColor)
- {
- ce.maintitle.titlecolor = ce.subtitle.titlecolor = 12;
- ce.chartwindow.background = 7;
- ce.datawindow.background = 8;
- ce.legend.textcolor = 0;
- ce.legend.legendwindow.background = 8;
- ce.legend.autosize = FALSE;
- ce.legend.legendwindow.y1 = vc.numypixels - 85;
- ce.legend.legendwindow.y2 = vc.numypixels - 45;
- }
- if( ViewChart() )
- return;
- else
- _clearscreen( _GCLEARSCREEN );
-
- DefaultData( _PG_COLUMNCHART, _PG_PLAINBARS, TRUE );
- strcpy( ce.subtitle.title, "Default Column Chart" );
- if( ViewChart() )
- return;
- else
- _clearscreen( _GCLEARSCREEN );
-
- strcpy( ce.subtitle.title, "Customized Column Chart" );
- strcpy( ce.xaxis.axistitle.title, "Month" );
- strcpy( ce.yaxis.axistitle.title, "Sales in Thousands" );
- ce.legend.place = _PG_BOTTOM;
- if (si.fColor)
- {
- ce.maintitle.titlecolor = 0;
- ce.subtitle.titlecolor = 0;
- ce.chartwindow.background = 8;
- ce.datawindow.background = 2;
- ce.legend.legendwindow.background = 10;
- }
- if( ViewChart() )
- return;
- else
- _clearscreen( _GCLEARSCREEN );
-
- DefaultData( _PG_LINECHART, _PG_POINTANDLINE, TRUE );
- strcpy( ce.subtitle.title, "Default Line Chart" );
- if( ViewChart() )
- return;
- else
- _clearscreen( _GCLEARSCREEN );
-
- strcpy( ce.subtitle.title, "Customized Line Chart" );
- strcpy( ce.xaxis.axistitle.title, "Month" );
- strcpy( ce.yaxis.axistitle.title, "Sales in Thousands" );
- ce.legend.place = _PG_RIGHT;
- if (si.fColor)
- {
- ce.maintitle.titlecolor = 1;
- ce.subtitle.titlecolor = 1;
- ce.chartwindow.background = 3;
- ce.datawindow.background = 7;
- ce.legend.legendwindow.background = 7;
- ce.legend.autosize = FALSE;
- ce.legend.legendwindow.y1 = vc.numypixels - 85;
- ce.legend.legendwindow.y2 = vc.numypixels - 45;
- }
- if( ViewChart() )
- return;
- else
- _clearscreen( _GCLEARSCREEN );
-
- DefaultData( _PG_SCATTERCHART, _PG_POINTONLY, TRUE );
- strcpy( ce.subtitle.title, "Default Scatter Chart" );
- if( ViewChart() )
- return;
- else
- _clearscreen( _GCLEARSCREEN );
-
- cSeries = 4;
- strcpy( ce.subtitle.title, "Customized Scatter Chart" );
- strcpy( ce.xaxis.axistitle.title, "Sales in Thousands" );
- strcpy( ce.yaxis.axistitle.title, "Average Temperature" );
- ce.legend.place = _PG_RIGHT;
- if (si.fColor)
- {
- ce.maintitle.titlecolor = 0;
- ce.subtitle.titlecolor = 0;
- ce.chartwindow.background = 4;
- ce.datawindow.background = 8;
- ce.legend.legendwindow.background = 8;
- ce.legend.autosize = FALSE;
- ce.legend.legendwindow.y1 = vc.numypixels - 85;
- ce.legend.legendwindow.y2 = vc.numypixels - 45;
- }
- if( ViewChart() )
- return;
- else
- _clearscreen( _GCLEARSCREEN );
-
- DefaultData( _PG_BARCHART, _PG_PERCENT, TRUE );
- }
-
- /* FindVideoMode - Finds the "best" video mode for the adaptor in use.
- *
- * Params: vc - structure of type struct videoconfig
- *
- * Returns: Best mode
- */
- int FindVideoMode( struct videoconfig vc )
- {
- switch( vc.adapter )
- {
- case _CGA:
- case _OCGA:
- return _HRESBW;
- case _EGA:
- case _OEGA:
- return( vc.monitor == _MONO ) ? _ERESNOCOLOR : _ERESC
- case _VGA:
- case _OVGA:
- case _MCGA:
- return _VRES16COLOR;
- case _HGC:
- return _HERCMONO;
- default:
- return _DEFAULTMODE;
- }
- }
-
- /* Initialize - Does various initialization tasks.
- *
- * Params: None
- */
- void Initialize( void )
- {
- int iSeries, iValue;
-
- /* Initialize all value arrays to missing. */
- for( iSeries = 0; iSeries < MAXSERIES; iSeries++ )
- {
-
- axValue[iSeries] = _PG_MISSINGVALUE;
- ayValue[iSeries] = _PG_MISSINGVALUE;
-
- for( iValue = 0; iValue < MAXVALUES; iValue++ )
- aValue[iSeries][iValue] = _PG_MISSINGVALUE;
-
- for( iValue = 0; iValue < MAXVALUES; iValue++ )
- {
- axValueMS[iSeries][iValue] = _PG_MISSINGVALUE;
- ayValueMS[iSeries][iValue] = _PG_MISSINGVALUE;
- }
- }
-
- /* Initialize zero sets. */
- cSeries = 0;
-
- /* Initialize default chart environment, screen mode, and data. */
- _pg_initchart();
- _getvideoconfig( &vc );
-
- /* Find the best available mode for display.
- * Don't set 256 color, medium resolution (_MRES256COLOR).
- */
- si.mode = FindVideoMode( vc );
-
- if( si.mode == _TEXTMONO )
- {
- _clearscreen( _GCLEARSCREEN );
- _outtext( "No graphics available. Can't run chart demo." );
- exit( 1 );
- }
-
- SetDisplayColors();
-
- SetGraphMode( si.mode );
- DefaultData( _PG_BARCHART, _PG_PLAINBARS, TRUE );
-
- _setvideomode( _DEFAULTMODE );
-
-
- }
-
- /* MainMenu - Manages the main menu.
- *
- * Params: None
- */
- void MainMenu( void )
- {
- int iChoice;
- char chResponse = 'Y';
- char chVerify;
-
- PushTitle( pszMainMenu[0] );
- do
- {
- /* If the user selects Quit, iChoice will contain 6. If the
- * user presses ESCAPE, iChoice will be ESCAPE, which is
- * equal to 27. In any case, we can test both conditions
- * by checking to see whether iChoice is less than 6.
- */
- while( (iChoice = Menu( pszMainMenu )) < 6 )
- {
- /* Get main menu selection. */
- switch( iChoice )
- {
-
- case 1:
- /* Display demo charts. */
- Demo();
- _setvideomode( _DEFAULTMODE );
- break;
-
- case 2:
- /* Set graphics video mode, display current chart,
- * and restore text video mode.
- */
- _setvideomode( si.mode );
- ViewChart();
- _setvideomode( _DEFAULTMODE );
- break;
-
- case 3:
- /* Get chart type and style. */
- ChartType();
- break;
-
- case 4:
- /* Get chart options. */
- ChartOptions();
- break;
- case 5:
- /* Show chart data. */
- ShowChartData();
- break;
-
- }
-
- }
-
- /* If the user is trying to leave the program using the ESCAPE
- * key, we must verify the choice. This is done to prevent
- * an eager typist from pressing ESCAPE one time too often
- * and exiting at an unanticipated point.
- */
- if( iChoice == ESCAPE )
- {
- Help( "Press \"Q\" to Actually Quit", co.InputColor );
-
- putchar( BEEP );
- _settextposition( si.help - 1, 32 );
- chVerify = getch();
- if( tolower( chVerify ) != 'q' )
- iChoice = 0;
- else
- iChoice = 6;
- }
-
- } while( iChoice != 6 );
- PopTitle();
- }
-
- /* ResetOptions - After confirmation, resets chart options to default.
- *
- * Params: None
- */
- void ResetOptions()
- {
- char chResponse;
-
- /* Prompt for confirmation before setting default environment. */
- ClrForm();
- Help( "Type 'Y' to reset all options, 'N' to keep them.", co.InputColor
- chResponse = InputCh( "Are you sure? ", "YN\x1b" );
- if( chResponse == 'Y' )
- _pg_defaultchart( &ce, 1, 1 );
-
- }
-
- /* SetGraphMode - Tests the specified graphics mode and sets the xMax
- * and yMax values in the si (Screen Information) structure.
- *
- * Params: mode number
- *
- * Return: FALSE if mode invalid, TRUE if valid
- */
- BOOL SetGraphMode(int mode)
- {
- if (!_setvideomode( mode ) )
- return FALSE;
- else
- {
- _getvideoconfig ( &vc );
- if( !vc.numxpixels )
- return FALSE;
- si.xMax = vc.numxpixels;
- si.yMax = vc.numypixels;
- si.mode = mode;
-
- /* Set flag to indicate whether multiple colors are available. */
- si.fColor = iscolor( mode );
-
- return TRUE;
- }
- }
-
- /* ShowChartData - Displays the data in the chart environment.
- *
- * Params: None
- */
- void ShowChartData()
- {
- int iRow = 2;
- struct _fontinfo fd;
- static char *szContinue =
- "Press any key to continue, ESC to return to the menu.";
-
- _clearscreen( _GCLEARSCREEN );
- SprintAt( iRow++, 1, "short charttype = %d", ce.charttype );
- SprintAt( iRow++, 1, "short chartstyle = %d", ce.chartstyle );
- SprintAt( iRow++, 1, "windowtype chartwindow =" );
- iRow = ShowWindowType( iRow, 1, ce.chartwindow );
- SprintAt( iRow++, 1, "windowtype datawindow =" );
- iRow = ShowWindowType( iRow, 1, ce.datawindow );
- SprintAt( ++iRow, 1, szContinue );
- if( getch() == ESCAPE )
- return;
-
- iRow = 2;
- _clearscreen( _GCLEARSCREEN );
- SprintAt( iRow++, 1, "titletype maintitle =" );
- iRow = ShowTitleType( iRow, 1, ce.maintitle );
- SprintAt( iRow++, 1, "titletype subtitle =" );
- iRow = ShowTitleType( iRow, 1, ce.subtitle );
- SprintAt( ++iRow, 1, szContinue );
- if( getch() == ESCAPE )
- return;
-
- iRow = 2;
- _clearscreen( _GCLEARSCREEN );
- SprintAt( iRow++, 1, "axistype xaxis =" );
- iRow = ShowAxisType( iRow, 1, ce.xaxis );
- SprintAt( ++iRow, 1, szContinue );
- if( getch() == ESCAPE )
- return;
-
- iRow = 2;
- _clearscreen( _GCLEARSCREEN );
- SprintAt( iRow++, 1, "axistype yaxis =" );
- iRow = ShowAxisType( iRow, 1, ce.yaxis );
- SprintAt( ++iRow, 1, szContinue );
- if( getch() == ESCAPE )
- return;
-
- iRow = 2;
- _clearscreen( _GCLEARSCREEN );
- SprintAt( iRow++, 1, "legendtype legend =" );
- iRow = ShowLegendType( iRow, 1, ce.legend );
- SprintAt( ++iRow, 1, szContinue );
- if( getch() == ESCAPE )
- return;
-
- iRow = 2;
- _clearscreen( _GCLEARSCREEN );
- if( _getfontinfo( &fd ) != -1 )
- {
- SprintAt( iRow++, 1, "struct _fontinfo =" );
- iRow = ShowFontInfo( iRow, 1, fd );
- SprintAt( ++iRow, 1, "Press any key to continue . . ." );
- getch();
- }
- }
-
- /* ShowAxisType - Displays data in a variable of type "axistype".
- *
- * Params: iRow - Row at which to start
- * iCol - Column from which to indent
- * theAxis - Variable of type "axistype" to display
- *
- * Return: Next available row
- */
- int ShowAxisType( int iRow, int iCol, axistype theAxis )
- {
- SprintAt( iRow++, iCol + 5, "short .grid = %d", theAxis.grid );
- SprintAt( iRow++, iCol + 5, "short .gridstyle = %d", theAxis.gridstyle
- SprintAt( iRow++, iCol + 5, "titletype axistitle=" );
- iRow = ShowTitleType( iRow, iCol + 5, theAxis.axistitle );
- SprintAt( iRow++, iCol + 5, "short .axiscolor = %d", theAxis.axiscolor
- SprintAt( iRow++, iCol + 5, "short .labeled = %s",
- (theAxis.labeled) ? "TRUE" : "FALSE" );
- SprintAt( iRow++, iCol + 5, "short .rangetype = %d", theAxis.rangetype
- SprintAt( iRow++, iCol + 5, "float .logbase = %f", theAxis.logbase );
- SprintAt( iRow++, iCol + 5, "short .autoscale = %s",
- (theAxis.autoscale) ? "TRUE" : "FALSE" );
- SprintAt( iRow++, iCol + 5, "float .scalemin = %f", theAxis.scalemin )
- SprintAt( iRow++, iCol + 5, "float .scalemax = %f", theAxis.scalemax )
- SprintAt( iRow++, iCol + 5, "float .scalefactor = %f", theAxis.scalefacto
- iRow = ShowTitleType( iRow, iCol + 5, theAxis.scaletitle );
- SprintAt( iRow++, iCol + 5, "float .ticinterval = %f", theAxis.ticinterv
- SprintAt( iRow++, iCol + 5, "short .ticformat = %d", theAxis.ticformat
- SprintAt( iRow++, iCol + 5, "short .ticdecimals = %d", theAxis.ticdecima
-
- return iRow;
- }
-
- /* ShowFontInfo - Displays data in a variable of type "_fontinfo".
- *
- * Params: iRow - Row at which to start
- * iCol - Column from which to indent
- * theFont - Variable of type "_fontinfo" to display
- *
- * Return: Next available row
- */
- int ShowFontInfo( int iRow, int iCol, struct _fontinfo theFont )
- {
- SprintAt( iRow++, iCol + 5, "int .type = %d", theFont.type );
- SprintAt( iRow++, iCol + 5, "int .ascent = %d", theFont.ascent );
- SprintAt( iRow++, iCol + 5, "int .pixwidth = %d", theFont.pixwidth )
- SprintAt( iRow++, iCol + 5, "int .pixheight = %d", theFont.pixheight
- SprintAt( iRow++, iCol + 5, "int .avgwidth = %d", theFont.avgwidth )
- SprintAt( iRow++, iCol + 5, "char .filename = %s", theFont.filename )
- SprintAt( iRow++, iCol + 5, "char .facename = %s", theFont.facename )
-
- return iRow;
- }
-
- /* ShowLegendType - Displays data in a variable of type "legendtype".
- *
- * Params: iRow - Row at which to start
- * iCol - Column from which to indent
- * theLegend - Variable of type "legendtype" to display
- *
- * Return: Next available row
- */
- int ShowLegendType( int iRow, int iCol, legendtype theLegend )
- {
- SprintAt( iRow++, iCol + 5, "short .legend = %s",
- (theLegend.legend) ? "TRUE" : "FALSE" );
- SprintAt( iRow++, iCol + 5, "short .place = %d", theLegend.place );
- SprintAt( iRow++, iCol + 5, "short .textcolor = %d", theLegend.textcolo
- SprintAt( iRow++, iCol + 5, "short .autosize = %d", theLegend.autosize
- SprintAt( iRow++, iCol + 5, "windowtype legendwindow =" );
- iRow = ShowWindowType( iRow, iCol + 5, theLegend.legendwindow );
-
- return iRow;
- }
-
- /* ShowSampleData - Displays the sample data for the demo.
- *
- * Params: None
- */
- void ShowSampleData()
- {
- int iCat, y, iSeries, iValue;
- char szTmp[80];
-
- /* Display data in table format. */
- _clearscreen( _GCLEARSCREEN );
- PrintAt( 1, 40 - strlen(szTmp) / 2, "Data in Table Format", -1 );
-
- /* Write titles and draw separator line. */
- y = 3;
- for( iCat = 1; iCat <= 12; iCat++ )
- PrintAt( y, iCat * 6, aMonths[iCat - 1], -1 );
-
- memset( szTmp, '-', 69 );
- szTmp[69] = 0;
- PrintAt( ++y, 6, szTmp, -1 );
-
- /* Write data. */
- for( iSeries = 1; iSeries <= 3; iSeries++ )
- {
- PrintAt( y += 2, 4, aSalesTitles[iSeries - 1], -1 );
- y += 2;
- for( iValue = 1; iValue <= 12; iValue++ )
- {
- sprintf( szTmp, "%#3.2f", aSales[iSeries - 1][iValue - 1] );
- PrintAt( y, iValue * 6, (char _far *)szTmp, -1 );
- }
- }
- PrintAt( y += 2, 4, TempTitle, -1 );
- y += 2;
- for( iValue = 1; iValue <= 12; iValue++ )
- {
- sprintf( szTmp, "%#3.1f", aTemperature[iValue - 1] );
- PrintAt( y, iValue * 6, szTmp, -1 );
- }
-
- PrintAt( y += 2, 1, "Press any key to continue . . .", -1 );
- getche();
- }
-
- /* ShowTitleType - Displays data in a variable of type "titletype".
- *
- * Params: iRow - Row at which to start
- * iCol - Column from which to indent
- * theTitle - Variable of type "titletype" to display
- *
- * Return: Next available row
- */
- int ShowTitleType( int iRow, int iCol, titletype theTitle )
- {
- SprintAt( iRow++, iCol + 5, "char .title[%d] = \"%s\"", _PG_TITLELEN,
- theTitle.title );
- SprintAt( iRow++, iCol + 5, "short .titlecolor = %d", theTitle.titlecolo
- SprintAt( iRow++, iCol + 5, "short .justify = %d", theTitle.justify )
-
- return iRow;
- }
-
- /* ShowWindowType - Displays data in a variable of type "windowtype".
- *
- * Params: iRow - Row at which to start
- * iCol - Column from which to indent
- * theWindow - Variable of type "windowtype" to display
- *
- * Return: Next available row
- */
- int ShowWindowType( int iRow, int iCol, windowtype theWindow )
- {
- SprintAt( iRow++, iCol + 5, "short .x1 = %d", theWindow.x1 );
- SprintAt( iRow++, iCol + 5, "short .y1 = %d", theWindow.y1 );
- SprintAt( iRow++, iCol + 5, "short .x2 = %d", theWindow.x2 );
- SprintAt( iRow++, iCol + 5, "short .y2 = %d", theWindow.y2 );
- SprintAt( iRow++, iCol + 5, "short .border = %d", theWindow.border )
- SprintAt( iRow++, iCol + 5, "short .background = %d", theWindow.backgrou
- SprintAt( iRow++, iCol + 5, "short .borderstyle = %d", theWindow.borderst
- SprintAt( iRow++, iCol + 5, "short .bordercolor = %d", theWindow.borderco
-
- return iRow;
- }
-
- /* ShowError - Displays error message for one of the chart library
- * errors.
- *
- * Params: iErr - Error number
- */
- void ShowError( int iErr )
- {
- char szTmp[50];
-
- /* Change to text screen. */
- _setvideomode( _DEFAULTMODE );
-
- /* Select the error text. */
- switch( iErr )
- {
- case _PG_NOTINITIALIZED:
- strcpy( szTmp, "Chart Library Not Initialized" );
- break;
- case _PG_BADSCREENMODE:
- strcpy( szTmp, "Invalid Screen Mode" );
- break;
- case _PG_BADCHARTTYPE:
- strcpy( szTmp, "Invalid Chart Type" );
- break;
- case _PG_BADCHARTSTYLE:
- strcpy( szTmp, "Invalid Chart Style" );
- break;
- case _PG_BADLEGENDWINDOW:
- strcpy( szTmp, "Invalid Legend Window" );
- break;
- case _PG_BADDATAWINDOW:
- strcpy( szTmp, "No Room for Data window" );
- break;
- case _PG_BADCHARTWINDOW:
- strcpy( szTmp, "Invalid Chart window coordinates" );
- break;
- case _PG_NOMEMORY:
- strcpy( szTmp, "Not Enough Memory for Data Arrays" );
- break;
- case _PG_BADLOGBASE:
- strcpy( szTmp, "X or Y log base <= 0" );
- break;
- case _PG_BADSCALEFACTOR:
- strcpy( szTmp, "X or Y scale factor = 0" );
- break;
- case _PG_TOOSMALLN:
- strcpy( szTmp, "Too few data values" );
- break;
- case _PG_TOOFEWSERIES:
- strcpy( szTmp, "No data series specified" );
- break;
- default:
- strcpy( szTmp, "Unknown error" );
- }
-
- ErrorMsg( szTmp );
- }
-
- /* ViewChart - Draws the current chart.
- *
- * Params: None
- */
- int ViewChart()
- {
- int cValue, iValue, iSeries, iErr;
-
- /* Make sure some data exists. */
- if( cSeries <= 0 )
- {
- fDefault = TRUE;
- DefaultData( ce.charttype, ce.chartstyle, FALSE );
- }
-
- /* Find the longest series. */
- cValue = 0;
- for( iSeries = 0; iSeries < cSeries; iSeries++ )
- if( acSeries[iSeries] > cValue )
- cValue = acSeries[iSeries];
-
- _setvideomode( si.mode );
-
-
- /* Process depending on the type of chart. */
- switch( ce.charttype )
- {
-
- case _PG_PIECHART:
- case _PG_BARCHART:
- case _PG_COLUMNCHART:
- case _PG_LINECHART:
-
- /* Initialize data and draw pie chart or single-series bar,
- * column, or line chart.
- */
- if( (cSeries == 1) ||( ce.charttype == _PG_PIECHART) )
- {
-
- /* Transfer data into a single-dimension array. */
- for( iValue = 0; iValue < cValue; iValue++ )
- axValue[iValue] = aValue[0][iValue];
-
- /* Draw chart. */
- if( ce.charttype == _PG_PIECHART )
- iErr = _pg_chartpie( &ce, aCat, axValue,
- aExplode, cValue );
- else
- iErr = _pg_chart( &ce, aCat, axValue, cValue );
- }
- /* If multiple-series, then data is OK. Just draw chart. */
- else
- iErr = _pg_chartms( &ce, aCat, (float _far *)aValue,
- cSeries, cValue, cValue, aSeriesName );
- break;
-
- case _PG_SCATTERCHART:
-
- /* Make sure there are enough data sets. */
- if( cSeries == 1 )
- {
- _setvideomode( _DEFAULTMODE );
- si.help = 10;
- ErrorMsg( "Too few value data columns for scatter chart." );
- return 1;
-
- }
- /* If it's a single-series scatter, transfer data to one-
- * dimensional arrays and make chart call.
- */
- else if( cSeries == 2 )
- {
- for( iValue = 0; iValue < cValue; iValue++ )
- {
- axValue[iValue] = aValue[0][iValue];
- ayValue[iValue] = aValue[1][iValue];
- }
- cSeries = 1;
- iErr = _pg_chartscatter( &ce, axValue, ayValue, cValue );
-
- }
- /* If it's a multiple-series scatter, transfer odd columns to
- * X-axis data array and even columns to Y-axis array and make
- * chart call.
- */
- else
- {
-
- for( iSeries = 1; iSeries < cSeries; iSeries += 2 )
- {
- aSeriesName[iSeries / 2] = aSeriesName[iSeries - 1];
- for( iValue = 0; iValue < cValue; iValue++ )
- {
- axValueMS[iSeries / 2][iValue] =
- aValue[iSeries - 1][iValue];
- ayValueMS[iSeries / 2][iValue] =
- aValue[iSeries][iValue];
- }
- }
- cSeries /= 2;
-
- iErr = _pg_chartscatterms( &ce, (float _far *)axValueMS,
- (float _far *)ayValueMS,
- cSeries, cValue, cValue,
- aSeriesName );
- }
- }
-
- if( !fDefault )
- ClearData( FALSE );
-
- /* If error, show it, else wait for keypress with chart on screen. */
- if( iErr )
- {
- ShowError( iErr );
- return iErr;
- }
- else
- return ( getch() == ESCAPE ); /* ESCAPE means stop demo */
- }
-
-
- CHRTOPT.C
- CD-ROM Disc Path: \SAMPCODE\C\MSC60\CHRTOPT.C
-
- #include <stdio.h>
- #include <conio.h>
- #include <string.h>
- #include <graph.h>
- #include <pgchart.h>
- #include "chrtdemo.h"
-
- /* Structures for system configuration and chart environment. */
- extern struct videoconfig vc;
- extern chartenv ce;
-
- /* Variable used to track control and screen position. */
- extern struct SCREENINFO si;
-
- /* Colors of menus and prompts. */
- extern struct tagColor co;
-
- /* Arrays of strings used by the Menu function. The first string is the
- * menu title. The next non-null strings are the menu selections. A null
- * string indicates the end of the list.
- */
- char *pszAxes[] =
- { "Axis", "X Axis", "Y Axis", "" };
-
- char *pszAxis[] =
- { "? Options", "Grid", "Axis Title", "Color",
- "Range Type", "Scale", "Tic Marks", "" };
-
- char *pszAuto[] =
- { "Auto", "Auto", "Manual", "" };
-
- char *pszBorder[] =
- { "Type", "Color", "Style", "" };
-
- char *pszChartWindow[] =
- { "Chart", "Size", "Color (Background)", "Border", "" };
-
- char *pszDataWindow[] =
- { "Data", "Color (Background)", "Border", "" };
-
- char * pszFontOpt[] =
- { "Font Options", "Change Typeface", "Set Character Size", "" };
-
- char *pszJustify[] =
- { "Justify", "Left", "Center", "Right", "" };
-
- char *pszLegendWindow[] =
- { "Options", "Place", "Text Color", "Size", "Color (Background)",
- "Border", "" };
-
- char *pszPlace[] =
- { "Place", "Right", "Bottom", "Overlay", "" };
-
- char *pszScale[] =
- { "Scale", "Low (Min)", "High (Max)", "Scale Factor", "Title", "" };
-
- char *pszSize[] =
- { "Size", "Top", "Left", "Bottom", "Right", "" };
-
- char *pszTic[] =
- { "Tic Type", "Interval", "Format", "Decimals", "" };
-
- char *pszTitleOpt[] =
- { "", "Text", "Color", "Justify", "" };
-
- char *pszTitles[] =
- { "Title", "Main Title", "Sub Title", "" };
-
- char *pszTypeface[] =
- { "Type Faces", "Courier", "Helv", "Tms Rmn", "Modern", "Script",
- "Roman", "None", "" };
-
- char *pszWindows[] =
- { "Window", "Chart Window", "Data Window", "" };
-
- /* Axes - Selects X or Y axis.
- *
- * Params: none
- */
- void Axes()
- {
- int iChoice;
- static axistype *patAxis[2] = { &ce.xaxis, &ce.yaxis };
-
- /* Get menu choice and call appropriate axis Menu. */
- PushTitle( pszAxes[0] );
- Help( "Choose 'X' or 'Y' Axis", co.InputColor );
- while( (iChoice = Menu( pszAxes )) != ESCAPE )
- {
- /* Modify axis title, depending on choice. */
- pszAxis[0][0] = (--iChoice == 0) ? 'X' : 'Y';
-
- /* Obtain axis information for appropriate axis. */
- Axis( patAxis[iChoice] );
- }
- PopTitle();
- }
-
- /* Axis - Selects axis options.
- *
- * Params: pat - Pointer to axistype variable
- */
- void Axis( axistype *pat )
- {
- int iChoice;
-
- PushTitle( pszAxis[0] );
- while( (iChoice = Menu( pszAxis )) != ESCAPE )
- {
-
- /* Get Axis option. */
- switch( iChoice )
- {
- case 1:
- /* Grid or not? */
- iChoice = BlankMenu( "Grid", "Grid", "No Grid" );
- switch( iChoice )
- {
-
- case 1:
- /* If yes, set grid flag and get the grid style. */
- pat->grid = TRUE;
- Help( "Enter a number in the range 0-10.",
- co.InputColor );
- pat->gridstyle =
- InputInt( "Grid Style? ", pat->gridstyle, 0, 10 )
- break;
-
- case 2:
- /* If no, clear grid flag. */
- pat->grid = FALSE;
- }
- PopTitle();
- break;
-
- case 2:
- /* Select axis title options. */
- pszTitleOpt[0] = "Axis Title";
- TitleOpt( &pat->axistitle );
- break;
-
- case 3:
- /* Select color. */
- Help( "Enter a number in the range 0-15.", co.InputColor );
- pat->axiscolor =
- InputInt( "Axis Color? ", pat->axiscolor, 0, 15 );
- break;
-
- case 4:
- /* Get the axis range. */
- AxisRange( pat );
- break;
-
- case 5:
- /* Get the axis scale. */
- AxisScale( pat );
- break;
-
- case 6:
- /* Get axis tic mark options. */
- AxisTics( pat );
- break;
-
- }
- }
- PopTitle();
- }
-
- /* AxisRange - Selects range for an axis.
- *
- * Params: pat - pointer to axistype variable
- */
- void AxisRange( axistype *pat )
- {
- int iChoice;
-
- iChoice = BlankMenu( "Range Type", "Normal", "Log" );
- switch( iChoice )
- {
- case 1:
- /* Set range type to linear. */
- pat->rangetype = _PG_LINEARAXIS;
- break;
-
- case 2:
- /* Set range type to log, then query for log base. */
- pat->rangetype = _PG_LOGAXIS;
- Help( "Enter a value greater than or equal 2.", co.InputColor );
- pat->logbase = (float)InputInt( "Log base? ",
- (int)pat->logbase, 2, 0 );
- break;
- }
- PopTitle();
- }
-
- /* AxisScale - Selects scale options for an axis.
- *
- * Params: pat - pointer to axistype variable
- */
- void AxisScale( axistype *pat )
- {
- int iChoice;
-
- PushTitle( pszAuto[0] );
- iChoice = Menu( pszAuto );
- switch( iChoice )
- {
-
- case 1:
- /* Set AutoScale flag. */
- pat->autoscale = TRUE;
- break;
-
- case 2:
-
- /* Clear AutoScale flag and get scale options. */
- pat->autoscale = FALSE;
- PushTitle( pszScale[0] );
- while( (iChoice = Menu( pszScale )) != ESCAPE )
- {
-
- switch( iChoice )
- {
-
- case 1:
- /* Query for scale minimum. */
- Help( "Enter the range minimum value.", co.InputColor
- pat->scalemin =
- (float)InputInt( "Minimum? ",
- (int)pat->scalemin, 1, 0 );
- break;
-
- case 2:
- /* Query for scale maximum. */
- Help( "Enter the range maximum value.", co.InputColor
- pat->scalemin =
- (float)InputInt( "Minimum? ",
- (int)pat->scalemin, 1, 0 );
- break;
-
- case 3:
- /* Query for scale factor. */
- Help( "Enter scale factor (must be 1 or greater).",
- co.InputColor );
- pat->scalefactor =
- (float)InputInt( "Scale Factor? ",
- (int)pat->scalefactor, 1, 0 );
- break;
-
- case 4:
- /* Modify scale title, then use menu to get
- * title options.
- */
- pszTitleOpt[0] = "Scale Title";
- TitleOpt( &pat->scaletitle );
-
- }
- }
- PopTitle();
- }
- PopTitle();
- }
-
- /* AxisTics - Selects tic options for an axis.
- *
- * Params: pat - pointer to axistype variable
- */
- void AxisTics( axistype *pat )
- {
- int iChoice;
-
- PushTitle( pszTic[0] );
- while( (iChoice = Menu( pszTic )) != ESCAPE )
- {
- switch( iChoice )
- {
-
- case 1:
- /* Query for tic interval. */
- Help( "Enter distance in data units.", co.InputColor );
- pat->ticinterval =
- InputFloat( "Distance between tic marks? ",
- pat->ticinterval );
- pat->autoscale = FALSE;
- break;
-
- case 2:
- /* Query for tic format. */
- iChoice = BlankMenu( "Tic Format", "Normal", "Log" );
- if( iChoice != ESCAPE )
- pat->ticformat = iChoice;
- break;
-
- case 3:
- /* Query for number of decimal places per tic. */
- pat->ticdecimals =
- InputInt( "Enter decimal places (0 to 9). ",
- pat->ticdecimals, 0, 9 );
- pat->autoscale = FALSE;
- break;
- }
-
- }
- PopTitle();
- }
-
- /* Border - Specifies border information for a window.
- *
- * Params: pwt - Pointer to windowtype variable
- */
- void Border( windowtype *pwt )
- {
- int iChoice;
-
- /* Ask whether a border is wanted. */
- iChoice = BlankMenu( "Border", "Border", "No Border" );
- switch( iChoice )
- {
-
- case 1:
-
- /* If border, set Border flag and query for border options. */
- pwt->border= TRUE;
- PushTitle( pszBorder[0] );
- while( (iChoice = Menu( pszBorder )) != ESCAPE )
- {
- switch( iChoice )
- {
- case 1:
- /* Query for border color. */
- Help( "Enter a color in the range 0-15.",
- co.InputColor );
- pwt->bordercolor =
- InputInt( "Border color? ",
- pwt->bordercolor, 0, 15 );
- break;
-
- case 2:
- /* Query for border style. */
- Help( "Enter a style in the range 0-10.", co.InputCol
- pwt->borderstyle =
- InputInt( "Border style? ",
- pwt->borderstyle, 0, 10 );
- }
- }
- PopTitle();
- break;
-
- case 2:
- /* If no border, clear Border flag. */
- pwt->border= FALSE;
- }
- PopTitle();
- }
-
- /* ChangeTypeface - Allow the user to specify a new type face.
- *
- * Params: iFaceIndex - index of last typeface
- *
- * Return: index of new typeface
- */
-
- int ChangeTypeface( int iFaceIndex )
- {
- int iChoice;
-
- /* Get menu choice and call appropriate axis Menu. */
- PushTitle( pszFontOpt[0] );
- Help( "Choose one of the type faces listed.", co.InputColor );
-
- if( (iChoice = Menu( pszTypeface ) - 1) != ESCAPE )
- {
- /* If the user wants the system font, unregister the other fonts. */
- if( iChoice == NOFONT )
- _unregisterfonts();
-
- /* If the user wants any font but the system font, make sure the
- * fonts are registered.
- */
- else
- {
- /* If last face was NOFONT, register fonts. */
- if( iFaceIndex == NOFONT )
- {
- /* Assumes font files are in current directory.
- * Could be enhanced to handle any directory.
- */
- if( _registerfonts( "*.FON" ) < 0 )
- ErrorMsg( "Font files must be in current directory" );
- else
- iFaceIndex = iChoice;
- }
- else
- iFaceIndex = iChoice;
- }
- }
-
- PopTitle();
- return iFaceIndex;
- }
-
- /* ChooseFont - Chooses a font from the font library.
- *
- * Params: WhichFont - A member of the set [COURIER, HELV, TMS_RMN,
- * MODERN, SCRIPT, ROMAN, NOFONT]
- * Height - The desired height of the text (in pixels)
- */
-
- void ChooseFont( int WhichFont, int Height )
- {
- static char *FontIds[] =
- {
- "courier", "helv", "tms rmn", "modern", "script", "roman"
- };
- char SetCommand[30];
-
- /* Construct the command to send to _setfont. */
- sprintf( SetCommand, "t'%s'h%dw0b", FontIds[WhichFont], Height );
-
- if( _setfont( SetCommand ) < 0 )
- {
- _outtext( "Could not set. Try different font or size" );
- getch();
- }
- }
-
- /* ChartWindow - Gets chart window information.
- *
- * Params: None
- */
- void ChartWindow()
- {
- int iChoice;
-
- PushTitle( pszChartWindow[0] );
- while( (iChoice = Menu( pszChartWindow )) != ESCAPE )
- {
-
- /* Get window options. */
- switch( iChoice )
- {
-
- case 1:
- /* Get window size. */
- WindowSize( &ce.chartwindow );
- break;
-
- case 2:
- /* Query for background color. */
- Help( "Enter a number in the range 0-15", co.InputColor );
- ce.chartwindow.background =
- InputInt( "Background Color? ", ce.chartwindow.background
- 0, 15 );
- break;
-
- case 3:
-
- /* Get border options. */
- Border( &ce.chartwindow );
-
- }
- }
- PopTitle();
- }
-
- /* DataWindow - Geta data window information.
- *
- * Params: None
- */
- void DataWindow()
- {
- int iChoice;
-
- PushTitle( pszDataWindow[0] );
- while( (iChoice = Menu( pszDataWindow )) != ESCAPE )
- {
-
- /* Get data window menu options. */
- switch( iChoice )
- {
-
- case 1:
- /* Query for background color. */
- Help( "Enter a number in the range 0-15", co.InputColor );
- ce.datawindow.background =
- InputInt( "Background Color? ",
- ce.datawindow.background,
- 0, 15 );
- break;
-
- case 2:
- /* Get border options. */
- Border( &ce.datawindow );
- break;
-
- }
- }
- PopTitle();
- }
-
- /* FontOptions - Allows the user to modify the font used for display.
- *
- * Params: None
- */
-
- void FontOptions()
- {
- int iChoice;
- static int iFaceIndex = NOFONT;
- static int iTypeSize = 8;
-
- /* Get menu choice and call appropriate axis Menu. */
- PushTitle( pszFontOpt[0] );
-
- while( (iChoice = Menu( pszFontOpt )) != ESCAPE )
- {
- switch( iChoice )
- {
- /* Change Typeface. */
- case 1:
- iFaceIndex = ChangeTypeface( iFaceIndex );
- ChooseFont( iFaceIndex, iTypeSize );
- break;
-
- /* Change Type Size. */
- case 2:
-
- if( iFaceIndex == NOFONT )
- {
- ErrorMsg( "Select a font first" );
- break;
- }
-
- iTypeSize = InputInt( "Enter a type size. ", iTypeSize,
- 8, 128 );
-
- ChooseFont( iFaceIndex, iTypeSize );
- break;
-
- default:
- break;
- }
- }
- PopTitle();
- }
-
- /* Justify - Gets title justification option.
- *
- * Params: Pointer to titletype variable
- */
- void Justify( titletype *ptt )
- {
- int iChoice;
-
- PushTitle( pszJustify[0] );
- iChoice = Menu( pszJustify );
- switch( iChoice )
- {
-
- /* Set justification. */
- case 1:
- case 2:
- case 3:
- ptt->justify = iChoice;
- }
- PopTitle();
- }
-
- /* Legend - Asks whether a legend is desired, and if so, gets
- * legend options.
- *
- * Params: None
- */
- void Legend()
- {
- int iChoice;
-
- /* Is legend desired? */
- iChoice = BlankMenu( "Legend", "Legend", "No Legend" );
- switch( iChoice )
- {
- case 1:
- /* If legend, set legend flag and get options. */
- ce.legend.legend = TRUE;
- PushTitle( pszLegendWindow[0] );
- do
- {
- iChoice = Menu( pszLegendWindow );
- switch( iChoice )
- {
-
- case 1:
- /* Get legend place. */
- LegendPlace();
- break;
-
- case 2:
- /* Query for legend color. */
- Help( "Enter a number in the range 0-15.", co.InputCo
- ce.legend.textcolor =
- InputInt( "Text color? ",
- ce.legend.textcolor,
- 0, 15 );
- break;
-
- case 3:
- /* Get auto or manual sizing. */
- PushTitle( "Auto Legend" );
- iChoice = Menu( pszAuto );
-
- /* Set or clear the autosize flag. If manual
- * sizing was selected, get legend size.
- */
- switch( iChoice )
- {
- case 1:
- ce.legend.autosize = TRUE;
- break;
-
- case 2:
- ce.legend.autosize = FALSE;
- WindowSize( &ce.legend.legendwindow );
- }
- PopTitle();
- break;
-
- case 4:
- /* Query for background color. */
- Help( "Type a number in the range 0-15.", co.InputCol
- ce.legend.legendwindow.background =
- InputInt( "Background color? ",
- ce.legend.legendwindow.background,
- 0, 15 );
- break;
-
- case 5:
- /* Get border options for legend window. */
- Border( &ce.legend.legendwindow );
- }
-
- } while( iChoice != ESCAPE );
- PopTitle();
- break;
-
- case 2:
- /* If no legend wanted, clear flag. */
- ce.legend.legend = FALSE;
-
- }
- PopTitle();
- }
-
- /* LegendPlace - Gets legend placement option.
- *
- * Params: None
- */
- void LegendPlace()
- {
- int iChoice;
-
- /* Get legend placement. */
- PushTitle( pszPlace[0] );
- iChoice = Menu( pszPlace );
- switch( iChoice )
- {
-
- case 1:
- ce.legend.place = _PG_RIGHT;
- break;
-
- case 2:
- ce.legend.place = _PG_BOTTOM;
- break;
-
- case 3:
- ce.legend.place = _PG_OVERLAY;
- }
- PopTitle();
- }
-
- /* ScreenMode - Gets a new screen mode.
- *
- * Params: None
- */
- void ScreenMode()
- {
- int iMode, i;
- char szTmp[80], szHlp[80];
- static int iLegal[5][11] =
- {
- { 3, 4, 5, 6 },
- { 4, 4, 5, 6, 64 },
- { 4, 4, 5, 6, 19 },
- { 7, 4, 5, 6, 13, 14, 15, 16 },
- { 10, 4, 5, 6, 13, 14, 15, 16, 17, 18, 19 }
- };
- int iAdaptor;
-
- PushTitle( "Screen Mode" );
-
- /* Show appropriate help line for adaptor. */
- switch( vc.adapter )
- {
- case _HGC:
- PopTitle();
- return;
- case _CGA:
- iAdaptor = 0;
- break;
- case _OCGA:
- iAdaptor = 1;
- break;
- case _MCGA:
- iAdaptor = 2;
- break;
- case _EGA:
- case _OEGA:
- if( vc.adapter == _MONO )
- {
- PopTitle();
- return;
- }
- else
- iAdaptor = 3;
- break;
- case _VGA:
- case _OVGA:
- iAdaptor = 4;
- break;
- }
-
- /* Form the help line (which gives the choices legal for
- * the adaptor sensed in the user's machine).
- */
- for( iMode = 0, szHlp[0] = '\0'; iMode <= iLegal[iAdaptor][0]; ++iMode )
- {
- if( iMode == 0 )
- strcpy( szTmp, "Enter " );
- else if( iMode < iLegal[iAdaptor][0] )
- sprintf( szTmp, "%d, ", iLegal[iAdaptor][iMode] );
- else
- sprintf( szTmp, "or %d", iLegal[iAdaptor][iMode] );
- strcat( szHlp, szTmp );
- }
-
- WrtForm( 18 );
- Help( szHlp, co.InputColor );
-
- /* Query for screen mode. */
- for( ;; )
- {
- iMode = InputInt( "Screen Mode? ", si.mode, 1, 64 );
- for( i = 1; i <= iLegal[iAdaptor][0]; ++i ) /* Test legal values *
- if( iMode == iLegal[iAdaptor][i] ) /* If a match is found *
- break; /* Terminate for loop *
- if( iMode == iLegal[iAdaptor][i] ) /* If it's a match, *
- break; /* terminate do loop, *
- else /* otherwise BEEP, and *
- putchar( BEEP ); /* solicit correct data *
- }
-
- PopTitle();
- if( SetGraphMode( iMode ) )
- _setvideomode( _DEFAULTMODE );
- else
- ShowError( _PG_BADSCREENMODE );
-
- /* Force rescaling of the chart by resetting the window
- * rectangles for the chart and data windows to zero size.
- */
- ce.chartwindow.x1 = ce.chartwindow.x2 = ce.chartwindow.y1 =
- ce.chartwindow.y2 = 0;
- ce.datawindow = ce.chartwindow;
- }
-
- /* TitleOpt - Gets title options.
- *
- * Params: ptt - Pointer to titletype variable
- */
- void TitleOpt( titletype *ptt )
- {
- int iChoice;
-
- PushTitle( pszTitleOpt[0] );
- do
- {
- iChoice = Menu( pszTitleOpt );
- switch( iChoice )
- {
-
- case 1:
- /* Query for title text. */
- Help( "70 characters maximum length.", co.InputColor );
- InputStr( "Enter Text: ", ptt->title );
- break;
-
- case 2:
- /* Query for title color color. */
- Help( "Enter a number in the range 0-15.", co.InputColor );
- ptt->titlecolor =
- InputInt( "Title Color? ", ptt->titlecolor, 0, 15 );
- break;
-
- case 3:
- /* Get justify option. */
- Justify( ptt );
- }
- ClrHelp();
-
- } while( iChoice != ESCAPE );
- PopTitle();
- }
-
- /* Titles - Manages Main and Sub title menus.
- *
- * Params: None
- */
- void Titles()
- {
- int iChoice;
-
- PushTitle( pszTitles[0] );
- do
- {
- iChoice = Menu( pszTitles );
- switch( iChoice )
- {
-
- case 1:
- /* Fix menu title and get options for main title. */
- pszTitleOpt[0] = "MainTitle";
- TitleOpt( &ce.maintitle );
- break;
-
- case 2:
- /* Fix menu title and get options for subtitle. */
- pszTitleOpt[0] = "Sub Title";
- TitleOpt( &ce.subtitle );
- }
- } while( iChoice != ESCAPE );
- PopTitle();
- }
-
- /* Windows - Selects chart or data window, and gets options for either.
- *
- * Params: None
- */
- void Windows()
- {
- int iChoice;
-
- PushTitle( pszWindows[0] );
- do
- {
-
- /* Select window and get options for it. */
- iChoice = Menu( pszWindows );
- switch( iChoice )
- {
-
- case 1:
- ChartWindow();
- break;
-
- case 2:
- DataWindow();
-
- }
- } while( iChoice != ESCAPE );
- PopTitle();
- }
-
- /* WindowSize - Gets coordinates for window location and size.
- *
- * Params: pwt - pointer to windowtype variable
- */
- void WindowSize( windowtype *pwt )
- {
- int iChoice;
-
- /* Get window size settings. */
- PushTitle( pszSize[0] );
- do
- {
- /* Query for top, bottom, left, or right of window. */
- iChoice = Menu( pszSize );
- switch( iChoice )
- {
-
- case 1:
- Help( "Enter window top in pixels.", co.InputColor );
- pwt->y1 = InputInt( "Top? ", pwt->y1, 0, si.yMax );
- break;
-
- case 2:
- Help( "Enter window Left in pixels.", co.InputColor );
- pwt->x1 = InputInt( "Left? ", pwt->x1, 0, si.xMax );
- break;
-
- case 3:
- Help( "Enter window bottom in pixels.", co.InputColor );
- pwt->y2 = InputInt( "Bottom? ", pwt->y2, 0, si.yMax );
- break;
-
- case 4:
- Help( "Enter window right in pixels.", co.InputColor );
- pwt->x2 = InputInt( "Right? ", pwt->x2, 0, si.xMax );
- }
- } while( iChoice != ESCAPE );
- PopTitle();
- }
-
-
- CHRTSUPT.C
- CD-ROM Disc Path: \SAMPCODE\C\MSC60\CHRTSUPT.C
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdarg.h>
- #include <string.h>
- #include <conio.h>
- #include <graph.h>
- #include <pgchart.h>
- #include "chrtdemo.h"
-
- /* Variables to manage menus. */
- int cMenuLevel = 0; /* Current menu level */
- char *szMenuTitles[10]; /* Stack of menu titles */
-
- char *pszBlankMenu[4];
-
- /* Variables used to track control and screen position. */
- extern struct SCREENINFO si;
-
- /* Colors of menus and prompts. */
- extern struct tagColor co;
-
- /* BlankMenu - Gets responses to two specified choices.
- *
- * Params: pchTitle - Menu title string
- * pchChoice1 - Selection 1 string
- * pchChoice2 - Selection 2 string
- *
- * Return: Number of choice, or ESCAPE
- */
- int BlankMenu( char *pchTitle, char *pchChoice1, char *pchChoice2 )
- {
- int iChoice;
-
- /* Initialize title and selections. */
- pszBlankMenu[0] = pchTitle;
- pszBlankMenu[1] = pchChoice1;
- pszBlankMenu[2] = pchChoice2;
- pszBlankMenu[3] = "\0";
- PushTitle( pszBlankMenu[0]);
-
- while( TRUE )
- {
- /* Accept only first letter of either selection, or ESC. */
- iChoice = Menu( pszBlankMenu );
- switch( iChoice )
- {
- case 1:
- case 2:
- case ESCAPE:
- return iChoice;
- }
- }
- }
-
- /* ClrForm - Clears the center of the screen form.
- *
- * Params: None
- */
- void ClrForm()
- {
-
- /* Set partial screen window and clear it, then reset full screen. */
- _settextwindow( si.top, 1, si.bot, 80 );
- _clearscreen( _GWINDOW );
- _settextwindow( 1, 1, 25, 80 );
-
- }
-
- /* ClrHelp - Clears the current help line.
- *
- * Params: None
- */
- void ClrHelp()
- {
- /* Decrement the help line counter and clear the line. */
- _settextwindow( --si.help, 1, si.help, 80 );
- _clearscreen( _GWINDOW );
- _settextwindow( 1, 1, 25, 80 );
- }
-
- /* ErrorMsg - Displays an error message.
- *
- * Params: pchMsg - error message string
- */
- void ErrorMsg( char *pchMsg )
- {
-
- /* Beep, set error color, and display error message and continue prompt.
- putch( BEEP );
- Help( pchMsg, co.ErrorColor );
- Help( "Press any key to continue.", co.ErrorColor );
-
- /* Wait for keypress and clear help lines. */
- getch();
- ClrHelp();
- ClrHelp();
-
- }
-
- /* Help - Displays a help line on the screen.
- *
- * Params: pchMsg - error message string
- * sColor - color for message
- */
- void Help( char *pchMsg, short sColor )
- {
-
- struct rccoord rcCursor;
-
- /* Save current cursor position. */
- rcCursor = _gettextposition();
-
- /* Print out help line and increment Helpline position variable. */
- PrintAt( si.help++, 5, pchMsg, sColor );
-
- /* Restore cursor position. */
- _settextposition( rcCursor.row, rcCursor.col );
-
- }
-
- /* InputCh - Prompts for and returns a character of input.
- *
- * Params: pchPrompt - Prompt string
- * pchAccept - String of acceptable characters (case insensitive)
- *
- * Return: Character entered
- */
- int InputCh( char *pchPrompt, char *pchAccept )
- {
- int chResponse;
-
- /* Display prompt. */
- PrintAt( si.mid, 10, pchPrompt, co.InputColor );
-
- /* Loop until response is valid. */
- while( TRUE )
- {
- chResponse = toupper( getch() );
-
- /* Display and return if acceptable character, or beep if not. */
- if( *strchr( pchAccept, chResponse) )
- {
- _settextcolor( co.InfoColor );
- putch( chResponse );
- return chResponse;
- }
- else
- putch( BEEP );
- }
- }
-
- /* InputInt - Prompts for and returns an integer value within a
- * specified range.
- *
- * Params: pchPrompt - Prompt string
- * iOld - Previous value
- * iMin - Minimum value of range
- * iMax - Maximum value of range
- *
- * Return: integer input by user
- */
- int InputInt( char *pchPrompt, int iOld, int iMin, int iMax )
- {
- int i;
- char szTmp[70];
-
- /* Prompt for a string input and convert to an integer until a
- * value in the specified range is given. Then return the value.
- */
- do
- {
- InputStr( pchPrompt, itoa( iOld, szTmp, 10) );
- i = atoi( szTmp );
- } while( !InRange( i, iMin, iMax) );
- return i;
- }
-
- /* InputFloat - Prompts for and returns a float value.
- *
- * Params: pchPrompt - Prompt string
- * fOld - Previous value
- *
- * Return: float input by user
- */
- float InputFloat( char *pchPrompt, float fOld )
- {
- char szTmp[70];
-
- /* Prompt for a string input and convert to a float. */
- sprintf( szTmp, "%f", fOld );
- InputStr( pchPrompt, szTmp );
- return (float)atof( szTmp );
- }
-
- /* InputStr - Prompts for a string. Displays the previous string
- * until the first character is given. Then replaces it with new
- * entry.
- *
- * Params: pchPrompt - Prompt string
- * pchOld - Charater buffer containing previous string; it
- * must be long enough to hold new string
- *
- * Return: pointer to pchOld, which now contains new string
- */
- char *InputStr( char *pchPrompt, char *pchOld )
- {
- char szTmp[81];
- int x = 5, y = si.mid, ch;
-
- /* Display prompt in center of form. */
- ClrForm();
- PrintAt( y, x, pchPrompt, co.InputColor );
- x += strlen( pchPrompt );
-
- /* Print the old value for reference. */
- _outtext( pchOld );
- _settextposition( y, x );
-
- /* Wait for input. When received, clear old string. */
- while( !(ch = kbhit()) )
- ;
- memset( szTmp, ' ', 80 );
- szTmp[80] = '\0';
- PrintAt( y, x, szTmp, -1 );
-
- /* Get new string. If string entered, return it. If null string
- * (ENTER key pressed), return old value.
- */
- _settextcolor( co.InfoColor );
- _settextposition( y, x );
- szTmp[0] = 70; /* Maximum length to be read */
-
- cgets( szTmp );
- if( szTmp[1] > 0 ) /* Are any characters read? */
- {
- strcpy( pchOld, &szTmp[2] );
- return &szTmp[2];
- }
- else
- {
- _settextposition( y, x );
- return pchOld;
- }
- }
-
- /* InRange - Checks an integer to see if it is in a specified range.
- *
- * Params: iValue - Integer to check
- * iMin - Minimum value of range
- * iMax - Maximim value of range
- *
- * Return: TRUE if in range, FALSE if not
- */
- BOOL InRange( int Value, int iMin, int iMax )
- {
- /* Check range and return true if valid, false if not. Note that
- * (iMin >= iMax) is taken as a signal to check only the minimum
- * value; there is no maximum.
- */
- if( Value >= iMin )
- if( (Value <= iMax) || (iMin >= iMax) )
- return TRUE;
- else
- {
- ErrorMsg( "Invalid value." );
- return FALSE;
- }
- }
-
- /* Menu - Draws menu on screen and returns choice number.
- *
- * Params: array of menu strings
- *
- * Return: number corresponding to the choice made from the menu
- */
- int Menu( char *pszMenuList[] )
- {
- int iItem, cItem, yItem, x = 10;
- int chResponse;
-
- /* Count menu items. */
- for( cItem = 1; *pszMenuList[cItem]; cItem++ )
- ;
- --cItem;
-
-
- /* Clear the form and print the items in the menu. */
- WrtForm( 10 + cItem );
- for( iItem = 1, yItem = 8; iItem <= cItem; iItem++, yItem++ )
- {
- PrintAt( yItem, x, pszMenuList[iItem], co.InputColor );
- PrintChar( yItem, x, pszMenuList[iItem][0], co.HiliteColor );
- }
- ++yItem;
-
- /* Display prompt and help. */
- if( strcmpi( pszMenuList[0], "main menu" ) ) /* If not the main menu *
- Help( "Type the first letter of your selection or ESC to back up.",
- co.InputColor );
- else
- Help( "Type the first letter of your selection or \"Q\" to quit.",
- co.InputColor );
-
- PrintAt( yItem, x += 5, "Choice? ", co.InfoColor );
- x += 8;
-
- /* Loop until a valid choice is made. Beep at invalid choices. */
- while( TRUE )
- {
- _settextposition( yItem, x );
- chResponse = toupper( getch() );
-
- /* Back up for ESC. */
- if( chResponse == 27 )
- {
- ClrHelp();
- return ESCAPE;
- }
-
- /* Search first letters of choices for a match. If found, return
- * choice and clear help line.
- */
- for( iItem = 1; iItem <= cItem; iItem++ )
- {
- if( chResponse == toupper( pszMenuList[iItem][0]) )
- {
- putch( chResponse );
- ClrHelp();
- return iItem;
- }
- }
-
- /* If we get here, no valid choice was found, so beep and repeat. */
- putch( BEEP );
- }
- }
-
- /* PopTitle - Pops a menu title from the menu stack.
- *
- * Params: None
- */
- void PopTitle()
- {
- szMenuTitles[--cMenuLevel] = "";
- }
-
- /* PrintAt - Prints a string at the row/column coordinates
- * specified, in the specified color.
- *
- * Params: row - row at which to begin output of string
- * col - column at which to begin output of string
- * lpszString - zero (null) terminated string
- * sColor - color in which to output string (-1 if
- * PrintAt should leave color alone)
- */
- void PrintAt( int row, int column, char _far *lpszString, short sColor )
- {
- if( sColor != -1 )
- _settextcolor( sColor );
- _settextposition( row, column );
- _outtext( lpszString );
- }
-
- /* PrintChar - Prints a character at the row/column coordinates
- * specified, in the specified color.
- *
- * Params: row - row at which to begin output of string
- * col - column at which to begin output of string
- * cChar - character to print
- * sColor - color in which to output string (-1 if
- * PrintChar should leave color alone)
- */
- void PrintChar(int row, int column, char cChar, short sColor)
- {
- char szTiny[2];
-
- szTiny[0] = cChar;
- szTiny[1] = '\0';
- PrintAt( row, column, szTiny, sColor );
- }
-
- /* PushTitle - Pushes a menu title on to the menu stack.
- *
- * Params: pchTitle - title string to push
- */
- void PushTitle( char *pchTitle )
- {
- szMenuTitles[cMenuLevel++] = pchTitle;
- }
-
- /* SetDisplayColors - Set the colors to values appropriate to the display
- * adaptor being used.
- *
- * Parms: None
- */
- void SetDisplayColors()
- {
- if( ismono( si.mode ) )
- {
- co.InputColor = M_INPUTCOLOR;
- co.HiliteColor = M_HILITECOLOR;
- co.FormColor = M_FORMCOLOR;
- co.TitleColor = M_TITLECOLOR;
- co.ErrorColor = M_ERRORCOLOR;
- co.InfoColor = M_INFOCOLOR;
- }
- else
- {
- co.InputColor = C_INPUTCOLOR;
- co.HiliteColor = C_HILITECOLOR;
- co.FormColor = C_FORMCOLOR;
- co.TitleColor = C_TITLECOLOR;
- co.ErrorColor = C_ERRORCOLOR;
- co.InfoColor = C_INFOCOLOR;
- }
- }
-
- /* SprintAt - Format a string, using sprintf() and output to screen
- * using PrintAt.
- *
- * Parms: iRow - Row at which to begin display
- * iCol - Column at which to begin display
- * szFmt - Format string (see run-time library documentation for
- * correct formation of a format string)
- * ... - Variables to output
- */
- void SprintAt( int iRow, int iCol, char * szFmt, ... )
- {
- char szTmp[81];
- va_list Marker;
- va_list saveMarker;
-
- va_start( Marker, szFmt );
- saveMarker = Marker;
- vsprintf( szTmp, szFmt, Marker );
- va_end( Marker );
-
- PrintAt( iRow, iCol, szTmp, -1 );
- }
-
- /* WrtForm - Displays screen form.
- *
- * Params: yBot - Row number of the bottom row
- */
- void WrtForm( int yBot )
- {
- int i;
- char szTmp[81];
-
- /* Print message in upper right. */
- _clearscreen( _GCLEARSCREEN );
- PrintAt( 1, 55, "Presentation Graphics Demo", co.TitleColor );
-
- /* Clear the top separator line. */
- memset( szTmp, ' ', 79 );
- szTmp[79] = 0;
-
- /* Display each level of the menu title. */
- _settextposition( 5, 5 );
- for( i = 0; i < cMenuLevel; i++ )
- {
- if( i )
- _outtext( " - " );
- _outtext( szMenuTitles[i] );
- }
-
- /* Display the top separator line. */
- memset( szTmp, 196, 80 );
- szTmp[80] = 0;
- PrintAt( 6, 1, szTmp, co.FormColor );
-
- /* Display the bottom separator line. */
- PrintAt( yBot, 1, szTmp, co.FormColor );
-
- /* Set the global screen variables. */
-
- si.help = yBot + 1;
- si.top = 7;
- si.bot = yBot - 1;
- si.mid = (si.top + si.bot) / 2;
- }
-
-
- GRDEMO.C
- CD-ROM Disc Path: \SAMPCODE\C\MSC60\GRDEMO.C
-
- /* GRDEMO.C - Demonstrates capabilities of the Microsoft graphics library.
- * Uses MENU module to display menus. Uses TURTLE module for Turtle
- * graphics. This program runs only in DOS and requires GRAPHICS.LIB.
- */
-
- #include <graph.h>
- #include <math.h>
- #include <malloc.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <conio.h>
- #include <time.h>
- #include "turtle.h"
- #include "menu.h"
-
- /* Function prototypes */
- int main( void );
- void Circles( void );
- void Sphere( void );
- int Polygons( void );
- int Spiral( int angle, double inc );
- int InSpiral( double side, int angle, int inc );
- void Bug( void );
- void Adjust( void );
- void Diamond( double xy );
-
- /* Returns a random number between min and max, which must be in
- * integer range.
- */
- #define getrandom( min, max ) ((rand() % (int)(((max) + 1) - (min))) + (min))
-
- /* Constants */
- #define PI 3.141593
- #define LASTATR 15
- #define NLASTATR 14
-
- /* Array and enum for main menu */
- ITEM mnuMain[] =
- { /* Highlight Char Pos */
- { 0, "Quit" }, /* Q 0 */
- { 0, "Circles" }, /* C 0 */
- { 0, "Rotating Sphere" }, /* R 0 */
- { 0, "Tunnel" }, /* T 0 */
- { 0, "Spiral" }, /* S 0 */
- { 0, "Inverted Spiral" }, /* I 0 */
- { 0, "Bug" }, /* B 0 */
- { 0, "Adjust Window" }, /* A 0 */
- { 0, "Mode Change" }, /* M 0 */
- { 0, "" }
- };
-
- /* Define constants (0, 1, 2,...) for menu choices */
- enum CHOICES
- {
- QUIT, CIRCLES, SPHERE, TUNNEL, SPIRAL, INSPIRAL, BUG, ADJUST, CHANGE
- };
-
- /* Arrays of video mode menu items and of corresponding mode numbers.
- * Each has a temporary array containing all items, and a pointer version
- * including all except Olivetti.
- */
- ITEM mnuModesT[] =
- { /* Highlight Char Pos */
- { 0, "ORESCOLOR " }, /* O 0 */
- { 4, "MRES4COLOR " }, /* 4 4 */
- { 4, "MRESNOCOLOR" }, /* N 4 */
- { 4, "HRESBW" }, /* B 4 */
- { 0, "MRES16COLOR" }, /* M 0 */
- { 0, "HRES16COLOR" }, /* H 0 */
- { 0, "ERESCOLOR" }, /* E 0 */
- { 4, "VRES2COLOR" }, /* 2 4 */
- { 0, "VRES16COLOR" }, /* V 0 */
- { 1, "MRES256COLOR" }, /* R 4 */
- { 0, "" }
- };
- ITEM *mnuModes = &mnuModesT[1]; /* Default is no Olivetti mode */
-
- int aModesT[] =
- {
- _ORESCOLOR,
- _MRES4COLOR,
- _MRESNOCOLOR,
- _HRESBW,
- _MRES16COLOR,
- _HRES16COLOR,
- _ERESCOLOR,
- _VRES2COLOR,
- _VRES16COLOR,
- _MRES256COLOR,
- _TEXTMONO,
- _ERESNOCOLOR,
- _HERCMONO
- };
- int *aModes = &aModesT[1]; /* Default is no Olivetti mode */
-
- /* Global video configuration */
- struct videoconfig vc;
-
- int main()
- {
- int rowMid, colMid;
- int fColor, fFirstTime = TRUE;
- int iMode, iMainCur = 0, iModesCur = 0;
-
- _displaycursor( _GCURSOROFF );
- _getvideoconfig( &vc );
- rowMid = vc.numtextrows / 2;
- colMid = vc.numtextcols / 2;
-
- /* Select best graphics mode, adjust menus, set color flag. Note
- * that this requires checking both the adapter and the mode.
- */
- switch( vc.adapter )
- {
- case _OCGA:
- mnuModes = &mnuModesT[0]; /* Turn on Olivetti mode */
- aModes = &aModesT[0];
- case _CGA:
- mnuModesT[4].achItem[0] = '\0'; /* Turn off EGA modes */
- iMode = _MRES4COLOR;
- break;
- case _HGC:
- mnuModesT[7].achItem[0] = '\0';
- iMode = _HERCMONO;
- break;
- case _OEGA:
- mnuModes = &mnuModesT[0]; /* Turn on Olivetti mode */
- aModes = &aModesT[0];
- case _EGA:
- mnuModesT[7].achItem[0] = '\0'; /* Turn off VGA modes */
- if( vc.memory > 64 )
- iMode = _ERESCOLOR;
- else
- iMode = _HRES16COLOR;
- break;
- case _OVGA:
- mnuModes = &mnuModesT[0]; /* Turn on Olivetti mode */
- aModes = &aModesT[0];
- case _VGA:
- iMode = _VRES16COLOR;
- break;
- case _MCGA:
- iMode = _MRES256COLOR;
- break;
- case _MDPA:
- default:
- puts( "No graphics mode available.\n" );
- return TRUE;
- }
- switch( vc.mode )
- {
- case _TEXTBW80:
- case _TEXTBW40:
- fColor = FALSE;
- break;
- case _TEXTMONO:
- case _ERESNOCOLOR:
- case _HERCMONO:
- fColor = FALSE;
- if( iMode != _HERCMONO )
- iMode = _ERESNOCOLOR;
- mnuMain[8].achItem[0] = '\0'; /* Turn off mode change */
- break;
- default:
- fColor = TRUE;
- break;
- }
-
- /* Find current mode in mode array. */
- for( iModesCur = 0; aModes[iModesCur] != iMode; iModesCur++ )
- ;
-
- /* Seed randomizer with time. */
- srand( (unsigned)time( NULL ) );
-
- while( TRUE )
- {
- /* Set text mode and optionally clear the screen to blue. */
- _setvideomode(_DEFAULTMODE );
- if( fColor )
- _setbkcolor( (long)_TBLUE );
- _clearscreen( _GCLEARSCREEN );
-
- /* Select from menu. */
- iMainCur = Menu( rowMid, colMid, mnuMain, iMainCur );
-
- /* Set graphics mode and initialize turtle graphics. Put border
- * on window.
- */
- if( iMainCur != CHANGE )
- {
- _setvideomode( iMode );
- _displaycursor( _GCURSOROFF );
- _getvideoconfig( &vc );
- InitTurtle( &vc );
- Rectangle( 2 * tc.xMax, 2 * tc.yMax );
- }
-
- /* Branch to menu choice. */
- switch( iMainCur )
- {
- case QUIT:
- _setvideomode( _DEFAULTMODE );
- return FALSE;
- case CIRCLES:
- Circles();
- break;
- case SPHERE:
- Sphere();
- break;
- case TUNNEL:
- PenDown( FALSE );
- MoveTo( -tc.xMax * .2, tc.yMax * .15 );
- PenDown( TRUE );
- Polygons();
- while( !GetKey( NO_WAIT ) )
- NextColorValue( DEFAULT ); /* Rotate palette */
- break;
- case SPIRAL:
- if( Spiral( getrandom( 30, 80 ), (double)getrandom( 1, 5 ) )
- break;
- while( !GetKey( NO_WAIT ) )
- NextColorValue( DEFAULT );
- break;
- case INSPIRAL:
- NextColorIndex( 0 );
- if( InSpiral( (double)getrandom( 8, 20 ),
- getrandom( 4, 22 ),
- getrandom( 3, 31 ) ) )
- break;
- while( !GetKey( NO_WAIT ) )
- NextColorValue( DEFAULT );
- break;
- case BUG:
- Bug();
- break;
- case ADJUST:
- Adjust();
- continue;
- case CHANGE:
- if( fColor )
- _setbkcolor( (long)_TBLUE );
- _clearscreen( _GCLEARSCREEN );
-
- iModesCur = Menu( rowMid, colMid, mnuModes, iModesCur );
- iMode = aModes[iModesCur];
- if( vc.adapter == _MCGA )
- switch( iMode )
- {
- case _MRES16COLOR:
- case _HRES16COLOR:
- case _ERESCOLOR:
- case _VRES16COLOR:
- _settextposition( 1, 22 );
- _outtext( "Mode not recognized" );
- iMode = _MRES256COLOR;
- }
- break;
- }
- }
- }
-
- /* Circles - Draw circles of varying sizes and colors on screen in a
- * round pattern.
- *
- * Params: None
- *
- * Return: None
- *
- * Uses: tc
- */
- void Circles()
- {
- double x, y, xyRadius;
- int fFill, fPenDown;
-
- /* Initialize and save pen and fill flags. */
- if( tc.cci <= 4 )
- fFill = SetFill( FALSE );
- else
- fFill = SetFill( TRUE );
- fPenDown = PenDown( FALSE );
-
- while( TRUE )
- {
- /* Draw circles. */
- for( xyRadius = 10.0; xyRadius <= 130.0; xyRadius++ )
- {
- x = (tc.xMax - 30) * atan( sin( xyRadius / PI ) );
- y = (tc.yMax - 30) * atan( cos( xyRadius / PI ) );
- MoveTo( x, y );
- PenColor( NextColorIndex( DEFAULT ) );
- Circle( xyRadius );
- if( GetKey( NO_WAIT ) )
- {
- PenDown( fPenDown );
- SetFill( fFill );
- return;
- }
- }
-
- /* For palette modes (except 256 color), start over. */
- if( tc.ccv == 64 || tc.ccv == 16 )
- {
- _clearscreen( _GCLEARSCREEN );
- SetFill( FALSE );
- MoveTo( 0.0, 0.0 );
- PenColor( WHITE );
- Rectangle( 2 * tc.xMax, 2 * tc.yMax );
- SetFill( fFill );
- NextColorValue( DEFAULT );
- }
- }
- }
-
- /* Sphere - Draw and fill slices of a sphere. Rotate colors in EGA+ modes
- * with more than 4 color indexes.
- *
- * Params: None
- *
- * Return: None
- *
- * Uses: tc
- */
- void Sphere()
- {
- double xCur, xSize, ySize, xInc;
- short ciBorder, fFill;
-
- ySize = xSize = tc.yMax * 0.9 * 2;
- fFill = SetFill( FALSE );
- NextColorIndex( 0 );
- xInc = xSize / 14;
- ciBorder = PenColor( DEFAULT );
- BorderColor( ciBorder );
-
- /* Draw slices. */
- for( xCur = xInc; xCur <= xSize; xCur += xInc * 2 )
- Ellipse( xCur, ySize );
- SetFill( TRUE );
- PenDown( FALSE );
- Turn( 90 );
- xSize /= 2;
- MoveTo( xSize - xInc, 0.0 );
-
- NextColorValue( LIMITED );
-
- /* Fill slices. */
- while( tc.xCur >= (-xSize + xInc))
- {
- PenColor( NextColorIndex( DEFAULT ) );
- FillIn();
- Move( -xInc );
- }
-
- while( !GetKey( NO_WAIT ) )
- NextColorValue( LIMITED );
-
- PenDown( TRUE );
- SetFill( fFill );
- }
-
- /* Polygons - Draws polygons (starting with triangle) of increasing
- * size by incrementing the number of sides without changing the
- * length of sides. Make sure pen is down.
- *
- * Params: None
- *
- * Return: 1 for user interrupt, 0 for edge of screen encountered
- *
- * Uses: tc
- */
- int Polygons()
- {
- int cSides = 3, atrib = 1;
- double dxy = tc.yUnit;
-
- while( TRUE )
- {
- PenColor( NextColorIndex( DEFAULT ) );
- if( !Poly( cSides++, dxy += 1.5 ) )
- return FALSE;
- if( GetKey( NO_WAIT ) )
- return TRUE;
- }
- }
-
- /* Spiral - Draw a spiral by incrementing the length of each side
- * of a rotating figure.
- *
- * Params: ang - determines tightness
- * xyInc - determines size of sides
- *
- * Return: 1 for user interrupt, 0 for edge of screen encountered
- *
- * Uses: tc
- */
- int Spiral( int ang, double xyInc )
- {
- double xy = tc.yUnit;
-
- while( TRUE )
- {
- PenColor( NextColorIndex( DEFAULT ) );
- if( !Move( xy += xyInc ) )
- return FALSE;
- Turn( ang );
- if( GetKey( NO_WAIT ) )
- return TRUE;
- }
- }
-
- /* InSpiral - Draw an inverted spiral by increasing each angle
- * of a rotating figure while keeping the length of sides constant.
- *
- * Params: xy - determines size
- * ang - initial angle determines shape
- * angInc - determines tightness and shape
- *
- * Return: 1 for user interrupt, 0 for edge of screen encountered
- */
- int InSpiral( double xy, int ang, int angInc )
- {
- while( TRUE )
- {
- PenColor( NextColorIndex( DEFAULT ) );
- if( !Move( xy ) )
- return FALSE;
- Turn( ang += angInc );
- if( GetKey( NO_WAIT ))
- return TRUE;
- }
- }
-
- /* Bug - Draws a winged bug on the screen. Then moves it randomly
- * around the screen.
- *
- * Params: None
- *
- * Return: None
- *
- * Uses: tc
- */
- void Bug()
- {
-
- static unsigned char uTopWing[] = { 0x81, 0x3c, 0xc3, 0x66,
- 0x66, 0x0f, 0xf0, 0x18 };
- static unsigned char uBotWing[] = { 0x66, 0x0f, 0xf0, 0x18,
- 0x81, 0x3c, 0xc3, 0x66 };
- char *buffer; /* Buffer for image */
-
- /* Draw bug. */
- PenDown( FALSE );
- SetFill( TRUE );
- Move( 40.0 ); /* Draw and fill front wings */
- Turn( 90 );
- Move( 80.0 );
- PenColor( 1 );
- _setfillmask( uTopWing );
- Ellipse( 172.0, 70.0 );
- Turn( 180 );
- Move( 160.0 );
- Ellipse( 172.0, 70.0 );
- Turn(-90 );
- MoveTo( 0.0, 0.0 );
- Move( 25.0 ); /* Draw and fill back wings */
- Turn( 90 );
- Move( 70.0 );
- PenColor( 2 );
- _setfillmask( uBotWing );
- Ellipse( 150.0, 70.0 );
- Turn( 180 );
- Move( 140.0 );
- Ellipse( 150.0, 70.0 );
- Turn(-90 );
- MoveTo( 0.0, 0.0 );
- _setfillmask( NULL ); /* Draw body */
- PenColor( 3 );
- BorderColor( 3 );
- Ellipse( 52.0, 220.0 );
- PenColor( 1 ); /* Drill eyes */
- BorderColor( 1 );
- SetFill( FALSE );
- Move( 90.0 );
- Turn( 90 );
- Move( 22.0 );
- Circle( 20.0 );
- PenColor( 0 );
- FillIn();
- PenColor( 1 );
- Turn( 180 );
- Move( 44.0 );
- Circle( 20.0 );
- PenColor( 0 );
- FillIn();
-
- /* Move into position - top-right of image. */
- MoveTo( 0.0, 0.0 );
- TurnTo( 0 );
- Move( 120.0 );
- Turn( -90 );
- Move( 175.0 );
- Turn( 90 );
-
- /* Size image and allocate memory for it. */
- buffer = (char *)malloc( (size_t)ImageSize( 350.0, 240.0 ) );
- GetImage( 350.0, 240.0, buffer );
-
- /* Move randomly, adjusting at edges. */
- while( !GetKey( NO_WAIT ) )
- {
- if( tc.xCur <= (-tc.xMax + 15.0) )
- TurnTo( 90 );
- else if( tc.yCur <= (-tc.yMax + 15.0) )
- TurnTo( 180 );
- else if( tc.xCur >= (tc.xMax - 365.0) )
- TurnTo( 270 );
- else if( tc.yCur >= (tc.yMax - 255.0) )
- TurnTo( 0 );
- else
- Turn( getrandom( -20, 20 ) );
- Move( 3.0 );
- PutImage( buffer, _GPSET );
- }
- free( (char *)buffer );
- }
-
- /* Adjust - Allow the user to interactively adjust the display window.
- * Unshifted direction keys adjust the window size. Shifted direction
- * keys move the window. The numeric keypad plus and minus keys adjust
- * aspect without changing the window. A window frame and a diamond give
- * visual feedback on adjustments.
- *
- * Params: None
- *
- * Return: None
- *
- * Uses: tc and vc
- */
- #define WININC 4
- void Adjust()
- {
- short iWriteMode;
- double xyRadius = 400.0, xEdge, yEdge;
- char achT[40];
-
- /* Display instructions. */
- _clearscreen( _GCLEARSCREEN );
- _settextposition( 2, 2 );
- _outtext(" Grey PLUS and MINUS Adjust aspect" );
- _settextposition( 3, 2 );
- _outtext(" Cursor keys Size window" );
- _settextposition( 4, 2 );
- _outtext(" SHIFT cursor keys Move window" );
- _settextposition( 5, 2 );
- _outtext(" ENTER Finished" );
-
- /* Save old write mode and set XOR so you can erase figures by
- * redrawing. This allows lines to overwrite text without erasing.
- */
- iWriteMode = _getwritemode();
- _setwritemode( _GXOR );
-
- while( TRUE )
- {
- /* Display data. */
- _settextposition( 6, 2 );
- sprintf( achT, " ratio=%1.2f xMax=%.f yMax=%.f",
- tc.yxRatio, tc.xMax, tc.yMax );
- _outtext( achT );
-
- /* Calculate current box edges. */
- xEdge = 2 * tc.xMax;
- yEdge = 2 * tc.yMax;
-
- /* Draw border rectangle and diamond that illustrates ratio. */
- Rectangle( xEdge, yEdge );
- Diamond( xyRadius );
-
- switch( GetKey( CLEAR_WAIT ) )
- {
- /* Adjust aspect. */
- case N_MINUS:
- if( tc.yxRatio > 0.4 )
- tc.yxRatio = (tc.xMax - (WININC * tc.yUnit)) / tc.yMax;
- break;
-
- case N_PLUS:
- if( tc.yxRatio < 8.0 )
- tc.yxRatio = (tc.xMax + (WININC * tc.yUnit)) / tc.yMax;
- break;
-
- /* Adjust window size. */
- case U_RT:
- if( tc.xsLeft < (vc.numxpixels / 3) )
- tc.xsLeft += WININC;
- if( tc.xsRight > (vc.numxpixels - (vc.numxpixels / 3)) )
- tc.xsRight -= WININC;
- break;
- case U_LT:
- if( tc.xsLeft )
- tc.xsLeft -= WININC;
- if( tc.xsRight < vc.numxpixels )
- tc.xsRight += WININC;
- break;
- case U_DN:
- if( tc.ysTop < (vc.numypixels / 3) )
- tc.ysTop += WININC;
- if( tc.ysBot > (vc.numypixels - (vc.numypixels / 3)) )
- tc.ysBot -= WININC;
- break;
- case U_UP:
- if( tc.ysTop )
- tc.ysTop -= WININC;
- if( tc.ysBot < vc.numypixels )
- tc.ysBot += WININC;
- break;
-
- /* Adjust window position. */
- case S_LT:
- if( tc.xsLeft )
- {
- tc.xsLeft -= WININC;
- tc.xsRight -= WININC;
- }
- break;
- case S_RT:
- if( tc.xsRight < vc.numxpixels )
- {
- tc.xsLeft += WININC;
- tc.xsRight += WININC;
- }
- break;
- case S_UP:
- if( tc.ysTop )
- {
- tc.ysTop -= WININC;
- tc.ysBot -= WININC;
- }
- break;
- case S_DN:
- if( tc.ysBot < vc.numypixels )
- {
- tc.ysTop += WININC;
- tc.ysBot += WININC;
- }
- break;
-
- /* Finished. */
- case ENTER:
- _setwritemode( iWriteMode );
- return;
-
- /* Ignore unknown key. */
- default:
- break;
- }
- /* Redraw figures to erase them. Reset defaults. */
- Rectangle( xEdge, yEdge );
- Diamond( xyRadius );
- Home();
- }
- }
-
- /* Routine used by Adjust to draw its diamond. */
- void Diamond( double xy )
- {
- PenDown( FALSE );
- MoveTo( 0.0, xy );
- PenDown( TRUE );
- MoveTo( xy, 0.0 );
- MoveTo( 0.0, -xy );
- MoveTo( -xy, 0.0 );
- MoveTo( 0.0, xy );
- PenDown( FALSE );
- MoveTo( 0.0, 0.0 );
- PenDown( TRUE );
- }
-
-
- MENU.C
- CD-ROM Disc Path: \SAMPCODE\C\MSC60\MENU.C
-
- /* MENU - Module of functions to put menus on the screen and handle keyboard
- * input. To use it, include the MENU.H file in your program. The following
- * functions are public:
- *
- * Menu - Puts a menu on screen and reads input for it
- * Box - Puts a box on screen (fill it yourself)
- * GetKey - Gets ASCII or function key
- * _outchar - Displays character using current text position and color
- *
- * The following structures are defined:
- *
- * MENU - Defines menu colors, box type, and centering
- * ITEM - Defines text of menu item and index of highlight characte
- *
- * The global variable "mnuAtrib" has type MENU. Change this variable to
- * change menu appearance.
- */
-
- #include <string.h>
- #include <stddef.h>
- #include <ctype.h>
- #include <graph.h>
- #include <bios.h>
- #include "menu.h"
-
- /* Prototype for internal function */
- static void Itemize( int row, int col, int fCur, ITEM itm, int cBlank );
-
- /* Default menu attribute. The default works for color or B&W. You can
- * override the default value by defining your own MENU variable and
- * assigning it to mnuAtrib, or you can modify specific fields at
- * run time. For example, you could use a different attribute for color
- * than for black and white.
- */
- MENU mnuAtrib =
- {
- _TBLACK, _TBLACK, _TWHITE, _TBRIGHTWHITE, _TBRIGHTWHITE,
- _TWHITE, _TWHITE, _TBLACK, _TWHITE, _TBLACK,
- TRUE,
- '┌', '┐', '┘', '└', '│', '─'
- };
-
- /* Menu - Puts menu on screen and reads menu input from keyboard. When a
- * highlighted hot key or ENTER is pressed, returns the index of the
- * selected menu item.
- *
- * Params: row and col - If "fCentered" attribute of "mnuAtrib" is true,
- * center row and column of menu; otherwise top left of menu
- * aItem - array of structure containing the text of each item
- * and the index of the highlighted hot key
- * iCur - index of the current selection--pass 0 for first item,
- * or maintain a static value
- *
- * Return: The index of the selected item
- *
- * Uses: mnuAtrib
- */
- int Menu( int row, int col, ITEM aItem[], int iCur )
- {
- int cItem, cchItem = 2; /* Counts of items and chars per item */
- int i, iPrev; /* Indexes - temporary and previous */
- int acchItem[MAXITEM]; /* Array of counts of character in items */
- char *pchT; /* Temporary character pointer */
- char achHilite[36]; /* Array for highlight characters */
- unsigned uKey; /* Unsigned key code */
- long bgColor; /* Screen color, position, and cursor */
- short fgColor;
- struct rccoord rc;
- unsigned fCursor;
-
- /* Save screen information. */
- fCursor = _displaycursor( _GCURSOROFF );
- bgColor = _getbkcolor();
- fgColor = _gettextcolor();
- rc = _gettextposition();
-
- /* Count items, find longest, and put count of each in array. Also,
- * put the highlighted character from each in a string.
- */
- for( cItem = 0; aItem[cItem].achItem[0]; cItem++ )
- {
- acchItem[cItem] = strlen( aItem[cItem].achItem );
- cchItem = (acchItem[cItem] > cchItem) ? acchItem[cItem] : cchItem;
- i = aItem[cItem].iHilite;
- achHilite[cItem] = aItem[cItem].achItem[i];
- }
- cchItem += 2;
- achHilite[cItem] = 0; /* Null-terminate and lowercase string */
- strlwr( achHilite );
-
- /* Adjust if centered, and draw menu box. */
- if( mnuAtrib.fCentered )
- {
- row -= cItem / 2;
- col -= cchItem / 2;
- }
- Box( row++, col++, cItem, cchItem );
-
- /* Put items on menu. */
- for( i = 0; i < cItem; i++ )
- {
- if( i == iCur )
- Itemize( row + i, col, TRUE, aItem[i], cchItem - acchItem[i] );
- else
- Itemize( row + i, col, FALSE, aItem[i], cchItem - acchItem[i] );
- }
-
- while( TRUE )
- {
- /* Wait until a uKey is pressed, then evaluate it. */
- uKey = GetKey( WAIT );
- switch( uKey )
- {
- case U_UP: /* Up key */
- iPrev = iCur;
- iCur = (iCur > 0) ? (--iCur % cItem) : cItem - 1;
- break;
- case U_DN: /* Down key */
- iPrev = iCur;
- iCur = (iCur < cItem) ? (++iCur % cItem) : 0;
- break;
- default:
- if( uKey > 256 ) /* Ignore unknown function key *
- continue;
- pchT = strchr( achHilite, (char)tolower( uKey ) );
- if( pchT != NULL ) /* If in highlight string, *
- iCur = pchT - achHilite;/* evaluate and fall through *
- else
- continue; /* Ignore unknown ASCII key *
- case ENTER:
- _setbkcolor( bgColor );
- _settextcolor( fgColor );
- _settextposition( rc.row, rc.col );
- _displaycursor( fCursor );
- return iCur;
- }
- /* Redisplay current and previous. */
- Itemize( row + iCur, col,
- TRUE, aItem[iCur], cchItem - acchItem[iCur] );
- Itemize( row + iPrev, col,
- FALSE, aItem[iPrev], cchItem - acchItem[iPrev] );
- }
- }
-
- /* Box - Draw menu box, filling interior with blanks of the border color.
- *
- * Params: row and col - upper left of box
- * rowLast and colLast - height and width
- *
- * Return: None
- *
- * Uses: mnuAtrib
- */
- void Box( int row, int col, int rowLast, int colLast )
- {
- int i;
- char achT[MAXITEM + 2]; /* Temporary array of characters */
-
- /* Set color and position. */
- _settextposition( row, col );
- _settextcolor( mnuAtrib.fgBorder );
- _setbkcolor( mnuAtrib.bgBorder );
-
- /* Draw box top. */
- achT[0] = mnuAtrib.chNW;
- memset( achT + 1, mnuAtrib.chEW, colLast );
- achT[colLast + 1] = mnuAtrib.chNE;
- achT[colLast + 2] = 0;
- _outtext( achT );
-
- /* Draw box sides and center. */
- achT[0] = mnuAtrib.chNS;
- memset( achT + 1, ' ', colLast );
- achT[colLast + 1] = mnuAtrib.chNS;
- achT[colLast + 2] = 0;
- for( i = 1; i <= rowLast; ++i )
- {
- _settextposition( row + i, col );
- _outtext( achT );
- }
-
- /* Draw box bottom. */
- _settextposition( row + rowLast + 1, col );
- achT[0] = mnuAtrib.chSW;
- memset( achT + 1, mnuAtrib.chEW, colLast );
- achT[colLast + 1] = mnuAtrib.chSE;
- achT[colLast + 2] = 0;
- _outtext( achT );
- }
-
- /* Itemize - Display one selection (item) of a menu. This function
- * is normally only used internally by Menu.
- *
- * Params: row and col - top left of menu
- * fCur - flag set if item is current selection
- * itm - structure containing item text and index of highlight
- * cBlank - count of blanks to fill
- *
- * Return: none
- *
- * Uses: mnuAtrib
- */
- void Itemize( int row, int col, int fCur, ITEM itm, int cBlank )
- {
- int i;
- char achT[MAXITEM]; /* Temporary array of characters */
-
- /* Set text position and color. */
- _settextposition( row, col );
- if( fCur )
- {
- _settextcolor( mnuAtrib.fgSelect );
- _setbkcolor( mnuAtrib.bgSelect );
- }
- else
- {
- _settextcolor( mnuAtrib.fgNormal );
- _setbkcolor( mnuAtrib.bgNormal );
- }
-
- /* Display item and fill blanks. */
- strcat( strcpy( achT, " " ), itm.achItem );
- _outtext( achT );
- memset( achT, ' ', cBlank-- );
- achT[cBlank] = 0;
- _outtext( achT );
-
- /* Set position and color of highlight character, then display it. */
- i = itm.iHilite;
- _settextposition( row, col + i + 1 );
- if( fCur )
- {
- _settextcolor( mnuAtrib.fgSelHilite );
- _setbkcolor( mnuAtrib.bgSelHilite );
- }
- else
- {
- _settextcolor( mnuAtrib.fgNormHilite );
- _setbkcolor( mnuAtrib.bgNormHilite );
- }
- _outchar( itm.achItem[i] );
- }
-
- /* GetKey - Gets a key from the keyboard. This routine distinguishes
- * between ASCII keys and function or control keys with different shift
- * states. It also accepts a flag to return immediately if no key is
- * available.
- *
- * Params: fWait - Code to indicate how to handle keyboard buffer:
- * NO_WAIT Return 0 if no key in buffer, else return key
- * WAIT Return first key if available, else wait for key
- * CLEAR_WAIT Throw away any key in buffer and wait for new key
- *
- * Return: One of the following:
- *
- * Keytype High Byte Low Byte
- * ------- --------- --------
- * No key available (only with NO_WAIT) 0 0
- * ASCII value 0 ASCII code
- * Unshifted function or keypad 1 scan code
- * Shifted function or keypad 2 scan code
- * CTRL function or keypad 3 scan code
- * ALT function or keypad 4 scan code
- *
- * Note: getkey cannot return codes for keys not recognized by BIOS
- * int 16, such as the CTRL-UP or the 5 key on the numeric keypad.
- */
- unsigned GetKey( int fWait )
- {
- unsigned uKey, uShift;
-
- /* If CLEAR_WAIT, drain the keyboard buffer. */
- if( fWait == CLEAR_WAIT )
- while( _bios_keybrd( _KEYBRD_READY ) )
- _bios_keybrd( _KEYBRD_READ );
-
- /* If NO_WAIT, return 0 if there is no key ready. */
- if( !fWait && !_bios_keybrd( _KEYBRD_READY ) )
- return FALSE;
-
- /* Get key code. */
- uKey = _bios_keybrd( _KEYBRD_READ );
-
- /* If low byte is not zero, it's an ASCII key. Check scan code to see
- * if it's on the numeric keypad. If not, clear high byte and return.
- */
- if( uKey & 0x00ff )
- if( (uKey >> 8) < 69 )
- return( uKey & 0x00ff );
-
- /* For function keys and numeric keypad, put scan code in low byte
- * and shift state codes in high byte.
- */
- uKey >>= 8;
- uShift = _bios_keybrd( _KEYBRD_SHIFTSTATUS ) & 0x000f;
- switch( uShift )
- {
- case 0:
- return( 0x0100 | uKey ); /* None (1) */
- case 1:
- case 2:
- case 3:
- return( 0x0200 | uKey ); /* Shift (2) */
- case 4:
- return( 0x0300 | uKey ); /* Control (3) */
- case 8:
- return( 0x0400 | uKey ); /* Alt (4) */
- }
- }
-
- /* _outchar - Display a character. This is the character equivalent of
- * _outtext. It is affected by _settextposition, _settextcolor, and
- * _setbkcolor. It should not be used in loops. Build strings and then
- * _outtext to show multiple characters.
- *
- * Params: out - character to be displayed
- *
- * Return: none
- */
- void _outchar( char out )
- {
- static char achT[2] = " "; /* Temporary array of characters */
-
- achT[0] = out;
- _outtext( achT );
- }
-
-
- SNAP.C
- CD-ROM Disc Path: \SAMPCODE\C\MSC60\SNAP.C
-
- /* Snap - An OS/2 screen capture utility
- *
- * Snap starts a background process containing a keyboard monitor.
- * The monitor checks for a hot key (ALT-*). If found, a thread is
- * launched to write the screen to a file. Various command line options
- * allow you to specify capture behavior or to deinstall the program.
- *
- * To compile, use the following command line:
- *
- * cl /MT /G2s snap.c
- */
-
- /* Function prototypes */
- int Monitor( void );
- void Snap( unsigned long _far *arg );
- void BackError( char *msgErr );
- void Syntax( void );
- void EvalOptions( int argc, char **argv );
-
- /* Define constants to enable function groups in OS2 include files */
- #define INCL_NOCOMMON
- #define INCL_NOPM
- #define INCL_KBD // KBDKEYINFO
- #define INCL_VIO // Vio functions
- #define INCL_DOSMEMMGR // DosGetShrSeg, DosAllocShrSeg,
- #define INCL_DOSMONITORS // DosMon functions
- #define INCL_DOSMISC // DosGetEnv
- #define INCL_DOSSEMAPHORES // DosSem functions
- #define INCL_DOSPROCESS // DosBeep, DosSetPrty
- #define INCL_DOSINFOSEG // DosGetInfoSeg
- #include <os2.h>
-
- #include <malloc.h> // malloc, free
- #include <process.h> // _beginthread, _endthread, exit, spawnl
- #include <string.h> // strcpy, strcat
- #include <stdlib.h> // atoi, itoa, _MAX_PATH
- #include <stddef.h> // _threadid variable
- #include <stdio.h> // puts, fopen, fwrite, etc.
- #include <conio.h> // kbhit
-
- #define CON 0 // Handle for the console device
- #define FAIL -1 // Fail to start thread
-
- #define STAR 0x37 // Scan code for * on numeric keypad
- #define RELEASE 0x40 // Bit mask for key release
-
- /* Name and structure for shared memory data */
- char szShrSeg[] = { "\\SHAREMEM\\SNAP.DAT" };
- struct SHARED
- {
- BOOL fSound; // Sound flag
- BOOL fAppend; // Append flag
- BOOL fInstall; // Install flag
- SHORT cScreen; // Count of screens
- LONG lfWait; // Wait semaphore
- CHAR achSnap[_MAX_PATH]; // Snap file name
- } _far *pshrSnap = 0; // Initialize offset to 0. Segment will
- // be initialized by system call.
-
- /* Count in bytes of shared segment */
- #define C_SHARESEG sizeof( struct SHARED )
-
- void main( int argc, char **argv )
- {
- USHORT offCmd; // Dummy for DosGetEnv
- CHAR *pchSnapExe = 0; // Pointer to name of executable file
- // (offset initialized to 0)
-
- /* Try to get shared segment (note how selector value is placed
- * directly in the segment word of the pointer address). There are
- * three possibilities:
- *
- * - We can't get memory. This means SNAP is not installed,
- * so we must allocate the memory and exec ourself in the
- * background to install the monitor.
- * - We can get memory and we are not installed. This means
- * we have been execed by previous process to install monitor.
- * - We can get memory and we are already installed. This means
- * we were just called to modify options.
- */
- if( DosGetShrSeg( szShrSeg, (PSEL)&pshrSnap + 1 ) )
- {
- /* Segment doesn't exist, so try to allocate it. */
- if( DosAllocShrSeg( C_SHARESEG, szShrSeg, (PSEL)&pshrSnap + 1 ) )
- {
- puts( "Can't allocate shared memory" );
- exit( 1 );
- }
- else
- {
- /* This is the first time through, so we must execute
- * ourself to do installation. First set defaults, then
- * modify for options.
- */
- pshrSnap->fSound = TRUE;
- pshrSnap->fAppend = TRUE;
- pshrSnap->cScreen = 0;
- pshrSnap->fInstall = FALSE;
- strcpy( pshrSnap->achSnap, "SNAP.IMG" );
- DosSemSet( &pshrSnap->lfWait );
- EvalOptions( argc, argv );
-
- /* Get our own path name from the end of the environment
- * segment. This is the most reliable way to get the full
- * path name of the current file, since the extension is
- * ommitted from argv[0].
- */
- DosGetEnv( (PUSHORT)&pchSnapExe + 1, &offCmd );
-
- /* Adjust forward until we point to full path of .EXE file. */
- while( *pchSnapExe++ || *pchSnapExe )
- ;
- ++pchSnapExe;
-
- /* Spawn ourself as a background process. Can't install
- * monitor now because we are in foreground. A background
- * process needs to install the monitor.
- */
- if( spawnl( P_DETACH, pchSnapExe, pchSnapExe, NULL ) == -1 )
- {
- puts( "Can't start background process" );
- exit( 1 );
- }
- puts( "Snap installed" );
- Syntax();
-
- /* Wait for background child process to report receiving
- * shared data.
- */
- DosSemWait( &pshrSnap->lfWait, SEM_INDEFINITE_WAIT );
- }
- }
- else
- {
- /* Already installed. We are being run to evaluate options and
- * modify behavior accordingly.
- */
- if( pshrSnap->fInstall )
- if( argc == 1 )
- puts( "Snap already installed" );
- else
- EvalOptions( argc, argv );
- else
- {
- /* Not installed, so we were execed by original SNAP to
- * install monitor. Tell parent we have received data, set
- * install flag, and install monitor.
- */
- DosSemClear( &pshrSnap->lfWait );
-
- /* Set installed flag and start monitor. */
- pshrSnap->fInstall = TRUE;
-
- exit( Monitor() );
- }
- }
- }
-
- /* Monitor routine checks keystrokes as they occur and calls
- * the Snap thread if the hot key is pressed.
- *
- * Params: None
- *
- * Return: 1 if error, 0 if deinstalled
- *
- * Uses: pshrSnap - Shared memory structure
- */
- int Monitor()
- {
- #define BUFSIZE 128 // Size for monitor buffers:
- // 64 minimum, 128 recommended
- #define STACKSIZE 2048 // 2K minimum for any system call
-
- PMONIN pmnin;
- PMONOUT pmnout;
-
- struct KEYPACKET // KBD monitor data record
- {
- USHORT fMon;
- KBDKEYINFO kki;
- USHORT fDD;
- } keyBuff;
- USHORT ckeyBuff = sizeof( keyBuff );
-
- HMONITOR hKeyMon; // Keyboard handle from monitor open
- PGINFOSEG pGIS = 0, pLIS = 0; // Information segment structures
- LONG lfSnap = FALSE; // Semaphore for each Snap thread
-
- /* Allocate space for monitor read/write buffers and mark size. */
- pmnin = (PMONIN)malloc( BUFSIZE );
- pmnin->cb = BUFSIZE;
- pmnout = (PMONOUT)malloc( BUFSIZE );
- pmnout->cb = BUFSIZE;
-
- /* Register monitor to the keyboard device (KBD$). */
- if( DosMonOpen( "KBD$", &hKeyMon ) )
- {
- BackError( "Can't open monitor" );
- return 1;
- }
-
- /* Get information segments (all we really need is ID of current
- * screen group from Global Information Segment).
- */
- DosGetInfoSeg( (PSEL)&pGIS + 1, (PSEL)&pLIS + 1 );
-
- /* Register the monitor buffers to the current screen group */
- if( DosMonReg( hKeyMon, (PBYTE)pmnin, (PBYTE)pmnout,
- MONITOR_DEFAULT, pGIS->sgCurrent ) )
- {
- BackError( "Can't register monitor" );
- return 1;
- }
-
- /* Make process time critical so keys are interpreted without delay. */
- DosSetPrty( PRTYS_PROCESS, PRTYC_TIMECRITICAL, 0, 0 );
-
- /* Monitor loop - read into monitor buffer and examine. Take action
- * if hot key, otherwise pass on to device driver.
- */
- while( pshrSnap->fInstall )
- {
- DosMonRead( (PBYTE)pmnin, IO_WAIT, (PBYTE)&keyBuff, &ckeyBuff );
-
- /* Snap if ALT+STAR is down. */
- if( ((keyBuff.kki.chScan == STAR) || (keyBuff.kki.chScan == 0x2a)) &&
- (keyBuff.kki.fsState & ALT) &&
- (!(keyBuff.fDD & RELEASE)) )
- {
- /* Make sure last thread is finished */
- DosSemWait( &lfSnap, SEM_INDEFINITE_WAIT );
- if( (_beginthread( Snap, NULL, STACKSIZE,
- (PVOID)&lfSnap )) == FAIL )
- BackError( "Can't start screen capture thread" );
- else
- DosSemSet( &lfSnap );
- }
- else
- /* Pass the key through if it is not the hot key */
- DosMonWrite( (PBYTE)pmnout, (PBYTE)&keyBuff, ckeyBuff );
- }
-
- /* Close monitor */
- free( pmnin );
- free( pmnout );
- DosMonClose( hKeyMon );
- return 0;
- }
-
- /* Screen capture routine (run as a thread). Does a pop-up to get access
- * to the current screen. Reads characters from the screen into a buffer.
- * Then filters trailing spaces as it writes buffer to a file.
- *
- * Params: plfSnap - pointer to flag indicated snap status
- *
- * Return: none
- *
- * Uses: pshrSnap - Shared memory structure
- */
- void Snap( ULONG _far *plfSnap )
- {
- enum { NOTE_B = 494, NOTE_C = 523, NOTE_F = 698 };
- CHAR *pchScreen; // Buffer for captured screen
- USHORT cbScreen; // Count of bytes in buffer
- FILE *sFile; // File stream
- USHORT usLine, usPos, usWidth;
- CHAR ach[5];
- USHORT fWait = VP_WAIT | VP_TRANSPARENT;
- VIOMODEINFO vmi = { sizeof( vmi ) };
-
- if( pshrSnap->fSound )
- DosBeep( NOTE_F, NOTE_C );
-
- /* Pop up to current screen and check its size. */
- VioPopUp( &fWait, CON );
- VioGetMode( &vmi, CON );
-
- /* Allocate memory for a full screen plus one byte */
- cbScreen = vmi.col * vmi.row;
- pchScreen = malloc( cbScreen + 1 );
-
- /* Read screen and end popup */
- VioReadCharStr( pchScreen, &cbScreen, 0, 0, CON );
- VioEndPopUp( 0 );
-
- /* Increment screen count (4 digits or less) and convert to string. */
- pshrSnap->cScreen = (pshrSnap->cScreen + 1) % 9999;
- itoa( pshrSnap->cScreen, ach, 10 );
-
- /* Make numbered file name if appropriate. */
- if( !pshrSnap->fAppend )
- strcat( strcat( strcpy( pshrSnap->achSnap, "SNAP" ), ach ), ".IMG" );
-
- /* Open file and write buffer to it a line at a time */
- if( (sFile = fopen( pshrSnap->achSnap, "at" )) == NULL )
- {
- BackError( "Can't open file" );
- --pshrSnap->cScreen;
- }
- else
- {
- if( pshrSnap->fAppend )
- {
- /* Not using fprintf reduces overhead. */
- fputs( "**** Screen ", sFile );
- fputs( ach, sFile );
- fputs( " ****\n", sFile );
- }
-
- for( usLine = 0, usPos = 0; usLine < vmi.row; usLine++ )
- {
- /* Throw away trailing spaces */
- for( usWidth = vmi.col;
- (pchScreen[usPos + usWidth - 1] == ' ' ) && usWidth;
- usWidth-- )
- ;
- /* Write line and newline */
- fwrite( pchScreen + usPos, 1, usWidth, sFile );
- fputc( '\n', sFile );
- usPos += vmi.col;
- }
- fclose( sFile );
- }
- if( pshrSnap->fSound )
- DosBeep( NOTE_C, NOTE_B );
-
- /* Free memory and let parent know we are done */
- free( pchScreen );
- DosSemClear( plfSnap );
- }
-
- /* Displays an error message from within a background process or thread.
- * The monitor is in the background and has no screen group, so it must
- * use VioPopUp to get access to the screen.
- *
- * Params: msgErr - error message string
- *
- * Return: None
- */
- void BackError( char *pchErr )
- {
- USHORT fWait = VP_WAIT | VP_TRANSPARENT;
-
- VioPopUp( &fWait, CON );
- puts( pchErr );
- puts( "Press any key to continue . . ." );
- while( !kbhit() )
- ;
- VioEndPopUp( CON );
- }
-
- /* Displays syntax.
- *
- * Params: None
- *
- * Return: None
- */
- void Syntax()
- {
- puts( "\nOptions: " );
- puts( "\t/H\t Display help." );
- puts( "\t/S\t Turn sound on (default)." );
- puts( "\t/Q\t Turn sound off." );
- puts( "\t/D\t Deinstall." );
- puts( "\t/A [path] Append each screen to a file (complete path allowed)."
- puts( "\t\t If no file given, default is SNAP.IMG in current directory"
- puts( "\t\t Resets screen number to 1." );
- puts( "\t/N [num] Create numbered file for each screen." );
- puts( "\t\t Example: SNAP1.IMG, SNAP2.IMG in current directory." );
- puts( "\t\t Resets screen number to 1 or to num if given." );
- }
-
- /* Evaluate command-line options.
- *
- * Params: argc - Number of arguments
- * argv - Pointer to argument list
- *
- * Return: none
- *
- * Uses: Shared memory structure - pshrSnap
- */
- void EvalOptions( int argc, char **argv )
- {
- SHORT i;
-
- /* Look for and handle arguments */
- for( i = 1; i < argc; i++ )
- {
- if( argv[i][0] == '/' || argv[i][0] == '-' )
- {
- switch( argv[i][1] )
- {
- case 'A':
- case 'a':
- pshrSnap->fAppend = TRUE;
- pshrSnap->cScreen = 0;
- if( (argv[++i]) &&
- (argv[i][0] != '/') &&
- (argv[i][0] != '-') )
-
- {
- strcpy( pshrSnap->achSnap, argv[i] );
- puts( "Append mode - name set" );
- }
- else
- puts( "Append mode" );
- break;
-
- case 'N':
- case 'n':
- pshrSnap->fAppend = FALSE;
- puts( "Numbered file mode" );
- if( (argv[++i]) &&
- (argv[i][0] != '/') &&
- (argv[i][0] != '-') )
- {
- pshrSnap->cScreen = (atoi( argv[i] ) % 9999) - 1;
- }
- else
- pshrSnap->cScreen = 0;
- break;
-
- case 'Q':
- case 'q':
- pshrSnap->fSound = FALSE;
- puts( "Sound off" );
- break;
-
- case 'S' :
- case 's' :
- pshrSnap->fSound = TRUE;
- puts( "Sound on" );
- break;
-
- case 'D':
- case 'd':
- if( pshrSnap->fInstall )
- {
- pshrSnap->fInstall = FALSE;
- puts( "Deinstalling" );
- }
- else
- exit( 0 );
- break;
-
- case 'H' :
- case 'h' :
- if( pshrSnap->fInstall )
- Syntax();
- break;
- }
- }
- }
- }
-
-
- SORTDEMO.C
- CD-ROM Disc Path: \SAMPCODE\C\MSC60\SORTDEMO.C
-
- /* SORTDEMO -This program graphically demonstrates six common sorting
- * algorithms. It prints 25 or 43 horizontal bars of different lengths
- * in random order, then sorts the bars from shortest to longest.
- * The program can beep to generate different pitches, depending on the
- * length and position of the bar.
- *
- * The program can be created for DOS or OS/2. To create for OS/2, define
- * the symbol OS2. Command lines for DOS and OS/2 are shown below:
- *
- * DOS:
- * cl /Lr sortdemo.c graphics.lib
- *
- * OS/2:
- * cl /Lp /DOS2 sortdemo.c grtextp.lib
- */
-
- #include <graph.h> // _outtext, _settextcolor, _settextposition
- #include <string.h> // strlen
- #include <stdio.h> // sprintf
- #include <conio.h> // getch
- #include <stdlib.h> // srand, rand, toupper
- #include <malloc.h> // malloc, free
- #include <time.h> // time, clock
-
- enum BOOL { FALSE, TRUE };
-
- /* Structure type for colored bars */
- typedef struct _BAR
- {
- char len;
- char clr;
- } BAR;
-
- /* Structure type for screen cells */
- typedef struct _CELL
- {
- char chChar;
- char chAttr;
- } CELL;
-
- /* Function prototypes */
- void main( void );
- void Cls( void );
- void InitMenu( void ); // Menu Functions
- void DrawFrame( int iTop, int Left, int Width, int Height );
- void RunMenu( void );
- void DrawTime( int iCurrentRow );
- void InitBars( void ); // Bar functions
- void ReInitBars( void );
- void DrawBar( int iRow );
- void SwapBars( int iRow1, int iRow2 );
- void Swaps( BAR *one, BAR *two );
- void InsertionSort( void ); // Sort functions
- void BubbleSort( void );
- void HeapSort( void );
- void PercolateUp( int iMaxLevel );
- void PercolateDown( int iMaxLevel );
- void ExchangeSort( void );
- void ShellSort( void );
- void QuickSort( int iLow, int iHigh );
- void Beep( int frequency, int duration );
- void Sleep( clock_t wait );
-
- /* Macro */
- #define GetRandom( min, max ) ((rand() % (int)(((max) + 1) - (min))) + (min))
- #define _outtextxy( ach, x, y ) { _settextposition( y, x ); \
- _outtext( ach ); }
-
- /* Constants */
- #define ESC 27
- #define BLANK 32
- #define BLOCK 223
- #define TOP 1
- #define FIRSTMENU (TOP + 6)
- #define LEFTCOLUMN 48
- #define PROMPTPOS 27
- #define WIDTH (80 - LEFTCOLUMN)
- #define HEIGHT (cszMenu + 2)
- #define MENUCOLOR 15
- #define BLANKCOLOR 7
- #define BACKCOLOR 0L
- #define PAUSELIMIT 900
-
- /* Global variables */
- clock_t clStart, clFinish, clPause = 30L;
- int fSound, iCurChoice, iSwaps, iCompares, cRow;
-
- BAR abarWork[43], abarPerm[43]; // Temporary and permanent sort arrays
-
- char *aszMenu[] =
- {
- "",
- " C Sorting Demo",
- "",
- " Time Swap Comp",
- "",
- "Insertion",
- "Bubble",
- "Heap",
- "Exchange",
- "Shell",
- "Quick",
- "",
- "Toggle Sound: ",
- "",
- "Pause Factor: ",
- "< (Slower)",
- "> (Faster)",
- "",
- "Type first character of",
- "choice ( I B H E S Q T < > )",
- "or ESC key to end program: "
- "",
- };
- int cszMenu = sizeof( aszMenu ) / sizeof( aszMenu[0] );
-
- void main()
- {
- cRow = _settextrows( 43 );
- _clearscreen( _GCLEARSCREEN );
- _displaycursor( _GCURSOROFF );
- InitBars();
- InitMenu();
- RunMenu(); // Respond to menu until quit
- _setvideomode( _DEFAULTMODE );
- }
-
-
- /* InitMenu - Calls the DrawFrame procedure to draw the frame around the
- * sort menu, then prints the different options stored in the menu array.
- */
- void InitMenu()
- {
- int i;
- char ach[15];
-
- _settextcolor( MENUCOLOR );
- _setbkcolor( BACKCOLOR );
- DrawFrame( TOP, LEFTCOLUMN - 3, WIDTH + 3, HEIGHT );
- for( i = 0; i < cszMenu; i++ )
- _outtextxy( aszMenu[i], LEFTCOLUMN, TOP + i + 1 );
-
- /* Print the current value for Sound. */
- if( fSound )
- strcpy( ach, "ON " );
- else
- strcpy( ach, "OFF" );
-
- _outtextxy( ach, LEFTCOLUMN + 14, cszMenu - 7 );
- sprintf( ach, "%3.3u", clPause / 30 );
- _outtextxy( ach, LEFTCOLUMN + 14, cszMenu - 5 );
-
- /* Erase the speed option if the length of the pause is at a limit. */
- strcpy( ach, " " );
- if( clPause == PAUSELIMIT )
- _outtextxy( ach, LEFTCOLUMN, cszMenu - 4 );
- if( clPause == 0L )
- _outtextxy( ach, LEFTCOLUMN, cszMenu - 3 );
- }
-
-
- /* DrawFrame - Draws a rectangular frame using the double-line box
- * characters. The parameters iTop, iLeft, iWidth, and iHeight are
- * the row and column arguments for the upper-left and lower-right
- * corners of the frame.
- */
- void DrawFrame( int iTop, int iLeft, int iWidth, int iHeight )
- {
- enum { ULEFT = 201, URIGHT = 187,
- LLEFT = 200, LRIGHT = 188, VERTICAL = 186, HORIZONTAL = 205
- };
- int iRow;
- char achTmp[80];
-
- memset( achTmp, HORIZONTAL, iWidth );
- achTmp[0] = ULEFT;
- achTmp[iWidth - 1] = URIGHT;
- achTmp[iWidth] = '\0';
- _outtextxy( achTmp, iLeft, iTop );
-
- memset( achTmp, BLANK, iWidth );
- achTmp[0] = VERTICAL;
- achTmp[iWidth - 1] = VERTICAL;
- for( iRow = iTop + 1; iRow <= iHeight; iRow++ )
- _outtextxy( achTmp, iLeft, iRow );
-
- memset( achTmp, HORIZONTAL, iWidth );
- achTmp[0] = LLEFT;
- achTmp[iWidth - 1] = LRIGHT;
- _outtextxy( achTmp, iLeft, iTop + iHeight );
- }
-
-
- /* RunMenu - The RunMenu procedure first calls the ReInitBars
- * procedure to make sure the abarWork is in its unsorted form, then
- * prompts the user to make one of the following choices:
- *
- * - Run one of the sorting algorithms
- * - Toggle sound on or off
- * - Increase or decrease speed
- * - End the program
- */
- void RunMenu()
- {
- char ch;
-
- while( TRUE )
- {
- iSwaps = iCompares = 0;
- _settextposition( TOP + cszMenu, LEFTCOLUMN + PROMPTPOS );
- _displaycursor( _GCURSORON );
- ch = getch();
- _displaycursor( _GCURSOROFF );
-
- /* Branch to the appropriate procedure depending on the key. */
- switch( toupper( ch ) )
- {
- case 'I':
- iCurChoice = 0;
- ReInitBars();
- InsertionSort();
- DrawTime( 0 ); // Print final time
- break;
- case 'B':
- iCurChoice = 1;
- ReInitBars();
- BubbleSort();
- DrawTime( 0 );
- break;
-
- case 'H':
- iCurChoice = 2;
- ReInitBars();
- HeapSort();
- DrawTime( 0 );
- break;
-
- case 'E':
- iCurChoice = 3;
- ReInitBars();
- ExchangeSort();
- DrawTime( 0 );
- break;
-
- case 'S':
- iCurChoice = 4;
- ReInitBars();
- ShellSort();
- DrawTime( 0 );
- break;
-
- case 'Q':
- iCurChoice = 5;
- ReInitBars();
- QuickSort( 0, cRow );
- DrawTime( 0 );
- break;
-
- case '>':
- /* Decrease pause length to speed up sorting time, then
- * redraw the menu to clear any timing results (since
- * they won't compare with future results).
- */
- if( clPause )
- clPause -= 30L;
- InitMenu();
- break;
-
- case '<':
- /* Increase pause length to slow down sorting time. */
- if( clPause <= 900L )
- clPause += 30L;
- InitMenu();
- break;
-
- case 'T':
- fSound = !fSound;
- InitMenu();
- break;
-
- case ESC:
- return;
-
- default: // Unknown key ignored
- break;
- }
- }
- }
-
-
- /* DrawTime - Prints seconds elapsed since the given sorting routine
- * started. Note that this time includes both the time it takes to redraw
- * the bars plus the pause while Beep plays a note, and thus is not an
- * accurate indication of sorting speed.
- */
- void DrawTime( int iCurrentRow )
- {
- char achTiming[80];
-
- _settextcolor( MENUCOLOR );
- clFinish = clock();
-
- sprintf( achTiming, "%7.2f %4.i %4.i",
- (float)(clFinish - clStart) / CLOCKS_PER_SEC,
- iSwaps, iCompares );
-
- /* Print the number of seconds elapsed */
- _outtextxy( achTiming, LEFTCOLUMN + 11, FIRSTMENU + iCurChoice );
- if( fSound )
- {
- Beep( 60 * iCurrentRow, 75 ); // Play note
- Sleep( clPause - 75L ); // Pause adjusted for note duration
- }
- else
- Sleep( clPause ); // Pause
- }
-
-
- /* InitBars - Initializes the bar arrays and the menu box.
- */
- void InitBars()
- {
- struct videoconfig vc;
- int aTemp[43], iRow, iRowMax, iRand, iColorMax, iLength;
-
- /* Seed the random-number generator. */
- srand( (unsigned)time( NULL ) );
- fSound = TRUE;
- clPause = 30L;
-
- /* If monochrome or color burst disabled, use one color */
- _getvideoconfig( &vc );
- if( (vc.monitor == _MONO) || (vc.mode == _TEXTBW80) ||
- (vc.mode == _TEXTBW40) )
- iColorMax = 1;
- else
- iColorMax = 15;
-
- /* Randomize an array of rows. */
- for( iRow = 0; iRow < cRow; iRow++ )
- aTemp[iRow] = iRow + 1;
- iRowMax = cRow - 1;
- for( iRow = 0; iRow < cRow; iRow++ )
- {
- /* Find a random element in aTemp between 0 and iRowMax,
- * then assign the value in that element to iLength.
- */
- iRand = GetRandom( 0, iRowMax );
- iLength = aTemp[iRand];
-
- /* Overwrite the value in aTemp[iRand] with the value in
- * aTemp[iRowMax] so the value in aTemp[iRand] is
- * chosen only once.
- */
- aTemp[iRand] = aTemp[iRowMax];
-
- /* Decrease the value of iRowMax so that aTemp[iRowMax] can't
- * be chosen on the next pass through the loop.
- */
- --iRowMax;
- abarPerm[iRow].len = iLength;
- if( iColorMax == 1 )
- abarPerm[iRow].clr = BLANKCOLOR;
- else
- abarPerm[iRow].clr = iLength % iColorMax + 1;
- }
-
- /* Assign permanent sort values to temporary and draw unsorted bars. */
- ReInitBars();
- }
-
-
- /* ReInitBars - Restores the array abarWork to its original unsorted
- * state and draws the unsorted bars.
- */
- void ReInitBars()
- {
- int iRow;
-
- clStart = clock();
- for( iRow = 0; iRow < cRow; iRow++ )
- {
- abarWork[iRow] = abarPerm[iRow];
- DrawBar( iRow );
- }
- }
-
-
- /* DrawBar - Prints a bar at a specified row by first blanking the
- * old bar, then drawing a new bar having the length and color given in
- * the work array.
- */
- void DrawBar( int iRow )
- {
- int cSpace;
- char achT[43];
-
- memset( achT, BLOCK, abarWork[iRow].len );
- cSpace = cRow - abarWork[iRow].len;
- memset( achT + abarWork[iRow].len, ' ', cSpace );
- achT[cRow] = '\0';
- _settextcolor( abarWork[iRow].clr );
- _outtextxy( achT, 0, iRow + 1 );
- }
-
-
- /* SwapBars - Calls DrawBar twice to switch the two bars in iRow1 and
- * iRow2, then calls DrawTime to update the time.
- */
- void SwapBars( int iRow1, int iRow2 )
- {
- DrawBar( iRow1 );
- DrawBar( iRow2 );
- DrawTime( iRow1 );
- }
-
-
- /* Swaps - Exchanges two bar structures.
- */
- void Swaps( BAR *bar1, BAR *bar2 )
- {
- BAR barTmp;
-
- ++iSwaps;
- barTmp = *bar1;
- *bar1 = *bar2;
- *bar2 = barTmp;
- }
-
-
- /* InsertionSort - InsertionSort compares the length of each element
- * with the lengths of all the preceding elements. When the appropriate
- * place for the new element is found, the element is inserted and
- * all the other elements are moved down one place.
- */
- void InsertionSort()
- {
- BAR barTemp;
- int iRow, iRowTmp, iLength;
-
- /* Start at the top. */
- for( iRow = 0; iRow < cRow; iRow++ )
- {
- barTemp = abarWork[iRow];
- iLength = barTemp.len;
-
- /* As long as the length of the temporary element is greater than
- * the length of the original, keep shifting the elements down.
- */
- for( iRowTmp = iRow; iRowTmp; iRowTmp-- )
- {
- iCompares++;
- if( abarWork[iRowTmp - 1].len > iLength )
- {
- ++iSwaps;
- abarWork[iRowTmp] = abarWork[iRowTmp - 1];
- DrawBar( iRowTmp ); // Print the new bar
- DrawTime( iRowTmp ); // Print the elapsed time
-
- }
- else // Otherwise, exit
- break;
- }
-
- /* Insert the original bar in the temporary position. */
- abarWork[iRowTmp] = barTemp;
- DrawBar( iRowTmp );
- DrawTime( iRowTmp );
- }
- }
-
-
- /* BubbleSort - BubbleSort cycles through the elements, comparing
- * adjacent elements and swapping pairs that are out of order. It
- * continues to do this until no out-of-order pairs are found.
- */
- void BubbleSort()
- {
- int iRow, iSwitch, iLimit = cRow;
-
- /* Move the longest bar down to the bottom until all are in order. */
- do
- {
- iSwitch = 0;
- for( iRow = 0; iRow < iLimit; iRow++ )
- {
- /* If two adjacent elements are out of order, swap their values
- * and redraw those two bars.
- */
- iCompares++;
- if( abarWork[iRow].len > abarWork[iRow + 1].len )
- {
- Swaps( &abarWork[iRow], &abarWork[iRow + 1] );
- SwapBars( iRow, iRow + 1 );
- iSwitch = iRow;
- }
- }
-
- /* Sort on next pass only to where the last switch was made. */
- iLimit = iSwitch;
- } while( iSwitch );
- }
-
-
- /* HeapSort - HeapSort (also called TreeSort) works by calling
- * PercolateUp and PercolateDown. PercolateUp organizes the elements
- * into a "heap" or "tree," which has the properties shown below:
- *
- * element[1]
- * / \
- * element[2] element[3]
- * / \ / \
- * element[4] element[5] element[6] element[7]
- * / \ / \ / \ / \
- * ... ... ... ... ... ... ... ...
- *
- *
- * Each "parent node" is greater than each of its "child nodes"; for
- * example, element[1] is greater than element[2] or element[3];
- * element[4] is greater than element[5] or element[6], and so forth.
- * Therefore, once the first loop in HeapSort is finished, the
- * largest element is in element[1].
- *
- * The second loop rebuilds the heap (with PercolateDown), but starts
- * at the top and works down, moving the largest elements to the bottom.
- * This has the effect of moving the smallest elements to the top and
- * sorting the heap.
- */
- void HeapSort()
- {
- int i;
-
- for( i = 1; i < cRow; i++ )
- PercolateUp( i );
-
- for( i = cRow - 1; i > 0; i-- )
- {
- Swaps( &abarWork[0], &abarWork[i] );
- SwapBars( 0, i );
- PercolateDown( i - 1 );
- }
- }
-
-
- /* PercolateUp - Converts elements into a "heap" with the largest
- * element at the top (see the diagram above).
- */
- void PercolateUp( int iMaxLevel )
- {
- int i = iMaxLevel, iParent;
-
- /* Move the value in abarWork[iMaxLevel] up the heap until it has
- * reached its proper node (that is, until it is greater than either
- * of its child nodes, or until it has reached 1, the top of the heap).
- */
- while( i )
- {
- iParent = i / 2; // Get the subscript for the parent node
-
- iCompares++;
- if( abarWork[i].len > abarWork[iParent].len )
- {
- /* The value at the current node is bigger than the value at
- * its parent node, so swap these two array elements.
- */
- Swaps( &abarWork[iParent], &abarWork[i] );
- SwapBars( iParent, i );
- i = iParent;
- }
- else
- /* Otherwise, the element has reached its proper place in the
- * heap, so exit this procedure.
- */
- break;
- }
- }
-
-
- /* PercolateDown - Converts elements to a "heap" with the largest elements
- * at the bottom. When this is done to a reversed heap (largest elements
- * at top), it has the effect of sorting the elements.
- */
- void PercolateDown( int iMaxLevel )
- {
- int iChild, i = 0;
-
- /* Move the value in abarWork[0] down the heap until it has reached
- * its proper node (that is, until it is less than its parent node
- * or until it has reached iMaxLevel, the bottom of the current heap).
- */
- while( TRUE )
- {
- /* Get the subscript for the child node. */
- iChild = 2 * i;
-
- /* Reached the bottom of the heap, so exit this procedure. */
- if( iChild > iMaxLevel )
- break;
-
- /* If there are two child nodes, find out which one is bigger. */
- if( iChild + 1 <= iMaxLevel )
- {
- iCompares++;
- if( abarWork[iChild + 1].len > abarWork[iChild].len )
- iChild++;
- }
-
- iCompares++;
- if( abarWork[i].len < abarWork[iChild].len )
- {
- /* Move the value down since it is still not bigger than
- * either one of its children.
- */
- Swaps( &abarWork[i], &abarWork[iChild] );
- SwapBars( i, iChild );
- i = iChild;
- }
- else
- /* Otherwise, abarWork has been restored to a heap from 1 to
- * iMaxLevel, so exit.
- */
- break;
- }
- }
-
-
- /* ExchangeSort - The ExchangeSort compares each element--starting with
- * the first--with every following element. If any of the following
- * elements is smaller than the current element, it is exchanged with
- * the current element and the process is repeated for the next element.
- */
- void ExchangeSort()
- {
- int iRowCur, iRowMin, iRowNext;
-
- for( iRowCur = 0; iRowCur < cRow; iRowCur++ )
- {
- iRowMin = iRowCur;
- for( iRowNext = iRowCur; iRowNext < cRow; iRowNext++ )
- {
- iCompares++;
- if( abarWork[iRowNext].len < abarWork[iRowMin].len )
- {
- iRowMin = iRowNext;
- DrawTime( iRowNext );
- }
- }
-
- /* If a row is shorter than the current row, swap those two
- * array elements.
- */
- if( iRowMin > iRowCur )
- {
- Swaps( &abarWork[iRowCur], &abarWork[iRowMin] );
- SwapBars( iRowCur, iRowMin );
- }
- }
- }
-
-
- /* ShellSort - ShellSort is similar to the BubbleSort. However, it
- * begins by comparing elements that are far apart (separated by the
- * value of the iOffset variable, which is initially half the distance
- * between the first and last element), then comparing elements that
- * are closer together. When iOffset is one, the last iteration of
- * is merely a bubble sort.
- */
- void ShellSort()
- {
- int iOffset, iSwitch, iLimit, iRow;
-
- /* Set comparison offset to half the number of bars. */
- iOffset = cRow / 2;
-
- while( iOffset )
- {
- /* Loop until offset gets to zero. */
- iLimit = cRow - iOffset;
- do
- {
- iSwitch = FALSE; // Assume no switches at this offset.
-
- /* Compare elements and switch ones out of order. */
- for( iRow = 0; iRow <= iLimit; iRow++ )
- {
- iCompares++;
- if( abarWork[iRow].len > abarWork[iRow + iOffset].len )
- {
- Swaps( &abarWork[iRow], &abarWork[iRow + iOffset] );
- SwapBars( iRow, iRow + iOffset );
- iSwitch = iRow;
- }
- }
-
- /* Sort on next pass only to where last switch was made. */
- iLimit = iSwitch - iOffset;
- } while( iSwitch );
-
- /* No switches at last offset, try one half as big. */
- iOffset = iOffset / 2;
- }
- }
-
-
- /* QuickSort - QuickSort works by picking a random "pivot" element,
- * then moving every element that is bigger to one side of the pivot,
- * and every element that is smaller to the other side. QuickSort is
- * then called recursively with the two subdivisions created by the pivot.
- * Once the number of elements in a subdivision reaches two, the recursive
- * calls end and the array is sorted.
- */
- void QuickSort( int iLow, int iHigh )
- {
- int iUp, iDown, iBreak;
-
- if( iLow < iHigh )
- {
- /* Only two elements in this subdivision; swap them if they are
- * out of order, then end recursive calls.
- */
- if( (iHigh - iLow) == 1 )
- {
- iCompares++;
- if( abarWork[iLow].len > abarWork[iHigh].len )
- {
- Swaps( &abarWork[iLow], &abarWork[iHigh] );
- SwapBars( iLow, iHigh );
- }
- }
- else
- {
- iBreak = abarWork[iHigh].len;
- do
- {
- /* Move in from both sides towards the pivot element. */
- iUp = iLow;
- iDown = iHigh;
- iCompares++;
- while( (iUp < iDown) && (abarWork[iUp].len <= iBreak) )
- iUp++;
- iCompares++;
- while( (iDown > iUp) && (abarWork[iDown].len >= iBreak) )
- iDown--;
- /* If we haven't reached the pivot, it means that two
- * elements on either side are out of order, so swap them.
- */
- if( iUp < iDown )
- {
- Swaps( &abarWork[iUp], &abarWork[iDown] );
- SwapBars( iUp, iDown );
- }
- } while ( iUp < iDown );
-
- /* Move pivot element back to its proper place in the array. */
- Swaps( &abarWork[iUp], &abarWork[iHigh] );
- SwapBars( iUp, iHigh );
-
- /* Recursively call the QuickSort procedure (pass the smaller
- * subdivision first to use less stack space).
- */
- if( (iUp - iLow) < (iHigh - iUp) )
- {
- QuickSort( iLow, iUp - 1 );
- QuickSort( iUp + 1, iHigh );
- }
- else
- {
- QuickSort( iUp + 1, iHigh );
- QuickSort( iLow, iUp - 1 );
- }
- }
- }
- }
-
- /* Beep - Sounds the speaker for a time specified in microseconds by
- * duration at a pitch specified in hertz by frequency.
- */
- void Beep( int frequency, int duration )
- {
- /* Use system call for OS/2 */
- #if defined( OS2 )
- #define INCL_NOCOMMON
- #define INCL_NOPM
- #define INCL_DOSPROCESS
- #include <os2.h>
- DosBeep( frequency, duration );
- #else
- /* Define procedure for DOS */
- int control;
-
- /* If frequency is 0, Beep doesn't try to make a sound. It
- * just sleeps for the duration.
- */
- if( frequency )
- {
- /* 75 is about the shortest reliable duration of a sound. */
- if( duration < 75 )
- duration = 75;
-
- /* Prepare timer by sending 10111100 to port 43. */
- outp( 0x43, 0xb6 );
-
- /* Divide input frequency by timer ticks per second and
- * write (byte by byte) to timer.
- */
- frequency = (unsigned)(1193180L / frequency);
- outp( 0x42, (char)frequency );
- outp( 0x42, (char)(frequency >> 8) );
-
- /* Save speaker control byte. */
- control = inp( 0x61 );
-
- /* Turn on the speaker (with bits 0 and 1). */
- outp( 0x61, control | 0x3 );
- }
-
- Sleep( (clock_t)duration );
-
- /* Turn speaker back on if necessary. */
- if( frequency )
- outp( 0x61, control );
-
- /* DOS version */
- }
-
- /* Pauses for a specified number of microseconds. */
- void Sleep( clock_t wait )
- {
- clock_t goal;
-
- goal = wait + clock();
- while( goal >= clock() )
- ;
- }
-
-
- TURTLE.C
- CD-ROM Disc Path: \SAMPCODE\C\MSC60\TURTLE.C
-
- /* TURTLE - Module of functions to implement turtle graphics. Turtle graphics
- * is a model for specifying relative movements of an imaginary pointer whose
- * direction, color, visibility, and other attributes are given default
- * values using turtle functions. To use the turtle module, include TURTLE.H
- * in your program. The following functions (many defined as macros)
- * are public :
- *
- * InitTurtle - Initiate turtle graphics
- * Home - Reset turtle defaults
- * PenDown - Set pen visibility
- * SetFill - Set fill state
- * PenColor - Set pen color index
- * BorderColor - Set border color index
- * Turn - Set direction relative to current
- * TurnTo - Set absolute direction
- * Move - Move in current direction
- * MoveTo - Move to absolute location
- * Poly - Draw a polygon
- * Circle - Draw a circle with center at current location
- * Ellipse - Draw an ellipse with center at current location
- * Rectangle - Draw a rectangle with center at current location
- * ImageSize - Get size of rectangle with top-left origin
- * GetImage - Get rectangular image with top-left origin
- * PutImage - Put rectangular image with top-left origin
- * FillIn - Fill from the current location to border
- * NextColorIndex - Rotate to next color index
- * NextColorValue - Rotate to next color value
- * OnScreen - Report whether current location is on screen
- * RGB - Combine Red, Green, and Blue elements of color value
- *
- * The TURTLE structure, the "tc" global variable (having TURTLE type), and
- * "vlColors" variable are defined. However, these are not normally used
- * directly by the programmer.
- */
-
- #include <graph.h>
- #include <math.h>
- #include <string.h>
- #include "turtle.h"
-
- #define PI 3.141593
-
- long cvlColors[256]; /* Array of long color values */
-
- TURTLE tc = { 1.39 }; /* Initial aspect - adjust for your screen */
-
- /* InitTurtle - Initializes all turtle defaults. This function should be
- * called at least once (after _setvideomode and _getvideoconfig) and
- * additionally after any change to a new graphics mode.
- *
- * Params: vc - pointer to videoconfig structure
- *
- * Return: 0 if fail, 1 if success
- *
- * Uses: tc structure variable cvlColors array
- */
- short InitTurtle( struct videoconfig *vc )
- {
- int i;
- unsigned cvuInc, cvuRed, cvuGreen, cvuBlue; /* Unsigned portions of */
- static int mode = -1; /* color values */
-
- /* Terminate if not graphics mode. */
- if( !vc->numxpixels )
- return 0;
-
- /* If mode has changed, set window coordinates. */
- if( mode != vc->mode )
- {
- mode = vc->mode;
- tc.xsLeft = tc.ysTop = 0;
- tc.xsRight = vc->numxpixels - 1;
- tc.ysBot = vc->numypixels - 1;
- }
-
- /* Set palette flag. */
- switch( vc->adapter )
- {
- case _MDPA:
- case _CGA:
- case _OCGA:
- case _HGC:
- tc.fPalette = FALSE;
- break;
- default:
- tc.fPalette = TRUE;
- break;
- }
-
- /* Set palette defaults. */
- switch( vc->mode )
- {
- case _HRESBW:
- case _HERCMONO:
- case _ERESNOCOLOR:
- case _ORESCOLOR:
- case _VRES2COLOR:
- tc.ccv = 0;
- tc.cci = 2;
- return Home();
- case _MRES256COLOR: /* Active bits in this order: */
- cvuInc = 12;
- tc.ccv = tc.cci = 125; /* ???????? ??bbbbbb ??gggggg ??rrrrrr */
- break;
- case _ERESCOLOR:
- if( vc->memory == 64 )
- {
- cvuInc = 32;
- tc.ccv = 16; /* ???????? ??????Bb ??????Gg ??????Rr */
- tc.cci = 4;
- break;
- } /* Else fall through */
- case _VRES16COLOR:
- cvuInc = 16;
- tc.ccv = 64; /* ???????? ??????bb ??????gg ??????rr */
- tc.cci = 16;
- break;
- case _MRES4COLOR:
- case _MRESNOCOLOR:
- cvuInc = 32;
- tc.ccv = 16; /* ???????? ??????Bb ??????Gg ??????Rr */
- tc.cci = 4;
- break;
- case _MRES16COLOR:
- case _HRES16COLOR:
- cvuInc = 32;
- tc.cci = tc.ccv = 16; /* ???????? ??????Bb ??????Gg ??????Rr */
- break;
- }
-
- /* Fill palette arrays. */
- for( i = 0, cvuBlue = 0; cvuBlue < 64; cvuBlue += cvuInc )
- for( cvuGreen = 0; cvuGreen < 64; cvuGreen += cvuInc )
- for( cvuRed = 0; cvuRed < 64; cvuRed += cvuInc )
- {
- cvlColors[i] = RGB( cvuRed, cvuGreen, cvuBlue );
- /* Special case of 6 bits for 16 colors (RGBI).
- * If both bits are on for any color, intensity is set.
- * If one bit is set for a color, that color is on.
- */
- if( cvuInc == 32 )
- cvlColors[i + 8] = cvlColors[i] | (cvlColors[i] >> 1)
- i++;
- }
- cvlColors[tc.ccv - 1] = _BRIGHTWHITE;
- NextColorValue( DEFAULT );
- return Home();
- }
-
- /* Home - Resets turtle defaults. This function can be called if you have
- * not changed the video mode, but you want to put the turtle back in
- * the center of the window and restore all defaults. For example, you can
- * change the absolute window corners and then call it to set a new
- * turtle window.
- *
- * Params: None
- *
- * Return: 0 if fail, 1 if success
- *
- * Uses: tc
- */
- short Home()
- {
- struct _wxycoord xy1, xy2;
-
- _setviewport( tc.xsLeft, tc.ysTop, tc.xsRight, tc.ysBot );
-
- /* Set the window based on screen height 1000 and width based on
- * aspect ratio.
- */
- tc.yMax = 500.0;
- tc.xMax = tc.yMax * tc.yxRatio;
- if( !_setwindow( FALSE, -tc.xMax, -tc.yMax, tc.xMax, tc.yMax ) )
- return 0;
-
- /* Calculate the unit size of 1 pixel using Y axis. */
- xy1 = _getwindowcoord( 1, 1 );
- xy2 = _getwindowcoord( 1, 2 );
- tc.yUnit = xy2.wy - xy1.wy;
-
- /* Set defaults for current pixel, angle, pen state and fill state. */
- tc.xCur = tc.yCur = 0.0;
- _moveto_w( tc.xCur, tc.yCur );
- TurnTo( 0 );
- PenDown( TRUE );
- SetFill( FALSE );
-
- /* Make white the last color index and set pen and border to it. */
- _remappalette( WHITE, _BRIGHTWHITE );
- BorderColor( WHITE );
- PenColor( WHITE );
- _setbkcolor( _BLACK );
- return 1;
- }
-
- /* PenDown - Sets the visibility of the pen used by Move and MoveTo. The
- * state can be TRUE (visible), FALSE (invisible), or DEFAULT (return
- * current without changing).
- *
- * Params: fPenDown
- *
- * Return: current pen state
- *
- * Uses: tc
- */
- int PenDown( int fPenDown )
- {
- switch( fPenDown )
- {
- case DEFAULT:
- break;
- case FALSE:
- tc.fPenDown = FALSE;
- break;
- default:
- tc.fPenDown = TRUE;
- break;
- }
- return tc.fPenDown;
- }
-
- /* SetFill - Determines the state of filling figures such as Rectangle,
- * Circle, and Ellipse. State can be TRUE (fill inside), FALSE (border
- * only), or DEFAULT (return current fill state).
- *
- * Params: fFill
- *
- * Return: current fill state
- *
- * Uses: tc
- */
- short SetFill( short fFill )
- {
- switch( fFill )
- {
- case DEFAULT:
- break;
- case _GBORDER:
- case FALSE:
- tc.fFill = _GBORDER;
- break;
- default:
- tc.fFill = _GFILLINTERIOR;
- break;
- }
- return tc.fFill;
- }
-
- /* PenColor - Sets the color index of the pen.
- *
- * Params: ciCur - any color index of DEFAULT to return without changing
- *
- * Return: current pen color index
- *
- * Uses: tc
- */
- short PenColor( short ciCur )
- {
- if( ciCur != DEFAULT )
- _setcolor( tc.ciCur = ciCur );
- return tc.ciCur;
- }
-
- /* BorderColor - Sets the color index of the border that will be recognized
- * by fills.
- *
- * Params: ciBorder - any color index of DEFAULT to return without changing
- *
- * Return: current border color index
- *
- * Uses: tc
- */
- short BorderColor( short border )
- {
- if( border != DEFAULT )
- tc.ciBorder = border;
- return tc.ciBorder;
- }
-
- /* Turn - Sets a new direction relative to the current direction.
- *
- * Params: angCur - a positive (clockwise) or negative (counterclockwise)
- * angle in degrees
- *
- * Return: new current absolute angle
- *
- * Uses: tc
- */
- short Turn( short angCur )
- {
- return( tc.angCur = ((tc.angCur + angCur) % CIRCUMFERENCE) );
- }
-
- /* TurnTo - Sets a new absolute direction.
- *
- * Params: angCur - a positive (clockwise) or negative (counterclockwise)
- * angle in degrees (0 points to 12 o'clock)
- *
- * Return: new current absolute angle
- *
- * Uses: tc
- */
- short TurnTo( short angCur )
- {
- if( angCur < 0 )
- return( tc.angCur = 360 - (angCur % CIRCUMFERENCE) );
- else
- return( tc.angCur = angCur % CIRCUMFERENCE );
- }
-
- /* Move - Moves from the current position in the current direction for a
- * specified distance. A line is drawn if the pen is down. The current
- * position is reset to the destination.
- *
- * Params: dxy - difference between current xy and new xy
- *
- * Return: 0 if new position is off screen, nonzero if on screen
- *
- * Uses: tc
- */
- short Move( double dxy )
- {
- double dx, dy; /* Differences of X and Y */
- double angT;
-
- /* Calculate new X and Y positions. */
- angT = (tc.angCur - 90) * (PI / HALFCIRCUMFERENCE);
- dx = dxy * cos( angT );
- dy = dxy * sin( angT );
-
- /* Move, drawing if pen down, then update position */
- if( tc.fPenDown )
- _lineto_w( tc.xCur + dx, tc.yCur + dy );
- else
- _moveto_w( tc.xCur + dx, tc.yCur + dy );
- tc.xCur += dx;
- tc.yCur += dy;
- return OnScreen();
- }
-
- /* MoveTo - Moves from the current position to a specified position. A
- * line is drawn if the pen is down. The current position is reset to the
- * destination. The current direction is not changed.
- *
- * Params: x and y - destination position
- *
- * Return: 0 if new position is off screen, nonzero if on screen
- *
- * Uses: tc
- */
- short MoveTo( double x, double y )
- {
- if( tc.fPenDown )
- _lineto_w( x, y );
- else
- _moveto_w( x, y );
- tc.xCur = x;
- tc.yCur = y;
- return OnScreen();
- }
-
- /* Poly - Draws a polygon.
- *
- * Params: cSide - count of polygon sides
- * dxySide - distance of each side
- *
- * Return: 0 if any part of polygon is off screen, nonzero if on screen
- */
- short Poly( int cSide, double dxySide )
- {
- short i, angT, fPen, ret = TRUE;
-
- /* Make sure pen is down (restore pen state when done). */
- fPen = PenDown( TRUE );
-
- /* Calculate angle, then draw each side. */
- angT = 360 / cSide;
- for( i = 1; i <= cSide; i++ )
- {
- ret = Move( dxySide ) && ret;
- Turn( angT );
- }
- PenDown( fPen );
- return ret;
- }
-
- /* NextColorIndex - Rotate to next color index. First attribute (normally
- * background) and last attribute (white) are skipped.
- *
- * Params: ciCur - Specify DEFAULT to use color index from last call,
- * or specify a new color to rotate from
- *
- * Return: rotated color index
- *
- * Uses: tc
- */
- short NextColorIndex( short ciCur )
- {
- static short ciPrev = 0; /* Static to retain index between calls */
-
- /* Assign new current if given. */
- if( ciCur != DEFAULT )
- ciPrev = ciCur;
-
- /* Toggle for two-color modes, rotate for multi-color modes. */
- if( tc.cci == 2 )
- return( ciPrev = !ciPrev );
- else
- return( ciPrev = (++ciPrev % (tc.cci - 1)) );
- }
-
- /* NextColorValue - Rotate to next color value for adapters (EGA
- * and higher) that support remappable palettes.
- *
- * Params: fAction - DEFAULT (rotate all) or LIMITED (rotate first 14 only)
- *
- * Return: None
- *
- * Uses: tc
- */
- void NextColorValue( int fAction )
- {
- static int icvCur = 1; /* Current index into color value array */
- static int ciCur = 1; /* Current color index */
- int icvT; /* Temporary index into color values */
- int i;
-
- /* Ignore modes with no palette values. */
- if( !tc.fPalette || !tc.ccv )
- return;
-
- /* Increment and rotate color value index. */
- icvT = (++icvCur % (tc.ccv - 2)) + 1;
-
-
- /* DEFAULT - Remap all color indexes, 14 at a time. For most modes,
- * this is all the indexes except first and last. For 256-color
- * mode, rotating all available indexes would be too slow.
- */
- if( fAction == DEFAULT )
- for( i = 1; i <= 14; i++ )
- _remappalette( (ciCur++ % (tc.cci - 2)) + 1,
- cvlColors[(icvT++ % (tc.ccv - 2)) + 1] );
-
- /* LIMITED - Rotate only the first 14 color indexes. */
- else
- for( i = 1; i <= 14; i++ )
- _remappalette( i, cvlColors[(icvT++ % (tc.ccv - 1)) + 1] );
- }
- Microsoft Quick-C Sample Code
-
-
- ARGV.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\ARGV.C
-
- /* ARGV.C: Demonstrate accessing command-line arguments. */
- #include <stdio.h>
-
- void show_args( char *argument );
-
- int main( int argc, char *argv[] )
- {
- int count;
- for( count=0; count < argc; count++ )
- show_args( argv[count] );
- return 0;
- }
-
- void show_args( char *argument )
- {
- printf( "%s\n", argument );
- }
-
-
- ARGV1.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\ARGV1.C
-
- /* ARGV1.C: Demonstrate null pointers. */
- #include <stdio.h>
-
- void show_args( char *argument );
-
- int main( int argc, char **argv )
- {
- while( *argv )
- show_args( *(argv++) );
- return 0;
- }
-
- void show_args( char *argument )
- {
- printf( "%s\n", argument );
- }
-
-
- ARRAY.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\ARRAY.C
-
- /* ARRAY.C: Demonstrate one-dimensional array. */
- #include <stdio.h>
-
- main()
- {
- int j;
- int i_array[3];
-
- i_array[0] = 176;
- i_array[1] = 4069;
- i_array[2] = 303;
-
- printf( "--- Values -------- --- Addresses -------\n\n" );
-
- for( j = 0; j < 3; j = j + 1 )
- {
- printf( "i_array[%d] = %d", j, i_array[j] );
- printf( "\t&i_array[%d] = %u\n", j, &i_array[j] );
- }
-
- }
-
-
- BAR.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\BAR.C
-
- /* BAR.C: Create sample bar chart. */
- #include <conio.h>
- #include <string.h>
- #include <graph.h>
- #include <pgchart.h>
- #define MONTHS 12
- typedef enum {FALSE, TRUE} boolean;
- float far value[MONTHS] =
- {
- 33.0, 27.0, 42.0, 64.0,106.0,157.0,
- 182.0,217.0,128.0, 62.0, 43.0, 36.0
- };
- char far *category[MONTHS] =
- {
- "Jan", "Feb", "Mar", "Apr",
- "May", "Jun", "Jly", "Aug",
- "Sep", "Oct", "Nov", "Dec"
- };
-
- main()
- {
- chartenv env;
- int mode = _VRES16COLOR;
- /* Set highest video mode available */
- while(!_setvideomode( mode ))
- mode--;
- if(mode == _TEXTMONO)
- return(0);
-
- /* Initialize chart library and a default bar chart */
- _pg_initchart();
-
- _pg_defaultchart( &env, _PG_BARCHART, _PG_PLAINBARS
- );
- /* Add titles and some chart options */
- strcpy( env.maintitle.title, "Good Neighbor Grocery" );
- env.maintitle.titlecolor = 6;
- env.maintitle.justify = _PG_RIGHT;
- strcpy( env.subtitle.title, "Orange Juice Sales" );
- env.subtitle.titlecolor = 6;
- env.subtitle.justify = _PG_RIGHT;
- strcpy( env.yaxis.axistitle.title, "Months" );
- strcpy( env.xaxis.axistitle.title, "Quantity (cases)" );
- env.chartwindow.border = FALSE;
-
- /* Parameters for call to _pg_chart are:
- * env - Environment variable
- * category - Category labels
- * value - Data to chart
- * MONTHS - Number of data values */
-
- if(_pg_chart( &env, category, value, MONTHS ))
- {
- _setvideomode( _DEFAULTMODE );
- _outtext( "Error: can't draw chart" );
- }
- else
- {
- getch();
- _setvideomode( _DEFAULTMODE );
- }
- return(0);
- }
-
-
- BEEP.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\BEEP.C
-
- /* BEEP.C: Demonstrate simple function */
- #include <stdio.h>
-
- void beep( void);
-
- main()
- {
- printf( "Time to beep\n" );
- beep();
- printf( "All done\n" );
- }
-
- void beep( void )
- {
- printf( "Beep!\a\n" );
- }
-
-
- BEEP1.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\BEEP1.C
-
- /* BEEP1.C: Demonstrate passing arguments */
- #include <stdio.h>
-
- void beep( int num_beep );
-
- main()
- {
- printf( "Time to beep\n" );
- beep( 5 );
- printf( "All done\n" );
- }
-
- void beep( int num_beep )
- {
- while( num_beep > 0 )
- {
- printf( "Beep!\a\n" );
- num_beep = num_beep - 1;
- }
- }
-
-
- BEEPER.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\BEEPER.C
-
- /* BEEPER.C: Demonstrate simple function */
- #include <stdio.h>
-
- void beep( void);
-
- main()
- {
- printf( "Time to beep\n" );
- beep();
- printf( "All done\n" );
- }
-
- void beep( void )
- {
- printf( "Beep!\a\n" );
- }
-
-
- BEEPER1.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\BEEPER1.C
-
- /* BEEPER1.C: Demonstrate passing arguments */
- #include <stdio.h>
-
- void beep( int num_beep );
-
- main()
- {
- printf( "Time to beep\n" );
- beep( 5 );
- printf( "All done\n" );
- }
-
- void beep( int num_beep )
- {
- while( num_beep > 0 )
- {
- printf( "Beep!\a\n" );
- num_beep = num_beep - 1;
- }
- }
-
-
- BITWISE.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\BITWISE.C
-
- /* BITWISE.C: Demonstrate bitwise operators. */
- #include <stdio.h>
-
- main()
- {
- printf( "255 & 15 = %d\n", 255 & 15 );
- printf( "255 | 15 = %d\n", 255 | 15 );
- printf( "255 ^ 15 = %d\n", 255 ^ 15 );
- printf( "2 << 2 = %d\n", 2 << 2 );
- printf( "16 >> 2 = %d\n", 16 >> 2 );
- printf( "~2 = %d\n", ~2 );
- }
-
-
- BREAKER.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\BREAKER.C
-
- /* BREAKER.C: Demonstrate break statement. */
-
- #include <stdio.h>
- #include <conio.h>
-
- main()
- {
- char ch;
- printf( "Press any key. Press Tab to quit.\n" );
- while( 1 )
- {
- ch = getche();
- if( ch == '\t' )
- {
- printf( "\a\nYou pressed Tab\n" );
- break;
- }
- }
- }
-
-
- BREAKER1.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\BREAKER1.C
-
- /* BREAKER1.C: Break only exits one loop. */
-
- #include <stdio.h>
- #include <conio.h>
-
- main()
- {
- char ch;
- printf( "Press any key. Press Enter to quit.\n" );
- do
- {
- while( ( ch = getche() ) != '\r' )
- {
- if( ch == '\t' )
- {
- printf( "\a\nYou pressed Tab\n" );
- break;
- }
- }
- } while( ch != '\r' );
- printf( "\nBye bye." );
- }
-
-
- CGA.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\CGA.C
-
- /* CGA.C: Demonstrates CGA colors */
- #include <stdio.h>
- #include <graph.h>
- #include <conio.h>
-
- long bkcolor[8] =
- {_BLACK, _BLUE, _GREEN, _CYAN,
- _RED, _MAGENTA, _BROWN, _WHITE};
-
- char *bkcolor_name [] =
- {"_BLACK", "_BLUE", "_GREEN", "_CYAN",
- "_RED", "_MAGENTA", "_BROWN", "_WHITE"};
-
- main()
- {
- int i, j, k;
- _setvideomode( _MRES4COLOR );
- for( i=0; i<= 3; i++ )
- {
- _selectpalette( i );
- for( k=0; k <= 7; k++ )
- {
- _setbkcolor( bkcolor[k] );
- for( j=0; j<=3; j++ )
- {
- _settextposition( 1, 1 );
- printf( "background color: %8s\n", bkcolor_name[k] );
- printf( "palette: %d\ncolor: %d\n", i, j );
- _setcolor( j );
- _rectangle( _GFILLINTERIOR, 160, 100, 320, 200 );
- getch();
- }
- }
- }
- _setvideomode( _DEFAULTMODE );
- }
-
-
- COLOR.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\COLOR.C
-
- /* COLOR.C: Sets a medium resolution mode with maximum color choices */
- #include <stdio.h>
- #include <stdlib.h>
- #include <graph.h>
- #include <conio.h>
- struct videoconfig vc;
-
- main()
- {
- if( _setvideomode( _MRES256COLOR ) )
- ;
- else if( _setvideomode( _MRES16COLOR ) )
- ;
- else if( _setvideomode( _MRES4COLOR ) )
- ;
- else {
- printf( "Error: No color graphics capability\n" );
- exit( 0 );
- }
-
- _getvideoconfig( &vc );
-
- printf( "%d available colors\n", vc.numcolors );
- printf( "%d horizontal pixels\n", vc.numxpixels );
- printf( "%d vertical pixels\n", vc.numypixels );
-
- getch();
- _clearscreen( _GCLEARSCREEN );
- _setvideomode( _DEFAULTMODE );
- }
-
-
- COLTEXT.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\COLTEXT.C
-
- /* COLTEXT.C: Displays text in color */
- #include <stdio.h>
- #include <conio.h>
- #include <graph.h>
-
- char buffer [80];
-
- main()
- {
- int blink,fgd;
- long bgd;
-
- _clearscreen( _GCLEARSCREEN );
- printf( "Text color attributes:\n" );
-
- for( blink=0; blink<=16; blink+=16 )
- {
- for( bgd=0; bgd<8; bgd++ )
- {
- _setbkcolor( bgd );
- _settextposition( bgd + ((blink / 16) * 9) + 3, 1 );
- _settextcolor( 7 );
- sprintf( buffer, "Bgd: %d Fgd:", bgd );
- _outtext( buffer );
-
- for( fgd=0; fgd<16; fgd++ )
- {
- _settextcolor( fgd+blink );
- sprintf( buffer, " %2d ", fgd+blink );
- _outtext( buffer );
- }
- }
- }
- getch();
- _setvideomode( _DEFAULTMODE );
- }
-
-
- CONT.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\CONT.C
-
- /* CONT.C: Demonstrate continue statement. */
- #include <stdio.h>
-
- main()
- {
- int count;
- for( count = 0; count < 10; count++ )
- {
- if( count > 3 )
- continue;
- printf( "count = %d\n", count );
- }
- printf( "Done!\n" );
- }
-
-
- CONVERT.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\CONVERT.C
-
- /* CONVERT.C: Demonstrate type conversions. */
- #include <stdio.h>
-
- main()
- {
- char c_val = 10;
- int i_val = 20;
- long l_val = 64000;
- float f_val = 3.1;
- int result;
-
- result = c_val + i_val + l_val + f_val; /* Error! */
-
- printf( "%d\n", result );
- }
-
-
- COPYFILE.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\COPYFILE.C
-
- /* COPYFILE.C: Demonstrate malloc and free functions */
-
- <stdio.h> /* printf function and NULL */
- <io.h> /* low-level I/O functions */
- <conio.h> /* getch function */
- <sys\types.h> /* struct members used in stat.h */
- <sys\stat.h> /* S_ constants */
- <fcntl.h> /* O_ constants */
- <malloc.h> /* malloc function */
- <errno.h> /* errno global variable */
-
- int copyfile( char *source, char *destin );
-
- main( int argc, char *argv[] )
- {
- if( argc == 3 )
- if( copyfile( argv[1], argv[2] ) )
- printf( "Copy failed\n" );
- else
- printf( "Copy successful\n" );
- else
- printf( " SYNTAX: COPYFILE <source> <target>\n" );
-
- return 0;
- }
-
- int copyfile( char *source, char *target )
- {
- char *buf;
- int hsource, htarget, ch;
- unsigned count = 50000;
-
- if( (hsource = open( source, O_BINARY | O_RDONLY )) == - 1 )
- return errno;
- htarget = open( target, O_BINARY | O_WRONLY | O_CREAT | O_EXCL,
- S_IREAD | S_IWRITE );
- if( errno == EEXIST )
- {
- cputs( "Target exists. Overwrite? " );
- ch = getch();
- if( (ch == 'y') || (ch == 'Y') )
- htarget = open( target, O_BINARY | O_WRONLY | O_CREAT | O_TRUNC,
- S_IREAD | S_IWRITE );
- printf( "\n" );
- }
- if( htarget == -1 )
- return errno;
-
- if( filelength( hsource ) < count )
- count = (int)filelength( hsource );
-
- buf = (char *)malloc( (size_t)count );
-
- if( buf == NULL )
- {
- count = _memmax();
- buf = (char *)malloc( (size_t)count );
- if( buf == NULL )
- return ENOMEM;
- }
-
- while( !eof( hsource ) )
- {
- if( (count = read( hsource, buf, count )) == -1 )
- return errno;
- if( (count = write( htarget, buf, count )) == - 1 )
- return errno;
- }
-
- close( hsource );
- close( htarget );
- free( buf );
- return 0;
- }
-
-
- DECRMENT.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\DECRMENT.C
-
- /* DECRMENT.C: Demonstrate prefix and postfix operators. */
- #include <stdio.h>
-
- main()
- {
- int val, sample = 3, proton = 3;
- val = sample--;
- printf( "val = %d sample = %d\n", val, sample );
- val = --proton;
- printf( "val = %d proton = %d\n", val, proton );
- }
-
-
- DEFINED.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\DEFINED.C
-
- /* DEFINED.C: Demonstrate defined operator. */
-
- #define DEBUG 12345
-
- main()
- {
- #if defined( DEBUG )
- printf( "Hi\n" );
- #endif
- }
-
-
- DO.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\DO.C
-
- /* DO.C: Demonstrate do loop. */
-
- #include <stdio.h>
-
- main()
- {
- int test = 10;
- do
- {
- printf( "test = %d\n", test );
- test = test - 2;
- } while( test > 0 );
- }
-
-
- EGA.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\EGA.C
-
- /* EGA.C: Demonstrates EGA palettes */
- #include <stdio.h>
- #include <conio.h>
- #include <graph.h>
-
- main()
- {
- _setvideomode( _ERESCOLOR );
- _setcolor( 4 );
- _rectangle( _GFILLINTERIOR, 50, 50, 200, 200 );
-
- _settextposition( 1, 1 );
- printf( "Normal palette\n" );
- printf( "Press a key" );
- getch();
-
- _remappalette( 4, _BLUE );
-
- _settextposition( 1, 1 );
- printf( "Remapped palette\n" );
- printf( "Press a key" );
- getch();
-
- _remappalette( 4, _RED );
-
- _settextposition( 1, 1 );
- printf( "Restored palette\n" );
- printf( "Press a key to clear the screen" );
- getch();
-
- _clearscreen( _GCLEARSCREEN );
- _setvideomode( _DEFAULTMODE );
- }
-
-
- ELSE.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\ELSE.C
-
- /* ELSE.C: Demonstrate else clause. */
-
- #include <stdio.h>
- #include <conio.h>
-
- main()
- {
- char ch;
- printf( "Press the b key to hear a bell.\n" );
- ch = getch();
- if( ch == 'b' )
- printf( "Beep!\a\n" );
- else
- printf( "Bye bye\n" );
- }
-
-
- ELSE1.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\ELSE1.C
-
- /* ELSE1.C: Demonstrate else-if construct. */
-
- #include <stdio.h>
- #include <conio.h>
-
- main()
- {
- char ch;
- printf( "Press the b key to hear a bell.\n" );
- ch = getch();
- if( ch == 'b' )
- printf( "Beep!\a\n" );
- else
- if( ch == '\r' )
- printf( "Enter\n" );
- else
- printf( "Bye bye\n" );
- }
-
-
- EMPLOY1.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\EMPLOY1.C
-
- /* EMPLOY1.C: Demonstrate structure pointers. */
- #include <stdio.h>
-
-
- struct employee
- {
- char name[10];
- int months;
- float wage;
- };
-
- void display( struct employee *e_ptr );
-
- main()
- {
- static struct employee jones =
- {
- "Jones, J",
- 77,
- 13.68
- };
-
- display( &jones );
- }
-
- void display( struct employee *e_ptr )
- {
- printf( "Name: %s\n", e_ptr->name );
- printf( "Months of service: %d\n", e_ptr->months );
- printf( "Hourly wage: %6.2f\n", e_ptr->wage );
- }
-
-
- EMPLOYEE.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\EMPLOYEE.C
-
- /* EMPLOYEE.C: Demonstrate structures. */
- #include <stdio.h>
- #include <string.h>
-
- struct employee
- {
- char name[10];
- int months;
- float wage;
- };
-
- void display( struct employee show );
-
- main()
- {
- struct employee jones;
-
- strcpy( jones.name, "Jones, J" );
- jones.months = 77;
- jones.wage = 13.68;
-
- display( jones );
- }
-
- void display( struct employee show )
- {
- printf( "Name: %s\n", show.name );
- printf( "Months of service: %d\n", show.months );
- printf( "Hourly wage: %6.2f\n", show.wage );
- }
-
-
- FILE1.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\FILE1.C
-
- /* FILE1.C: Visibility in multiple source files.
- */
-
- int chico = 20, harpo = 30;
- extern void yonder( void );
-
- main()
- {
- yonder();
- }
-
-
- FILE2.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\FILE2.C
-
- /* FILE2.C: Visibility in multiple source files.
- */
-
- #include <stdio.h>
-
- void yonder( void )
- {
- extern int chico, harpo;
- printf( "chico = %d, harpo = %d\n", chico, harpo );
- }
-
-
- FORLOOP.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\FORLOOP.C
-
- /* FORLOOP.C: Demonstrate for loop. */
-
- #include <stdio.h>
-
- main()
- {
- int test;
- for( test = 10; test > 0; test = test - 2 )
- printf( "test = %d\n", test );
- }
-
-
- FORLOOP1.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\FORLOOP1.C
-
- /* FORLOOP1.C: Demonstrate multiple expressions. */
-
- #include <stdio.h>
-
- main()
- {
- int a, b;
- for( a = 256, b = 1; b < 512; a = a / 2, b = b * 2 )
- printf( "a = %d b = %d\n", a, b );
- }
-
-
- FORLOOP2.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\FORLOOP2.C
-
- /* FORLOOP2.C: Demonstrate similarity of for and while.
- */
-
- #include <stdio.h>
-
- main()
- {
- int count;
-
- for( count = 0; count < 10; count++ )
- printf( "count = %d\n", count );
-
- count = 0;
- while( count < 10 )
- {
- printf( "count = %d\n", count );
- count++;
- }
-
- }
-
-
- FUNCPTR.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\FUNCPTR.C
-
- /* FUNCPTR.C: Demonstrate function pointers. */
- #include <stdio.h>
-
- main()
- {
- int (*func_ptr) ();
- func_ptr = printf;
- (*func_ptr) ( "Curiouser and curiouser...\n" );
- }
-
-
- FUNCPTR1.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\FUNCPTR1.C
-
- /* FUNCPTR1.C: Passing function pointers as arguments. */
- #include <stdio.h>
-
- void gimme_func( void (*func_ptr) () );
-
- main()
- {
- gimme_func( puts );
- gimme_func( printf );
- }
-
- void gimme_func( void (*func_ptr) () )
- {
- (*func_ptr) ( "Ausgezeichnet!" );
- }
-
-
- GRAPHIC.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\GRAPHIC.C
-
- /* GRAPHIC.C: Displays every graphics mode */
- #include <stdio.h>
- #include <graph.h>
- #include <conio.h>
-
- struct videoconfig screen;
- int modes[12] =
- {
- _MRES4COLOR, _MRESNOCOLOR, _HRESBW,
- _HERCMONO,
- _MRES16COLOR, _HRES16COLOR, _ERESNOCOLOR, _ERESCOLOR,
- _VRES2COLOR, _VRES16COLOR, _MRES256COLOR, _ORESCOLOR
- };
-
- void print_menu( void );
- void show_mode( char );
-
- main()
- {
- char key;
- print_menu();
- while( (key = getch()) != 'x' )
- show_mode( key );
- }
-
- void print_menu( void )
- {
- _setvideomode( _DEFAULTMODE );
- _clearscreen( _GCLEARSCREEN );
- printf( "Please choose a graphics mode\nType 'x' to exit.\n\n" );
- printf( "0 _MRES4COLOR\n1 _MRESNOCOLOR\n2 _HRESBW\n" );
- printf( "3 _HERCMONO\n4 _MRES16COLOR\n5 _HRES16COLOR\n" );
- printf( "6 _ERESNOCOLOR\n7 _ERESCOLOR\n" );
- printf( "8 _VRES2COLOR\n9 _VRES16COLOR\na _MRES256COLOR\n" );
- printf( "b _ORESCOLOR\n" );
- }
-
- void show_mode( char which )
- {
- int nc, i;
- int height, width;
- int mode = which;
-
- if( mode < '0' || mode > '9' )
- if( mode == 'a' )
- mode = '9' + 1;
- else if( mode == 'b' )
- mode = '9' + 2;
- else
- return;
-
- if( _setvideomode( modes[mode - '0'] ) )
- {
- _getvideoconfig( &screen );
- nc = screen.numcolors;
- width = screen.numxpixels/nc;
- height = screen.numypixels/2;
- for( i = 0; i < nc; i++ )
- {
- _setcolor( i );
- _rectangle( _GFILLINTERIOR, i * width, 0, (i + 1) * width, height );
- }
- }
- else
- {
- printf( " \nVideo mode %c is not available.\n", which);
- printf( "Please press a key.\n" );
- }
- getch();
- _setvideomode( _DEFAULTMODE );
- print_menu();
- }
-
-
- HORIZON.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\HORIZON.C
-
- /* HORIZON.C: VGA graphics with cycling of 256 colors */
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- #include <graph.h>
-
- #define RED 0x0000003FL
- #define GRN 0x00003F00L
- #define BLU 0x003F0000L
- #define WHT 0x003F3F3FL
- #define STEP 21
-
- struct videoconfig screen;
- long int rainbow[512];
-
- main()
- {
- int i;
- long int col, gray;
-
- if( _setvideomode( _MRES256COLOR ) == 0 )
- {
- printf("This program requires a VGA card.\n" );
- exit( 0 );
- }
- for( col = 0; col < 64; col++ )
- {
- gray = col | (col << 8) | (col << 16);
- rainbow[col] = rainbow[col + 256] = BLU & gray;
- rainbow[col + 64] = rainbow[col + 64 + 256] = BLU | gray;
- rainbow[col + 128] = rainbow[col + 128 + 256] = RED | (WHT & ~gray);
- rainbow[col + 192] = rainbow[col + 192 + 256] = RED & ~gray;
- }
- _setvieworg( 160, 85 );
-
- for( i = 0; i < 255; i++ )
- {
- _setcolor( 255 - i );
- _moveto( i, i - 255 );
- _lineto( -i, 255 - i );
- _moveto( -i, i - 255 );
- _lineto( i, 255 - i );
- _ellipse( _GBORDER, -i, -i / 2, i, i / 2 );
- }
- for( i = 0; !kbhit(); i += STEP, i %= 256 )
- _remapallpalette( &(rainbow[i]) );
-
- _setvideomode( _DEFAULTMODE );
- }
-
-
- IFF.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\IFF.C
-
- /* IFF.C: Demonstrate if statement. */
-
- #include <stdio.h>
- #include <conio.h>
-
- main()
- {
- char ch;
- printf( "Press the b key to hear a bell.\n" );
- ch = getche();
- if( ch == 'b' )
- printf( "Beep!\a\n" );
- }
-
-
- INPUT.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\INPUT.C
-
- /* INPUT.C: Reads keyboard. */
- #include <stdio.h>
- #include <conio.h>
- #include <ctype.h>
-
- main()
- {
- int num, c;
- char name[80];
- float rb;
-
- puts( "** Type \"Name:\" and your name" );
- scanf( "Name: %40s", name );
- printf( "** You typed this:\n%s", name );
- puts( "\n\n** Try again, with the gets function." );
- fflush( stdin );
- gets( name );
- printf( "** You typed this:\n%s\n", name );
-
- printf( "\n** Now type an integer.\n" );
- scanf( "%i", &num );
- sprintf( name, "** You typed this number: %i\n", num );
- puts( name );
-
- fflush( stdin );
- printf( "** Enter a floating-point value.\n" );
- scanf( "%f", &rb );
- printf( "** The answer is %f or %e\n", rb, rb );
-
- printf( "** Continue? Y or N\n" );
-
- do
- {
- c = getch();
- c = tolower( c );
- } while( c != 'y' && c != 'n' );
- }
-
-
- MACRO.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\MACRO.C
-
- /* MACRO.C: Demonstrate macros. */
-
- #include <stdio.h>
- #define ABS(value) ( (value) >= 0 ? (value) : -(value) )
-
- main()
- {
- int val = -20;
- printf( "result = %d\n", ABS(val) );
- }
-
-
- NFORMAT.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\NFORMAT.C
-
- /* NFORMAT.C: Prints numbers and a string. */
- #include <stdio.h>
- #include <string.h>
-
- main()
- {
- int a = -765,
- b = 1,
- c = 44000,
- d = 33;
- float e = 1.33E8,
- f = -0.1234567,
- g = 12345.6789,
- h = 1.0;
- char i[80];
-
- strcpy( i, "word 1, word 2, word 3, word 4, word 5" );
-
- printf( "Unformatted:\n%d %d %d %d\n", a, b, c, d );
- printf( "%f %f %f %f\n", e, f, g, h );
- printf( "%s\n", i );
- }
-
-
- NOT.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\NOT.C
-
- /* NOT.C: Demonstrate logical NOT operator. */
- #include <stdio.h>
-
- main()
- {
- int val = 0;
- if( !val )
- printf( "val is zero" );
- }
-
-
- OLDSTYLE.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\OLDSTYLE.C
-
- /* OLDSTYLE.C: Old-style function. */
- #include <stdio.h>
- #define PI 3.14
-
- float sphere();
-
- main()
- {
- float volume;
- int radius = 3;
- volume = sphere( radius );
- printf( "Volume: %f\n", volume );
- }
-
- float sphere( rad )
- int rad;
- {
- float result;
- result = rad * rad * rad;
- result = 4 * PI * result;
- result = result / 3;
- return result;
- }
-
-
- PARRAY.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\PARRAY.C
-
- /* PARRAY.C: Demonstrate pointer to array. */
- #include <stdio.h>
-
- int i_array[] = { 25, 300, 2, 12 };
-
- main()
- {
- int *ptr;
- int count;
- ptr = &i_array[0];
- for( count = 0; count < 4 ; count++ )
- {
- printf( "i_array[%d] = %d\n", count, *ptr );
- ptr++;
- }
- }
-
-
- PARRAY1.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\PARRAY1.C
-
- /* PARRAY1.C: Compact version of PARRAY.C. */
- #include <stdio.h>
-
- int i_array[] = { 25, 300, 2, 12 };
-
- main()
- {
- int count;
- int *ptr = i_array;
- for( count = 0; count < 4 ; count++ )
- printf( "i_array[%d] = %d\n", count, *ptr++ );
- }
-
-
- PFUNC.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\PFUNC.C
-
- /* PFUNC.C: Passing pointers to a function. */
- #include <stdio.h>
-
- void swap( int *ptr1, int *ptr2 );
-
- main()
- {
- int first = 1, second = 3;
- int *ptr = &second;
- printf( "first: %d second: %d\n", first, *ptr );
- swap( &first, ptr );
- printf( "first: %d second: %d\n", first, *ptr );
- }
-
- void swap( int *ptr1, int *ptr2 )
- {
- int temp;
- temp = *ptr1;
- *ptr1 = *ptr2;
- *ptr2 = temp;
- }
-
-
- PIE.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\PIE.C
-
- /* PIE.C: Create sample pie chart. */
- #include <conio.h>
- #include <string.h>
- #include <graph.h>
- #include <pgchart.h>
-
- #define MONTHS 12
-
- typedef enum {FALSE, TRUE} boolean;
-
- float far value[MONTHS] =
- {
- 33.0, 27.0, 42.0, 64.0,106.0,157.0,
- 182.0,217.0,128.0, 62.0, 43.0, 36.0
- };
- char far *category[MONTHS] =
- {
- "Jan", "Feb", "Mar", "Apr",
- "May", "Jun", "Jly", "Aug",
- "Sep", "Oct", "Nov", "Dec"
- };
- short far explode[MONTHS] = {0};
-
- main()
- {
- chartenv env;
- int mode = _VRES16COLOR;
-
- /* Set highest video mode available */
- while(!_setvideomode( mode ))
- mode--;
- if(mode == _TEXTMONO)
- return( 0 );
-
- /* Initialize chart library and a default pie chart */
- _pg_initchart();
- _pg_defaultchart( &env, _PG_PIECHART, _PG_PERCENT );
-
- /* Add titles and some chart options */
- strcpy( env.maintitle.title, "Good Neighbor Grocery" );
- env.maintitle.titlecolor = 6;
- env.maintitle.justify = _PG_RIGHT;
- strcpy( env.subtitle.title, "Orange Juice Sales" );
- env.subtitle.titlecolor = 6;
- env.subtitle.justify = _PG_RIGHT;
- env.chartwindow.border = FALSE;
-
- /* Parameters for call to _pg_chartpie are:
- *
- * env - Environment variable
- * category - Category labels
- * value - Data to chart
- * explode - Separated pieces
- * MONTHS - Number of data values
- */
-
- if(_pg_chartpie( &env, category, value,
- explode, MONTHS ))
- {
- _setvideomode( _DEFAULTMODE );
- _outtext( "Error: can't draw chart" );
- }
- else
- {
- getch();
- _setvideomode( _DEFAULTMODE );
- }
- return( 0 );
- }
-
-
- POINTER.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\POINTER.C
-
- /* POINTER.C: Demonstrate pointer basics. */
- #include <stdio.h>
-
- main()
- {
- int val = 25;
- int *ptr;
- ptr = &val;
- printf( " val = %d\n", val );
- printf( "*ptr = %d\n\n", *ptr );
- printf( "&val = %u\n", &val );
- printf( " ptr = %d\n", ptr );
- }
-
-
- POWER2.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\POWER2.C
-
- /* POWER2.C */
- #include <stdio.h>
-
- int power2( int num, int power );
-
- void main( void )
- {
- printf( "3 times 2 to the power of 5 is %d\n", \
- power2( 3, 5) );
- }
-
- int power2( int num, int power )
- {
- _asm
- {
- mov ax, num ; Get first argument
- mov cx, power ; Get second argument
- shl ax, cl ; AX = AX * ( 2 to the power of CL )
- }
- /* Return with result in AX */
- }
-
-
- PRTESC.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\PRTESC.C
-
- /* PRTESC.C: Prints escape characters \",\n, and \t. */
- #include <stdio.h>
- #include <string.h>
-
- main()
- {
- char b[80];
- int i,j;
-
- strcpy( b, "and seven years ago\n" );
- printf( "\"Four score\n" );
- printf( b );
- printf( "\tone tab\n\t\ttwo tabs\n\t\t\tthree tabs\n" );
- i = sizeof( b );
- j = strlen( b );
- printf( "Size is %d\nLength is %d.\n", i, j );
- }
-
-
- PRTSTR.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\PRTSTR.C
-
- /* PRTSTR.C: Prints strings. */
- #include <stdio.h>
- #include <string.h>
-
- main()
- {
- char aline[80], more[80];
- char *strptr;
-
- /* aline = "Another line."; */
- /* Note: This causes a compiler error */
-
- strcpy( aline, "Another line." );
- strcpy( more, aline );
- strptr = aline;
- strcat( aline, "dog" );
- printf( "A line of text." );
- printf( aline );
- printf( more );
- printf( strptr );
- }
-
-
- PSTRING.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\PSTRING.C
-
- /* PSTRING.C: Demonstrate pointer to a string. */
-
- #include <stdio.h>
-
- main()
- {
- int count;
- static char name[] = "john";
- char *ptr = name;
- for( count = 0; count < 4; count++ )
- {
- printf( "name[%d]: %c\n", count, *ptr++ );
- }
- }
-
-
- PSTRING1.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\PSTRING1.C
-
- /* PSTRING1.C: Look for null at string's end. */
- #include <stdio.h>
-
- main()
- {
- char name[] = "john";
- char *ptr = name;
- while( *ptr )
- printf( "*ptr = %c\n", *ptr++ );
- }
-
-
- PSTRING2.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\PSTRING2.C
-
- /* PSTRING2.C: Demonstrate strings and array notation. */
- #include <stdio.h>
- #include <string.h>
-
- main()
- {
- int count;
- char name[] = "john";
- for( count = 0; count < strlen( name ); count++ )
- printf( "name[%d]: %c\n", count, name[count] );
- }
-
-
- PSTRING3.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\PSTRING3.C
-
- /* PSTRING3.C: Strings and pointer notation. */
- #include <stdio.h>
- #include <string.h>
-
- main()
- {
- int count;
- char name[] = "john";
- for( count = 0; count < strlen( name ); count++ )
- printf( "*(name+%d) = %c\n", count, *(name+count) );
- }
-
-
- PTRPTR.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\PTRPTR.C
-
- /* PTRPTR.C: Demonstrate a pointer to a pointer. */
- #include <stdio.h>
-
- main()
- {
- int val = 501;
- int *ptr = &val;
- int **ptr_ptr = &ptr;
- printf( "val = %d\n", **ptr_ptr );
- }
-
-
- QCSORT.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\QCSORT.C
-
- /* QCSORT.C: Demonstrate sorting array of pointers. */
-
- #include <stdio.h>
- #define SIZE 4
-
- void sort( int size, double *p[] );
- void show( int size, double *p[], double dd[] );
-
- main()
- {
- int x;
- double d[] = { 3.333, 1.111, 2.222, 4.444 };
- double *d_ptr[SIZE];
- for( x = 0; x < SIZE; x++ )
- d_ptr[x] = &d[x];
- show( SIZE, d_ptr, d );
- sort( SIZE, d_ptr );
- show( SIZE, d_ptr, d );
- }
-
- void sort( int size, double *p[] )
- {
- int x, x1;
- double *temp;
- for( x = 0; x < size - 1; x++ )
- for( x1 = x + 1; x1 < size; x1++ )
- {
- if( *p[x] > *p[x1] )
- {
- temp = p[x1];
- p[x1] = p[x];
- p[x] = temp;
- }
- }
- }
-
- void show( int size, double *p[], double dd[] )
- {
- int x;
- printf( "------------------------" );
- printf( "------------------------\n" );
- for( x = 0; x < size; x++ )
- {
- printf( "*d_ptr[%d] = %1.3f ", x, *p[x]);
- printf( "d_ptr[%d] = %u ", x, p[x]);
- printf( " d[%d] = %1.3f\n", x, dd[x] );
- }
- }
-
-
- QCSORT1.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\QCSORT1.C
-
- /* QCSORT1.C: Demonstrate sort with pointer notation. */
-
- #include <stdio.h>
- #define SIZE 4
-
- void sort( int size, double **p );
- void show( int size, double **p, double dd[] );
-
- main()
- {
- int x;
- double d[] = { 3.333, 1.111, 2.222, 4.444 };
- double *d_ptr[SIZE];
- for( x = 0; x < SIZE; x++ )
- d_ptr[x] = &d[x];
- show( SIZE, d_ptr, d );
- sort( SIZE, d_ptr );
- show( SIZE, d_ptr, d );
- }
-
- void sort( int size, double **p )
- {
- int x, x1;
- double *temp;
- for( x = 0; x < size - 1; x++ )
- for( x1 = x + 1; x1 < size; x1++ )
- {
- if( **(p+x) > **(p+x1) )
- {
- temp = *(p+x1);
- *(p+x1) = *(p+x);
- *(p+x) = temp;
- }
- }
- }
-
- void show( int size, double **p, double dd[] )
- {
- int x;
- printf( "------------------------" );
- printf( "------------------------\n" );
- for( x = 0; x < size; x++ )
- {
- printf( "*d_ptr[%d] = %1.3f ", x, **(p+x) );
- printf( "d_ptr[%d] = %u ", x, *(p+x) );
- printf( " d[%d] = %1.3f\n", x, dd[x] );
- }
- }
-
-
- RDFILE.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\RDFILE.C
-
- /* RDFILE.C: Reads a file and prints characters to the screen. */
- #include <stdio.h>
-
- main()
- {
- int c;
- FILE *fp;
-
- if( fp = fopen( "c:\\testfile.asc", "rb" ) )
- {
- while( (c = fgetc( fp )) != EOF )
- printf( " %c\t%d\n", c, c );
- printf( "\nEnd of file marker: %d", c );
- fclose( fp );
- }
- else
- printf( "Error in opening file\n" );
- }
-
-
- REALG.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\REALG.C
-
- /* REALG.C: Example of real-coordinate graphics */
- #include <stdio.h>
- #include <conio.h>
- #include <graph.h>
-
- #define TRUE 1
- #define FALSE 0
-
- int four_colors( void );
- void three_graphs( void );
- void grid_shape( void );
-
- int halfx, halfy;
- struct videoconfig screen;
- double bananas[] =
- { -0.3, -0.2, -0.224, -0.1, -0.5, +0.21, +2.9,
- +0.3, +0.2, 0.0, -0.885, -1.1, -0.3, -0.2,
- +.001, +.005, +0.14, 0.0, -0.9, -0.13, +0.3
- };
-
- main()
- {
- if( four_colors() )
- three_graphs();
- else
- printf( "This program requires a CGA, EGA, or VGA graphics card.\n" );
- }
-
- int four_colors( void )
- {
- _getvideoconfig( &screen );
- switch( screen.adapter )
- {
- case _CGA:
- case _OCGA:
- _setvideomode( _MRES4COLOR );
- break;
- case _EGA:
- case _OEGA:
- _setvideomode( _ERESCOLOR );
- break;
- case _VGA:
- case _OVGA:
- _setvideomode( _VRES16COLOR );
- break;
- default:
- return( FALSE );
- }
- _getvideoconfig( &screen );
- return( TRUE );
- }
-
- void three_graphs( void )
- {
- int xwidth, yheight, cols, rows;
- struct _wxycoord upleft, botright;
-
- _clearscreen( _GCLEARSCREEN );
- xwidth = screen.numxpixels;
- yheight = screen.numypixels;
- halfx = xwidth/2;
- halfy = yheight/2;
- cols = screen.numtextcols;
- rows = screen.numtextrows;
-
- /* first window */
- _setviewport( 0, 0, halfx-1, halfy-1 );
- _settextwindow( 1, 1, rows/2, cols/2 );
- _setwindow( FALSE, -2.0, -2.0, 2.0, 2.0 );
- grid_shape();
- _rectangle( _GBORDER, 0, 0, halfx-1, halfy-1 );
-
- /* second window */
- _setviewport( halfx, 0, xwidth-1, halfy-1 );
- _settextwindow( 1, cols/2+1, rows/2, cols );
- _setwindow( FALSE, -3.0, -3.0, 3.0, 3.0 );
- grid_shape();
- _rectangle_w( _GBORDER, -3.0, -3.0, 3.0, 3.0 );
-
- /* third window */
- _setviewport( 0, halfy, xwidth-1, yheight-1 );
- _settextwindow( rows/2+1, 1, rows, cols );
- _setwindow( TRUE, -3.0, -1.5, 1.5, 1.5 );
- grid_shape();
- upleft.wx = -3.0;
- upleft.wy = -1.5;
- botright.wx = 1.5;
- botright.wy = 1.5;
- _rectangle_wxy( _GBORDER, &upleft, &botright );
-
- getch();
- _setvideomode( _DEFAULTMODE );
- }
-
- void grid_shape( void )
- {
- int i, numc, x1, y1, x2, y2;
- double x, y;
- char txt[80];
-
- numc = screen.numcolors;
- for( i = 1; i < numc; i++ )
- {
- _settextposition( i, 2 );
- _settextcolor( i );
- sprintf( txt, "Color %d", i );
- _outtext( txt );
- }
-
- _setcolor( 1 );
- _rectangle_w( _GBORDER, -1.0, -1.0, 1.0, 1.0 );
- _rectangle_w( _GBORDER, -1.02, -1.02, 1.02, 1.02 );
-
- for( x = -0.9, i = 0; x < 0.9; x += 0.1 )
- {
- _setcolor( 2 );
- _moveto_w( x, -1.0 );
- _lineto_w( x, 1.0 );
- _moveto_w( -1.0, x );
- _lineto_w( 1.0, x );
-
- _setcolor( 3 );
- _moveto_w( x - 0.1, bananas[i++] );
- _lineto_w( x, bananas[i] );
- }
- _moveto_w( 0.9, bananas[i++] );
- _lineto_w( 1.0, bananas[i] );
- }
-
-
- RWFILE.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\RWFILE.C
-
- /* RWFILE.C: Reads and writes a file. */
- #include <stdio.h>
- #include <string.h>
- #include <fcntl.h>
- #include <sys\types.h>
- #include <sys\stat.h>
- #include <io.h>
-
- #define BUFF 512
-
- main()
- {
- char inbuffer[BUFF];
- char outbuffer[BUFF];
- int infile, outfile, length, num;
-
- strcpy( outbuffer, "Happy Birthday." );
- length = strlen( outbuffer );
- length++;
-
- if( (outfile = open( "testfile.bin",
- O_CREAT | O_WRONLY | O_BINARY, S_IWRITE )) != -1 )
- {
- if( (num = write( outfile, outbuffer, length )) == -1 )
- perror( "Error in writing" );
- printf( "\nBytes written to file: %d\n", num );
- close( outfile );
- }
- else
- perror( "Error opening outfile" );
-
- if( (infile = open( "testfile.bin", O_RDONLY | O_BINARY )) != -1 )
- {
- while( length = read( infile, inbuffer, BUFF ) )
- printf( "%d bytes received so far.\n", length );
- close( infile );
- printf( "%s\n", inbuffer );
- }
- else
- perror( "Error opening infile" );
- }
-
-
- SAMPLER.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\SAMPLER.C
-
- /* SAMPLER.C: Display sample text in various fonts. */
- #include <stdio.h>
- #include <conio.h>
- #include <stdlib.h>
- #include <graph.h>
- #include <string.h>
-
- #define NFONTS 6
-
- main()
- {
- static unsigned char *text[2*NFONTS] =
- {
- "COURIER", "courier",
- "HELV", "helv",
- "TMS RMN", "tms rmn",
- "MODERN", "modern",
- "SCRIPT", "script",
- "ROMAN", "roman"
- };
- static unsigned char *face[NFONTS] =
- {
- "t'courier'",
- "t'helv'",
- "t'tms rmn'",
- "t'modern'",
- "t'script'",
- "t'roman'"
- };
- static unsigned char list[20];
- struct videoconfig vc;
- int mode = _VRES16COLOR;
- register i;
-
- /* Read header info from all .FON files in
- * current directory */
- if(_registerfonts( "*.FON" )<0 )
- {
- _outtext("Error: can't register fonts");
- exit( 0 );
- }
-
- /* Set highest available video mode */
- while( !_setvideomode( mode ) )
- mode--;
- if( mode == _TEXTMONO )
- exit ( 0 );
-
- /* Copy video configuration into structure vc */
- _getvideoconfig( &vc );
-
- /* Display six lines of sample text */
- for( i = 0; i<NFONTS; i++ )
- {
- strcpy( list, face[i] );
- strcat( list, "h30w24b" );
-
- if( !_setfont( list ) )
- {
- _setcolor( i + 1 );
- _moveto( 0, (i * vc.numypixels) / NFONTS );
- _outgtext( text[i * 2] );
- _moveto( vc.numxpixels / 2,
- (i * vc.numypixels) / NFONTS );
- _outgtext( text[(i * 2) + 1] );
- }
- else
- {
- _setvideomode( _DEFAULTMODE );
- _outtext( "Error: can't set font" );
- exit( 0 );
- }
- }
- getch();
- _setvideomode( _DEFAULTMODE );
-
- /* Return memory when finished with fonts */
- _unregisterfonts();
- exit( 0 );
- }
-
-
- SCATTER.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\SCATTER.C
-
- /* SCATTER.C: Create sample scatter diagram. */
-
- #include <conio.h>
- #include <string.h>
- #include <graph.h>
- #include <pgchart.h>
-
- #define MONTHS 12
- typedef enum {FALSE, TRUE} boolean;
-
- /* Orange juice sales */
-
- float far xvalue[MONTHS] =
- {
- 33.0, 27.0, 42.0, 64.0,106.0,157.0,
- 182.0,217.0,128.0, 62.0, 43.0, 36.0
- };
- /* Hot chocolate sales */
-
- float far yvalue[MONTHS] =
- {
- 37.0, 37.0, 30.0, 19.0, 10.0, 5.0,
- 2.0, 1.0, 7.0, 15.0, 28.0, 39.0
- };
-
- main()
- {
- chartenv env;
- int mode = _VRES16COLOR;
-
- /* Set highest video mode available */
-
- while(!_setvideomode( mode ))
- mode--;
- if(mode == _TEXTMONO)
- return(0);
-
- /* Initialize chart library and default
- * scatter diagram
- */
-
- _pg_initchart();
-
- _pg_defaultchart( &env, _PG_SCATTERCHART,
- _PG_POINTONLY );
-
- /* Add titles and some chart options */
-
- strcpy( env.maintitle.title, "Good Neighbor Grocery" );
- env.maintitle.titlecolor = 6;
- env.maintitle.justify = _PG_RIGHT;
- strcpy( env.subtitle.title,
- "Orange Juice vs Hot Chocolate" );
- env.subtitle.titlecolor = 6;
- env.subtitle.justify = _PG_RIGHT;
- env.yaxis.grid = TRUE;
- strcpy( env.xaxis.axistitle.title,
- "Orange Juice Sales" );
- strcpy( env.yaxis.axistitle.title,
- "Hot Chocolate Sales" );
- env.chartwindow.border = FALSE;
-
- /* Parameters for call to _pg_chartscatter are:
- * env - Environment variable
- * xvalue - X-axis data
- * yvalue - Y-axis data
- * MONTHS - Number of data values
- */
-
- if(_pg_chartscatter( &env, xvalue,
- yvalue, MONTHS ))
- {
- _setvideomode( _DEFAULTMODE );
- _outtext( "Error: can't draw chart" );
- }
- else
- {
- getch();
- _setvideomode( _DEFAULTMODE );
- }
- return(0);
- }
-
-
- SHOWME.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\SHOWME.C
-
- /* SHOWME.C: Demonstrate passing by value. */
- #include <stdio.h>
-
- void showme( int a, int b, int c );
-
- main()
- {
- int x = 10, y = 20, z = 30;
- showme( z, y, x );
- }
-
- void showme( int a, int b, int c )
- {
- printf( "a=%d b=%d c=%d", a, b, c );
- }
-
-
- SHOWMORE.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\SHOWMORE.C
-
- /* SHOWMORE.C: Demonstrate passing by value. */
- #include <stdio.h>
-
- void showme( int any, int old, int name );
-
- main()
- {
- int x = 10, y = 20, z = 30;
- showme( z, y, x );
- printf( " z=%d y=%d x=%d\n", z, y, x );
- }
-
- void showme( int any, int old, int name )
- {
- printf( "any=%d old=%d name=%d\n", any, old, name );
- any = 55;
- old = 66;
- name = 77;
- printf( "any=%d old=%d name=%d\n", any, old, name );
- }
-
-
- SINE.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\SINE.C
-
- /* SINE.C: Illustrates basic graphics commands */
- #include <stdio.h>
- #include <stdlib.h>
- #include <graph.h>
- #include <math.h>
- #include <conio.h>
- #define PI 3.14159
-
- void graphics_mode( void );
- void draw_lines( void );
- void sine_wave( void );
- void draw_shapes( void );
- void end_program( void );
- int newx( int );
- int newy( int );
-
- struct videoconfig myscreen;
- int maxx, maxy;
- unsigned char diagmask[8] =
- { 0x93, 0xC9, 0x64, 0xB2, 0x59, 0x2C, 0x96, 0x4B };
- unsigned char linemask[8] =
- { 0xFF, 0x00, 0x7F, 0xFE, 0x00, 0x00, 0x00, 0xCC };
-
- main()
- {
- graphics_mode();
- draw_lines();
- sine_wave();
- draw_shapes();
- end_program();
- }
-
- void graphics_mode( void )
- {
- _getvideoconfig( &myscreen );
- switch( myscreen.adapter )
- {
- case _CGA:
- _setvideomode( _HRESBW );
- break;
- case _OCGA:
- _setvideomode( _ORESCOLOR );
- break;
- case _EGA:
- case _OEGA:
- if( myscreen.monitor == _MONO )
- _setvideomode( _ERESNOCOLOR );
- else
- _setvideomode( _ERESCOLOR );
- break;
- case _VGA:
- case _OVGA:
- case _MCGA:
- _setvideomode( _VRES2COLOR );
- break;
- case _HGC:
- _setvideomode( _HERCMONO );
- break;
- default:
- printf( "This program requires a CGA, EGA, VGA, or Hercules card\n"
- exit( 0 );
- }
- _getvideoconfig( &myscreen );
- maxx = myscreen.numxpixels - 1;
- maxy = myscreen.numypixels - 1;
- }
-
- int newx( int xcoord )
- {
- int nx;
- float tempx;
- tempx = ((float) maxx)/ 1000.0;
- tempx = ((float) xcoord) * tempx + 0.5;
- return( (int) tempx );
- }
-
- int newy( int ycoord )
- {
- int ny;
- float tempy;
- tempy = ((float) maxy)/ 1000.0;
- tempy = ((float) ycoord) * tempy + 0.5;
- return( (int) tempy );
- }
-
- void sine_wave( void )
- {
- int locx, locy;
- double i, rad;
-
- for( i = 0.0; i < 1000.0; i += 3.0 )
- {
- rad = -sin( (PI * (float) i) / 250.0 );
- locx = newx( (int) i );
- locy = newy( (int) (rad * 250.0) );
- _setpixel( locx, locy );
- }
- }
-
- void draw_shapes( void )
- {
- _setlinestyle( 0xFFFF );
- _setfillmask( diagmask );
- _rectangle( _GBORDER, newx(50), newy(-325), newx(200), newy(-425) );
- _rectangle( _GFILLINTERIOR, newx(550), newy(-325), newx(700), newy(-425) )
-
- _setfillmask( linemask );
- _ellipse( _GBORDER, newx(50), newy(325), newx(200), newy(425) );
- _ellipse( _GFILLINTERIOR, newx(550), newy(325), newx(700), newy(425) );
- }
-
- void end_program( void )
- {
- getch();
- _setvideomode( _DEFAULTMODE );
- }
-
- void draw_lines( void )
- {
- _rectangle( _GBORDER, 0, 0, maxx, maxy );
- /* _setcliprgn( 20, 20, maxx - 20, maxy - 20 ); */
- _setvieworg( 0, newy( 500 ) );
-
- _moveto( 0, 0 );
- _lineto( newx( 1000 ), 0 );
- _setlinestyle( 0xAA3C );
- _moveto( 0, newy( -250) );
- _lineto( newx( 1000 ), newy( -250 ) );
-
- _setlinestyle( 0x8888 );
- _moveto( 0, newy( 250 ) );
- _lineto( newx( 1000 ), newy( 250 ) );
- }
-
-
- STATIC.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\STATIC.C
-
- /* STATIC.C: Demonstrate static variables. */
-
- #include <stdio.h>
-
- void add_val( int value );
-
- main()
- {
- add_val( 1 );
- add_val( 5 );
- add_val( 20 );
- }
-
- void add_val( int value )
- {
- static int methuselah;
- if( value == 1 )
- methuselah = 0;
- methuselah = methuselah + value;
- printf( "methuselah = %d\n", methuselah );
- }
-
-
- STRING.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\STRING.C
-
- /* STRING.C: Demonstrate string arrays. */
- #include <stdio.h>
-
- main()
- {
- int j;
- char c_array[] = "Hello";
-
- printf( "--- Values -------- --- Addresses -------\n\n" );
-
- for( j = 0; j < 6; j = j + 1 )
- {
- printf( "c_array[%d] = %x %c", j, c_array[j], c_array[j] );
- printf( "\t&c_array[%d] = %u\n", j, &c_array[j] );
- }
- }
-
-
- SVBIN.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\SVBIN.C
-
- /* SVBIN.C: Saves integer variables in binary format. */
- #include <stdio.h>
- #define ASIZE 10
-
- main()
- {
- FILE *ap;
- int zebra[ASIZE], acopy[ASIZE], bcopy[ASIZE];
- int i;
-
- for( i = 0; i < ASIZE; i++ )
- zebra[i] = 7700 + i;
-
- if( (ap = fopen( "binfile", "wb" )) != NULL )
- {
- fwrite( zebra, sizeof(zebra), 1, ap );
- fclose( ap );
- }
- else
- perror( "Write error" );
-
- if( (ap = fopen( "morebin", "wb" )) != NULL )
- {
- fwrite( &zebra[0], sizeof(zebra[0]), ASIZE, ap );
- fclose( ap );
- }
- else
- perror( "Write error" );
-
- if( (ap = fopen( "binfile", "rb" )) != NULL )
- {
- printf( "Hexadecimal values in binfile:\n" );
- while( (i = fgetc( ap )) != EOF )
- printf( "%02X ", i );
- rewind( ap );
- fread( acopy, sizeof(acopy), 1, ap );
- rewind( ap );
- fread( &bcopy[0], sizeof( bcopy[0] ), ASIZE, ap);
- for( i=0; i<ASIZE; i++ )
- printf( "\nItem %d = %d\t%d", i, acopy[i], bcopy[i] );
- fclose( ap );
-
- }
- else
- perror( "Read error" );
-
- }
-
-
- SVTEXT.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\SVTEXT.C
-
- /* SVTEXT.C: Save integer variables as text. */
- #include <stdio.h>
-
- int list[] = { 53, -23456, 50, 500, 5000, -99 };
- extern int errno;
- char fname[] = "numtext";
- char temp[81];
-
- main()
- {
- FILE *fptr;
- int i;
-
- if( (fptr = fopen( "numtext","wt" )) != NULL )
- {
- for( i=0; i<6; i++ )
- fprintf( fptr, "Item %d: %6d \n", i, list[i] );
- fclose( fptr );
- }
- else
- printf( "Error: Couldn't create file.\n" );
-
- if( (fptr = fopen( "badname", "rt" )) != NULL )
- {
- /* do nothing */
- }
- else
- {
- printf( "Error number: %d\n\t", errno );
- perror( "Couldn't open file BADNAME\n\t" );
- }
-
- if( (fptr = fopen( fname, "rt" )) != NULL )
- {
- list[0] = 0;
- fscanf( fptr, "Item %d: %d \n", &i, &list[0] );
- printf( "Values read from file:\t %d %d\n", i, list[0] );
- fgets( temp, 80, fptr );
- printf( "String from file: \t%s\n", temp );
- while( (i = fgetc( fptr )) != '\n' )
- printf( "char: %c \t ASCII: %d \n", i, i );
- rewind( fptr );
- printf( "Rewind to start -->\t%s", fgets( temp, 80, fptr ) );
- fclose( fptr );
- }
- else
- printf( "Trouble opening %s \n", fname );
- }
-
-
- SWITCH.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\SWITCH.C
-
- /* SWITCH.C: Demonstrate switch statement. */
-
- #include <stdio.h>
- #include <conio.h>
-
- main()
- {
- char ch;
- printf( "Press the b key to hear a bell.\n" );
- ch = getch();
- switch( ch )
- {
- case 'b':
- printf( "Beep!\a\n" );
- break;
- case '\r':
- printf( "Enter\n" );
- break;
- default:
- printf( "Bye bye" );
- break;
- }
- }
-
-
- TWODIM.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\TWODIM.C
-
- /* TWODIM.C: Demonstrate multidimensional arrays. */
-
- #include <stdio.h>
-
- main()
- {
- int j, k;
- int i_array[2][3] = { { 176, 4069, 303 }, { 6, 55, 777 } };
-
- printf( "--- Values -------- --- Addresses -------\n\n" );
-
- for( j = 0; j < 2; j = j + 1 )
- {
- for( k = 0; k < 3; k = k + 1 )
- {
- printf( "i_array[%d][%d] = %d", j, k, i_array[j][k] );
- printf( "\t&i_array[%d][%d] = %u\n", j, k, &i_array[j][k] );
- }
- printf( "\n" );
- }
-
- }
-
-
- TYPES.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\TYPES.C
-
- /* TYPES.C: Illustrate basic data types. */
- #include <stdio.h>
-
- main()
- {
- char char_val = 'a';
- int int_val = 543;
- float float_val = 11.1;
- double double_val = 66.123456789;
- printf( "char_val = %c\n", char_val );
- printf( "int_val = %d\n", int_val );
- printf( "float_val = %f\n", float_val );
- printf( "double_val = %2.9f\n", double_val );
- }
-
-
- VISIBLE.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\VISIBLE.C
-
- /* VISIBLE.C: Demonstrate local visibility. */
-
- #include <stdio.h>
- void be_bop( void );
-
- main()
- {
- int val = 10;
- be_bop();
- }
-
- void be_bop( void )
- {
- printf( "val = %d", val ); /* Error! */
- }
-
-
- VISIBLE1.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\VISIBLE1.C
-
- /* VISIBLE1.C: Demonstrate local visibility. */
-
- #include <stdio.h>
-
- void be_bop( int param );
-
- main()
- {
- int val = 10;
- be_bop( val );
- }
-
- void be_bop( int param )
- {
- printf( "%d\n", param );
- }
-
-
- VISIBLE2.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\VISIBLE2.C
-
- /* VISIBLE2.C: Demonstrate external visibility.
- */
-
- #include <stdio.h>
-
- void be_bop( int param );
-
- main()
- {
- be_bop( val ); /* Error! */
- }
-
- int val = 10;
-
- void be_bop( int param )
- {
- printf( "val = %d\n", param );
- }
-
-
- VOLUME.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\VOLUME.C
-
- /* VOLUME.C: Calculate sphere's volume. */
- #include <stdio.h>
- #define PI 3.14
-
- float sphere( int rad );
-
- main()
- {
- float volume;
- int radius = 3;
- volume = sphere( radius );
- printf( "Volume: %f\n", volume );
- }
-
- float sphere( int rad )
- {
- float result;
- result = rad * rad * rad;
- result = 4 * PI * result;
- result = result / 3;
- return result;
- }
-
-
- WHILE.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\WHILE.C
-
- /* WHILE.C: Demonstrate while loop. */
-
- #include <stdio.h>
-
- main()
- {
- int test = 10;
-
- while( test > 0 )
- {
- printf( "test = %d\n", test );
- test = test - 2;
- }
- }
-
-
- WRFILE.C
- CD-ROM Disc Path: \SAMPCODE\QC\QC25\WRFILE.C
-
- /* WRFILE.C: Creates and writes to a disk file. */
- #include <stdio.h>
-
- main()
- {
- FILE *fp;
-
- if( (fp = fopen( "c:\\testfile.asc","w" )) != NULL )
- {
- fputs( "Example string", fp );
- fputc( '\n', fp );
- fclose( fp );
- }
- else
- printf( "error message\n" );
- }
- Proficient C - Sample Code
-
-
- ANSI_CPR.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\13ANSI\ANSI_CPR.C
-
- /*
- * ansi_cpr -- report where the cursor is located
- * The position information is placed in the keyboard buffer
- * in the form ESC[rr;ccR where ESC is the value of the
- * ESCAPE character (\033) and r and c represent
- * decimal values of row and column data.
- */
-
- #include <local\ansi.h>
-
- void
- ansi_cpr(row, col)
- int *row,
- *col;
- {
- int i;
-
- /* request a cursor position report */
- ANSI_DSR;
-
- /* toss the ESC and '[' */
- (void) getkey();
- (void) getkey();
-
- /* read the row number */
- *row = 10 * (getkey() - '0');
- *row = *row + getkey() - '0';
-
- /* toss the ';' separator */
- (void) getkey();
-
- /* read the column number */
- *col = 10 * (getkey() - '0');
- *col = *col + getkey() - '0';
-
- /* toss the trailing ('R') and return */
- (void) getkey();
- (void) getkey();
- return;
- }
-
-
- ANSI_TST.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\13ANSI\ANSI_TST.C
-
- /*
- * ansi_tst -- verify that the ANSI.SYS driver is loaded
- * (prints message and exits is ANSI driver not working)
- */
-
- #include <stdio.h>
- #include <local\ansi.h>
- #include <local\video.h>
-
- #define TST_ROW 2
- #define TST_COL 75
-
- void
- ansi_tst()
- {
- int row, col;
- static char *help[] = {
- "\n",
- "ANSI.SYS device driver not loaded:\n",
- " 1. Copy ANSI.SYS to your system disk.\n",
- " 2. Add the line device=ansi.sys to your\n",
- " CONFIG.SYS file and reboot your machine.\n",
- NULL
- };
- char **msg;
-
- extern int getstate();
- extern int readcur(int *, int *, int);
-
- getstate();
- ANSI_CUP(TST_ROW, TST_COL);
- readcur(&row, &col, Vpage);
- if (row != TST_ROW - 1 || col != TST_COL - 1) {
- for (msg = help; *msg != NULL; ++msg)
- fputs(*msg, stderr);
- exit(1);
- }
-
- return;
- }
-
-
- BEEP.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\BEEP.C
-
- /*
- * beep -- sound the terminal beeper
- */
-
- #include <stdio.h>
-
- #define BEL 7
-
- void
- beep()
- {
- putchar(BEL);
- }
-
-
- CAT.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\06USER\CAT.C
-
- /*
- * cat -- concatenate files
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <local\std.h>
-
- main(argc, argv)
- int argc;
- char **argv;
- {
- int ch;
- char *cp;
- FILE *fp;
- BOOLEAN errflag, silent;
- static char pgm[MAXNAME + 1] = { "cat" };
-
- extern void getpname(char *, char *);
- extern int fcopy(FILE *, FILE *);
- extern int getopt(int, char **, char *);
- extern int optind;
- extern char *optarg;
-
- /* use an alias if one is given to this program */
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- /* process optional arguments, if any */
- errflag = FALSE;
- silent = FALSE;
- while ((ch = getopt(argc, argv, "s")) != EOF)
- switch (ch) {
- case 's':
- /* don't complain about non-existent files */
- silent = TRUE;
- break;
- case '?':
- /* say what? */
- errflag = TRUE;
- break;
- }
- if (errflag == TRUE) {
- fprintf(stderr, "Usage: %s [-s] file...\n", pgm);
- exit(1);
- }
-
- /* process any remaining arguments */
- argc -= optind;
- argv += optind;
- if (argc == 0)
- /* no file names -- use standard input */
- if (fcopy(stdin, stdout) != 0) {
- fprintf(stderr, "error copying stdin");
- exit(2);
- }
- else
- exit(0);
-
- /* copy the contents of each named file to standard output */
- for (; argc-- > 0; ++argv) {
- if ((fp = fopen(*argv, "r")) == NULL) {
- if (silent == FALSE)
- fprintf(stderr, "%s: can't open %s\n",
- pgm, *argv);
- continue;
- }
- if (fcopy(fp, stdout) != 0) {
- fprintf(stderr, "%s: Error while copying %s",
- pgm, *argv);
- exit(3);
- }
- if (fclose(fp) != 0) {
- fprintf(stderr, "%s: Error closing %s",
- pgm, *argv);
- exit(4);
- }
- }
-
- exit(0);
- }
-
-
- CLRSCRN.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\CLRSCRN.C
-
- /*
- * clrscrn -- clear the "visual" screen page
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
- #include <local\video.h>
-
- int
- clrscrn(a)
- unsigned int a; /* video attribute for new lines */
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = SCROLL_UP;
- inregs.h.al = 0; /* blank entire window */
- inregs.h.bh = a; /* use specified attribute */
- inregs.h.bl = 0;
- inregs.x.cx = 0; /* upper left corner */
- inregs.h.dh = Maxrow[Vmode] - 1;/* bottom screen row */
- inregs.h.dl = Maxcol[Vmode] - 1;/* rightmost column */
- int86(VIDEO_IO, &inregs, &outregs);
-
- return (outregs.x.cflag);
- }
-
-
- CLRW.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\CLRW.C
-
- /*
- * clrw -- clear specified region of "visual" screen page
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
-
- int
- clrw(t, l, b, r, a)
- int t; /* top row of region to clear */
- int l; /* left column */
- int b; /* bottom row */
- int r; /* right column */
- unsigned char a;/* attribute for cleared region */
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = SCROLL_UP;/* scroll visual page up */
- inregs.h.al = 0; /* blank entire window */
- inregs.h.bh = a; /* attribute of blank lines */
- inregs.h.bl = 0;
- inregs.h.ch = t; /* upper left of scroll region */
- inregs.h.cl = l;
- inregs.h.dh = b; /* lower right of scroll region */
- inregs.h.dl = r;
- int86(VIDEO_IO, &inregs, &outregs);
-
- return (outregs.x.cflag);
- }
-
-
- COLORNUM.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\13ANSI\COLORNUM.C
-
- /*
- * colornum -- return the IBM number for the color
- * presented as a string; return -1 if no match.
- */
-
- #include <stdio.h>
- #include <string.h>
- #include <local\ibmcolor.h>
-
- #define NCHARS 3
-
- int
- colornum(name)
- char *name;
- {
- register int n;
- static struct color_st {
- char *c_name;
- int c_num;
- } colortab[] = {
- "black", IBM_BLACK,
- "blue", IBM_BLUE,
- "green", IBM_GREEN,
- "cyan", IBM_CYAN,
- "red", IBM_RED,
- "magenta", IBM_MAGENTA,
- "brown", IBM_BROWN,
- "white", IBM_WHITE,
- "normal", IBM_NORMAL,
- "bright", IBM_BRIGHT,
- "light", IBM_BRIGHT,
- "bold", IBM_BRIGHT,
- "yellow", IBM_BROWN + IBM_BRIGHT,
- "blink", IBM_BLINK,
- "reverse", IBM_REVERSE,
- "invisible", IBM_INVISIBLE,
- NULL, (-1)
- };
-
- (void) strlwr(name);
- for (n = 0; colortab[n].c_name != NULL; ++n)
- if ((strncmp(name, colortab[n].c_name, NCHARS)) == 0)
- return (colortab[n].c_num);
- return (-1);
- }
-
-
- CP.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\03DOS\CP.C
-
- /*
- * cp -- a simplified copy command
- */
-
- #include <stdio.h>
-
- main()
- {
- int ch;
-
- while ((ch = getc(stdin)) != EOF)
- putc(ch, stdout);
- exit(0);
- }
-
-
- CPBLK.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\11SCREEN\CPBLK.C
-
- /*
- * cpblk -- copy a block of characters and attributes
- * while eliminating "snow" on a standard CGA display
- */
-
- #include <conio.h>
- #include <memory.h>
-
- #define BLKCNT 10
- #define VSTAT 0x3DA
- #define VRBIT 8
- #define WRDCNT 200
- #define NBYTES (2 * WRDCNT)
-
- /* macro to synchronize with vertical retrace period */
- #define VSYNC while ((inp(VSTAT) & VRBIT) == VRBIT); \
- while ((inp(VSTAT) & VRBIT) != VRBIT)
-
- int
- cpblk(src_os, src_seg, dest_os, dest_seg)
- unsigned int src_os, src_seg, dest_os, dest_seg;
- {
- register int i;
- int n;
- register int delta;
-
- n = 0;
- delta = 0;
- for (i = 0; i < BLKCNT ; ++i) {
- /* copy a block of words during vertical retrace */
- VSYNC;
- movedata(src_seg, src_os + delta,
- dest_seg, dest_os + delta, NBYTES);
- n += WRDCNT;
-
- /* adjust buffer offset */
- delta += NBYTES;
- }
-
- return (n);
- }
-
-
- CURBACK.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\CURBACK.C
-
- /*
- * curback -- move cursor back (left); return the
- * value of the new column position
- */
-
- #include <local\bioslib.h>
-
- int
- curback(n, pg)
- int n, pg;
- {
- int r, c;
-
- /*
- * move the cursor left by up to n positions but
- * not past the beginning of the current line
- */
- readcur(&r, &c, pg);
- if (c - n < 0)
- c = 0;
- putcur(r, c, pg);
- return (c);
- }
-
-
- CURSOR.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\CURSOR.C
-
- /*
- * cursor -- interactively set cursor shape
- */
-
- #include <dos.h>
- #include <stdlib.h>
- #include <local\video.h>
- #include <local\keydefs.h>
-
- /* additional drawing characters (others are defined in video.h) */
- #define DOT 254
- #define NO_DOT 196
- #define D_POINT 31
- #define R_POINT 16
- #define L_POINT 17
-
- /* dimensions of the help frame */
- #define BOX_Y 6
- #define BOX_X 30
-
- /* upper-left row and column of big cursor */
- int Ulr;
- int Ulc;
- int Mid;
-
- /* cursor scan-line-selection modes */
- typedef enum { STARTSCAN, ENDSCAN } CMODE;
-
- int
- main()
- {
- int i, j;
- int ch;
- int start, end;
- int height, width;
- static char spoint[] = { "Start\020" }; /* contains right pointer */
- static char epoint[] = { "\021Stop" }; /* contains left pointe
- static char title[] = { "CURSOR: Control cursor shape (V1.0)" };
- unsigned char
- oldattr, /* video attribute upon entry */
- headattr, /* video attribute of header */
- attr, /* primary video attribute */
- standout; /* highlighting video attribute */
- CMODE mode;
-
- static void drawdspy(int, int, int, int, int);
- static void drawstart(int, char *);
- static void drawend(int, int, char *);
- static void drawactive(int, int, CMODE);
- static void showhelp(int, int);
-
- /* get video information and initialize */
- getstate();
- Mid = Vwidth / 2;
- readca(&ch, &oldattr, Vpage); /* preserve user's video attribu
- getctype(&start, &end, Vpage); /* and cursor shape */
- headattr = (WHT << 4) | BLK;
-
- /* set parameters based on video mode (default = CGA) */
- height = width = 8; /* use an 8 by 8 block character cell */
- attr = (BLU << 4) | CYAN | BRIGHT;
- standout = YEL;
- if (Vmode == MDA_M80) {
- /* uses a 14 by 9 dot block character cell */
- height = 14;
- width = 9;
- attr = NORMAL;
- standout = BWHT;
- }
- setctype(height + 1, height + 1); /* cursor off */
-
- /* basic text and layout */
- Ulr = 2;
- Ulc = Mid - width / 2;
- clrscrn(attr);
- putcur(0, 0, Vpage);
- writeca(' ', headattr, Vwidth, Vpage);
- putcur(0, Mid - strlen(title) / 2, Vpage);
- writestr(title, Vpage);
- showhelp(Ulr + height + 1, Mid - BOX_X / 2);
-
- /* interactively select cursor shape */
- mode = STARTSCAN;
- drawdspy(start, end, standout, width, height);
- drawstart(start, spoint);
- drawend(end, width, epoint);
- drawactive(height, width, mode);
- while (1) {
- switch (ch = getkey()) {
- case K_UP:
- /* move up one scan line */
- if (mode == STARTSCAN)
- drawstart(start--, " ");
- else
- drawend(end--, width, " ");
- break;
- case K_DOWN:
- /* move down one scan line */
- if (mode == STARTSCAN)
- drawstart(start++, " ");
- else
- drawend(end++, width, " ");
- break;
- case K_LEFT:
- /* starting scan-line-selection mode */
- mode = STARTSCAN;
- drawactive(height, width, mode);
- continue;
- case K_RIGHT:
- /* ending scan-line-selection mode */
- mode = ENDSCAN;
- drawactive(height, width, mode);
- continue;
- case K_RETURN:
- /* set the new cursor shape */
- setctype(start, end);
- clrscrn(oldattr);
- putcur(0, 0, Vpage);
- exit(0);
- }
-
- /* make corrections at cursor image boundaries */
- if (start < 0)
- start = 0;
- else if (start > height)
- start = height;
- if (end < 0)
- end = 0;
- else if (end >= height)
- end = height - 1;
-
- /* show updated cursor shape and pointers */
- drawdspy(start, end, standout, width, height);
- drawstart(start, spoint);
- drawend(end, width, epoint);
- }
-
- exit(0);
- } /* end main() */
-
-
- /*
- * drawdspy -- draw a magnified image of a cursor with the
- * currently active scan lines depicted as a sequence of dots
- * and inactive lines depicted as straight lines
- */
-
- static void
- drawdspy(s, e, a, w, h)
- int s; /* starting scan line */
- int e; /* ending scan line */
- int a; /* video attribute */
- int w; /* width */
- int h; /* height */
- {
- int i;
-
- /* display an exploded image of each scan line */
- for (i = 0; i < h; ++i) {
- putcur(Ulr + i, Ulc, Vpage);
- if (s >= h)
- /* cursor is effectively off */
- writeca(NO_DOT, a, w, Vpage);
- else if ((s <= e && i >= s && i <= e) || /* a full block */
- (s > e && (i <= e || i >= s))) /* a split blo
- writeca(DOT, a, w, Vpage);
- else
- /* outside start/end range */
- writeca(NO_DOT, a, w, Vpage);
- }
- } /* end drawdspy() */
-
-
- /*
- * drawstart -- display a pointer to the displayed starting
- * scan line in the magnified cursor image
- */
-
- static void
- drawstart(s, sp)
- int s; /* starting scan line number */
- char *sp; /* visual pointer to the displayed starting scan line */
- {
- putcur(Ulr + s, Ulc - strlen(sp), Vpage);
- putstr(sp, Vpage);
- } /* end drawstart() */
-
-
- /*
- * drawend -- display a pointer to the displayed ending
- * scan line in the magnified cursor image
- */
-
- static void
- drawend(e, w, ep)
- int e; /* ending scan line number */
- int w; /* width of the cursor image */
- char *ep; /* visual pointer to the displayed ending scan line */
- {
- putcur(Ulr + e, Ulc + w, Vpage);
- putstr(ep, Vpage);
- } /* end drawend() */
-
- static void
- drawactive(h, w, m)
- int h, w;
- CMODE m;
- {
- int col;
-
- /* clear active selector row */
- putcur(Ulr - 1, Ulc, Vpage);
- writec(' ', w, Vpage);
-
- /* point to active selector */
- col = (m == STARTSCAN) ? 0 : w - 1;
- putcur(Ulr - 1, Ulc + col, Vpage);
- writec(D_POINT, 1, Vpage);
- } /* end drawactive() */
-
- /*
- * showhelp -- display a set of instructions about the
- * use of the cursor program in a fine-ruled box
- */
-
- static void
- showhelp(r, c)
- int r, c; /* upper-left corner of help frame */
- {
- static char title[] = { " Instructions " };
- extern int drawbox(int, int, int, int, int);
-
- /* fine-ruled box */
- clrw(r, c, r + BOX_Y, c + BOX_X, (WHT << 4) | GRN | BRIGHT);
- drawbox(r, c, r + BOX_Y, c + BOX_X, Vpage);
-
- /* centered title */
- putcur(r, c + (BOX_X - strlen(title)) / 2, Vpage);
- putstr(title, Vpage);
-
- /* display symbols and text using brute-force positioning */
- putcur(r + 2, c + 2, Vpage);
- put_ch(LEFTARROW, Vpage);
- put_ch(RIGHTARROW, Vpage);
- putstr(" Change selection mode", Vpage);
- putcur(r + 3, c + 2, Vpage);
- put_ch(UPARROW, Vpage);
- put_ch(DOWNARROW, Vpage);
- putstr(" Select scan lines", Vpage);
- putcur(r + 4, c + 2, Vpage);
- put_ch(L_POINT, Vpage);
- put_ch(LRC11, Vpage);
- putstr(" Set shape and exit", Vpage);
- } /* end showhelp() */
-
-
- DELAY.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\DELAY.C
-
- /*
- * delay -- provide a delay of ** approximately ** the
- * specified duration (resolution is about 0.055 second)
- */
-
- #include <local\timer.h>
-
- void
- delay(d)
- float d; /* duration in seconds and fractional seconds */
- {
- long ticks, then;
- extern long getticks();
-
- /* convert duration to number of PC clock ticks */
- ticks = d * TICKRATE;
-
- /* delay for the specified interval */
- then = getticks() + ticks;
- while (1)
- if (getticks() >= then)
- break;
- }
-
-
- DRAWBOX.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\DRAWBOX.C
-
- /*
- * drawbox -- create a box with IBM line-drawing characters
- */
-
- #include <local\video.h>
-
- int
- drawbox(top, lft, btm, rgt, pg)
- int top, lft, btm, rgt, pg;
- {
- int i;
- int x; /* interior line length for top and bottom segments */
-
- x = rgt - lft - 1;
-
- /* draw the top row */
- putcur(top, lft, pg);
- put_ch(ULC11, pg);
- writec(HBAR1, x, pg);
- putcur(top, rgt, pg);
- put_ch(URC11, pg);
-
- /* draw the sides */
- for (i = 1; i < btm - top; ++i)
- {
- putcur(top + i, lft, pg);
- put_ch(VBAR1, pg);
- putcur(top + i, rgt, pg);
- put_ch(VBAR1, pg);
- }
-
- /* draw the bottom row */
- putcur(btm, lft, pg);
- put_ch(LLC11, pg);
- writec(HBAR1, x, pg);
- putcur(btm, rgt, pg);
- put_ch(LRC11, pg);
- }
-
-
- DRVPATH.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\DOS\DRVPATH.C
-
- /*
- * drvpath -- convert a drive name to a full pathname
- */
-
- #include <stdio.h>
- #include <dos.h>
- #include <string.h>
- #include <ctype.h>
- #include <local\doslib.h>
-
- char *
- drvpath(path)
- char path[]; /* path string */
- /* must be large enough to hold a full DOS path + NUL */
- {
- union REGS inregs, outregs;
- static int drive(char);
-
- /* patch root directory onto drive name */
- strcat(path, "\\");
-
- /* set current directory path for drive from DOS */
- inregs.h.ah = GET_CUR_DIR;
- inregs.h.dl = drive(path[0]); /* convert to drive numb
- inregs.x.si = (unsigned)&path[3]; /* start of return string */
- intdos(&inregs, &outregs);
-
- return (outregs.x.cflag ? (char *)NULL : path);
- }
-
- static int
- drive(dltr)
- char dltr; /* drive letter */
- {
- /* 'A' (or 'a') => 1, 'B' (or 'b') => 2, etc. */
- return (tolower(dltr) - 'a' + 1);
- }
-
-
- DSPYTYPE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\11SCREEN\DSPYTYPE.C
-
- /*
- * dspytype -- determine display adapter type
- */
-
- #include <stdio.h>
- #include <dos.h>
- #include <local\bioslib.h>
- #include <local\video.h>
-
- #define MDA_SEG 0xB000
- #define CGA_SEG 0xB800
-
- main()
- {
- extern int memchk(unsigned int, unsigned int);
- int mdaflag, egaflag, cgaflag;
- int ega_mem, ega_mode;
- unsigned int features, switches;
- static int memtab[] = {
- 64, 128, 192, 256
- };
-
- mdaflag = egaflag = cgaflag = 0;
-
- /* look for display adapters */
- if (ega_info(&ega_mem, &ega_mode, &features, &switches))
- ++egaflag;
- fputs("Enhanced graphics adapter ", stdout);
- if (egaflag) {
- fputs("installed\n", stdout);
- fprintf(stdout, "EGA memory size = %d-KB\n", memtab[ega_mem])
- fprintf(stdout, "EGA is in %s mode\n",
- ega_mode ? "monochrome" : "color");
- }
- else
- fputs("not installed\n", stdout);
-
- if (egaflag && ega_mode == 0) {
- /* look for IBM monochrome memory */
- if (memchk(MDA_SEG, 0))
- ++mdaflag;
- }
- else {
- /* look for IBM monochrome memory */
- if (memchk(CGA_SEG, 0))
- ++cgaflag;
- }
- fputs("Monochrome adapter ", stdout);
- if (mdaflag)
- fputs("installed\n", stdout);
- else
- fputs("not installed\n", stdout);
- fputs("Color/graphics adapter ", stdout);
- if (cgaflag)
- fputs("installed\n", stdout);
- else
- fputs("not installed\n", stdout);
-
- /* report video settings */
- getstate();
- fprintf(stdout, "mode=%d width=%d page=%d\n", Vmode, Vwidth, Vpage);
-
- exit(0);
- }
-
-
- DUMP.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\10DUMP\DUMP.C
-
- /*
- * dump -- display contents of non-ASCII files in hex byte and
- * ASCII character forms (like the DOS debug dump option)
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <sys\types.h>
- #include <sys\stat.h>
- #include <io.h>
- #include <local\std.h>
-
- #define STDINPUT 0
- #define LINEWIDTH 80
-
- main(argc,argv)
- int argc;
- char *argv[];
- {
- int ch;
- BOOLEAN sflag = FALSE,
- vflag = FALSE,
- errflag = FALSE;
- int fd;
- static char pgm[MAXNAME + 1] = { "dump" };
-
- extern int getopt(int, char **, char *);
- extern char *optarg;
- extern int optind, opterr;
- extern void getpname(char *, char *);
- extern int hexdump(int, BOOLEAN);
- extern void fatal(char *, char *, int);
-
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- while ((ch = getopt(argc, argv, "sv")) != EOF)
- switch (ch) {
- case 's': /* strip -- convert all non-ASCII to '.' */
- sflag = TRUE;
- break;
- case 'v': /* verbose -- tell user what's happening */
- vflag = TRUE;
- break;
- case '?': /* bad option */
- errflag = TRUE;
- break;
- }
-
- if (errflag == TRUE) {
- fprintf(stderr, "Usage: %s [-sv] [file...]\n", pgm);
- exit(1);
- }
-
- if (optind == argc) {
- if (setmode(STDINPUT, O_BINARY) == -1)
- fatal(pgm, "Cannot set binary mode", 2);
- hexdump(STDINPUT, sflag);
- exit(0);
- }
-
- for ( ; optind < argc; ++optind) {
- if ((fd = open(argv[optind], O_BINARY | O_RDONLY)) == -1) {
- fprintf(stderr,
- "%s: Error opening %s -- ", pgm, argv[optind]
- perror("");
- continue;
- }
- if (vflag == TRUE)
- fprintf(stdout, "\n%s:\n", argv[optind]);
- if (hexdump(fd, sflag) == FAILURE) {
- fprintf(stderr,
- "%s: Error reading %s -- ", pgm, argv[optind]
- perror("");
- }
- if (close(fd) == -1)
- fatal(pgm, "Error closing input file", 3);
- }
-
- exit(0);
- }
-
-
- EGA_INFO.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\EGA_INFO.C
-
- /*
- * ega_info -- gather information about an EGA;
- * return a non-zero value if one is found
- */
-
- #include <dos.h>
- #include <local\bioslib.h>
-
- #define EGA_INFO 0x10
- #define NMODES 2
- #define NMEMSIZ 4
-
- int
- ega_info(memsize, mode, features, switches)
- int *memsize; /* EGA memory size indicator: 0 = 64K */
- /* 1 = 128K; 2 = 192K; 3 = 256K */
- int *mode; /* 0 = color mode; 1 = mono mode */
- /* use getstate function to find out which mode */
- unsigned int
- *features, /* feature bit settings */
- *switches; /* EGA switch settings */
- {
- int result = 0;
- union REGS inregs, outregs;
-
- /* request EGA information */
- inregs.h.ah = ALT_FUNCTION;
- inregs.h.bl = EGA_INFO;
- int86(VIDEO_IO, &inregs, &outregs);
-
- *memsize = outregs.h.bl;
- *mode = outregs.h.bh;
- *features = outregs.h.ch;
- *switches = outregs.h.cl;
-
- /* return non-zero if EGA installed */
- if (*memsize >= 0 && *memsize < NMEMSIZ && *mode >= 0 && *mode < NMOD
- result = 1;
- return (result);
- }
-
-
- EQUIPCHK.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\EQUIPCHK.C
-
- /*
- * equipchk -- get equipment list
- */
-
- #include <dos.h>
- #include <local\bioslib.h>
- #include <local\equip.h>
-
- struct EQUIP Eq;
-
- int
- equipchk()
- {
- union REGS inregs, outregs;
-
- /* call BIOS equipment check routine */
- int86(EQUIP_CK, &inregs, &outregs);
-
- /* extract data from returned data word */
- Eq.nprint = (outregs.x.ax & 0xC000) / 0x8000;
- Eq.game_io = ((outregs.x.ax & 0x1000) / 0x1000) ? 1 : 0;
- Eq.nrs232 = (outregs.x.ax & 0x0E00) /0x0200;
- Eq.ndrive = ((outregs.x.ax & 0x00C0) / 0x0040) + 1;
- Eq.vmode = (outregs.x.ax & 0x0030) / 0x0010;
- Eq.basemem = ((outregs.x.ax & 0x000C) / 0x0004) + 1;
- Eq.disksys = outregs.x.ax & 0x0001 == 1;
-
- return (outregs.x.cflag);
- }
-
-
- FATAL.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\FATAL.C
-
- /*
- * fatal -- issue a diagnostic message and terminate
- */
-
- #include <stdio.h>
- #include <stdlib.h>
-
- void
- fatal(pname, mesg, errlevel)
- char *pname; /* program name */
- char *mesg; /* message text */
- int errlevel; /* errorlevel (exit code) */
- {
- /* display error message */
- fputs(pname, stderr);
- fputc(':', stderr);
- fputc(' ', stderr);
- fputs(mesg, stderr);
-
- /* return to DOS with the specified errorlevel */
- exit(errlevel);
- }
-
-
- FCONFIG.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\FCONFIG.C
-
- /*
- * fconfig -- return a FILE pointer to a local or
- * global configuration file, or NULL if none found
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- #include <local\std.h>
-
- FILE *
- fconfig(varname, fname)
- char *varname;
- char *fname;
- {
- FILE *fp;
- char pname[MAXPATH + 1];
- char *p;
-
- /* look for a local configuration file */
- if ((fp = fopen(fname, "r")) != NULL)
- return (fp);
-
- /* look for a directory variable */
- if ((p = getenv(strupr(varname))) != NULL) {
- strcpy(pname, p);
- strcat(pname, "\\");
- strcat(pname, fname);
- if ((fp = fopen(pname, "r")) != NULL)
- return (fp);
- }
-
- /* didn't find anything to read */
- return (NULL);
- }
-
-
- FCOPY.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\FCOPY.C
-
- /*
- * fcopy -- copy input stream (fin) to output stream
- * (fout) and return an indication of success or failure
- */
-
- #include <stdio.h>
-
- #define BUFLEN 1024
-
- int
- fcopy(fin, fout)
- FILE *fin, *fout;
- {
- int errcount = 0;
- char line[BUFLEN];
- register char *s;
-
- while ((s = fgets(line, BUFLEN, fin)) != NULL)
- if (fputs(s, fout) == EOF)
- ++errcount;
- if (ferror(fin))
- ++errcount;
- return (errcount); /* 0 if all went well */
- }
-
-
- FIRST_FM.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\DOS\FIRST_FM.C
-
- /*
- * first_fm - find first file match in work directory
- */
-
- #include <dos.h>
- #include <local\doslib.h>
-
- int
- first_fm(path, fa)
- char *path; /* pathname of directory */
- int fa; /* attribute(s) of file to match */
- {
- union REGS inregs, outregs;
-
- /* find first matching file */
- inregs.h.ah = FIND_FIRST;
- inregs.x.cx = fa;
- inregs.x.dx = (unsigned int)path;
- (void)intdos(&inregs, &outregs);
-
- return (outregs.x.cflag);
- }
-
-
- GETCTYPE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\GETCTYPE.C
-
- /*
- * getctype -- pass back cursor type info (scan lines)
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
-
- #define LO_NIBBLE 0x0F
-
- int
- getctype(start_scan, end_scan, pg)
- int *start_scan;/* starting scan line */
- int *end_scan; /* ending scan line */
- int pg; /* "visual" page */
- {
- union REGS inregs, outregs;
-
- inregs.h.bh = pg;
- inregs.h.ah = GET_CUR;
-
- int86(VIDEO_IO, &inregs, &outregs);
-
- /* end_scan = low 4 bits of cl */
- *end_scan = outregs.h.cl & LO_NIBBLE;
-
- /* starting_scan = low 4 bits of ah */
- *start_scan = outregs.h.ch & LO_NIBBLE;
-
- return (outregs.x.cflag);
- }
-
-
- GETDRIVE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\DOS\GETDRIVE.C
-
- /*
- * getdrive -- return the number of the default drive
- */
-
- #include <dos.h>
- #include <local\doslib.h>
-
- int getdrive()
- {
- return (bdos(CURRENT_DISK, 0, 0));
- }
-
-
- GETKEY.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\DOS\GETKEY.C
-
- /*
- * getkey -- return a code for single combo keystrokes
- * - returns a unique code for each keystroke or combination
- * - ignores "Ctrl-Break" input
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\doslib.h>
- #include <local\keydefs.h>
-
- int
- getkey()
- {
- int ch;
-
- /* normal key codes */
- if ((ch = bdos(KEYIN, 0, 0) & LOBYTE) != '\0')
- return (ch);
-
- /* convert scan codes to unique internal codes */
- return ((bdos(KEYIN, 0, 0) & LOBYTE) | XF);
- }
-
-
- GETNAME.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\GETNAME.C
-
- /*
- * getname -- strip drive identifier and directory node
- * list, if any, from a pathname; returns a pointer to
- * the resulting filename[.ext] string or NULL for error
- */
-
- #include <stdio.h>
- #include <sys\types.h>
- #include <sys\stat.h>
-
- #define MAXFSPEC 13
-
- char *
- getname(path)
- char *path; /* string to modify */
- {
- register char *cp; /* character pointer */
- struct stat buf;
-
- /* try to get information about the pathname */
- if (stat(path, &buf) != 0)
- return (NULL); /* bad pathname */
-
- /* locate the end of the pathname string */
- cp = path;
- while (*cp != '\0')
- ++cp;
- --cp; /* went one too far */
-
- /* find the start of the filename part */
- while (cp > path && *cp != '\\' && *cp != ':' && *cp != '/')
- --cp;
- if (cp > path)
- ++cp; /* on a separator (\, :, or /) -- move one past
-
- /* return the full filespec (filename[.ext]) */
- return (cp);
- }
-
-
- GETOPT.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\GETOPT.C
-
- /*
- * Copyright (c) 1984, 1985 AT&T
- * All Rights Reserved
- *
- * ----- Author's Note -----
- * getopt() is reproduced with permission of the AT&T UNIX(R) System
- * Toolchest. This is a public domain version of getopt(3) that is
- * distributed to registered Toolchest participants.
- * Defining DOS_MODS alters the code slightly to obtain compatibility
- * with DOS and support libraries provided with most DOS C compilers.
- */
-
- #define DOS_MODS
-
- #if defined (DOS_MODS)
- /* getopt() for DOS */
- #else
- #ident "@(#)getopt.c 1.9"
- #endif
-
- /* 3.0 SID # 1.2 */
- /*LINTLIBRARY*/
- #define NULL 0
- #define EOF (-1)
-
- /*
- * For this to work under versions of DOS prior to 3.00, argv[0]
- * must be set in main() to point to a valid program name or a
- * reasonable substitute string. (ARH, 10-8-86)
- */
- #define ERR(s, c) if(opterr){\
- char errbuf[2];\
- errbuf[0] = c; errbuf[1] = '\n';\
- (void) write(2, argv[0], (unsigned)strlen(argv[0]));\
- (void) write(2, s, (unsigned)strlen(s));\
- (void) write(2, errbuf, 2);}
-
- #if defined (DOS_MODS)
- /* permit function prototyping under DOS */
- #include <stdlib.h>
- #include <string.h>
- #else
- /* standard UNIX declarations */
- extern int strcmp();
- extern char *strchr();
- /*
- * The following line was moved here from the ERR definition
- * to prevent a "duplicate definition" error message when the
- * code is compiled under DOS. (ARH, 10-8-86)
- */
- extern int strlen(), write();
- #endif
-
- int opterr = 1;
- int optind = 1;
- int optopt;
- char *optarg;
-
- int
- getopt(argc, argv, opts)
- int argc;
- char **argv, *opts;
- {
- static int sp = 1;
- register int c;
- register char *cp;
-
- if(sp == 1)
- if(optind >= argc ||
- argv[optind][0] != '-' || argv[optind][1] == '\0')
- return(EOF);
- else if(strcmp(argv[optind], "--") == NULL) {
- optind++;
- return(EOF);
- }
- optopt = c = argv[optind][sp];
- if(c == ':' || (cp=strchr(opts, c)) == NULL) {
- ERR(": illegal option -- ", c);
- if(argv[optind][++sp] == '\0') {
- optind++;
- sp = 1;
- }
- return('?');
- }
- if(*++cp == ':') {
- if(argv[optind][sp+1] != '\0')
- optarg = &argv[optind++][sp+1];
- else if(++optind >= argc) {
- ERR(": option requires an argument -- ", c);
- sp = 1;
- return('?');
- } else
- optarg = argv[optind++];
- sp = 1;
- } else {
- if(argv[optind][++sp] == '\0') {
- sp = 1;
- optind++;
- }
- optarg = NULL;
- }
- return(c);
- }
-
-
- GETPNAME.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\GETPNAME.C
-
- /*
- * getpname -- extract the base name of a program from
- * the pathname string (deletes a drive specifier, any
- * leading path node information, and the extension)
- */
-
- #include <stdio.h>
- #include <ctype.h>
-
- char *
- getpname(path, pname)
- char *path; /* full or relative pathname */
- char *pname; /* program name pointer */
- {
- register char *cp;
-
- /* find the end of the pathname string */
- cp = path; /* start of pathname */
- while (*cp != '\0')
- ++cp;
- --cp; /* went one too far */
-
- /* find the start of the filename part */
- while (cp > path && *cp != '\\' && *cp != ':' && *cp != '/')
- --cp;
- if (cp > path)
- ++cp; /* move off the pathname separator */
-
- /* copy the filename part only */
- while ((*pname = tolower(*cp)) != '.' && *pname != '\0') {
- ++cp;
- ++pname;
- }
- *pname = '\0';
- }
-
-
- GETREPLY.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\06USER\GETREPLY.C
-
- /*
- * getreply -- display a message and wait for a reply
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <memory.h>
- #include <ctype.h>
- #include <local\std.h>
- #include <local\keydefs.h>
- #include "linebuf.h"
-
- char *
- getreply(row, col, width, mesg, lp, size, attr, pg)
- short row, col, width; /* window location and width */
- char *mesg; /* message text */
- LINEBUF *lp; /* line pointer */
- short size; /* size of line buffer */
- short attr; /* video attribute for response field */
- short pg; /* active display page */
- {
- int n, k, len;
- short mfw; /* message field width */
- short rfw; /* response field width */
- short ccol; /* visible cursor column */
- int msgflag; /* non-zero after a message is displayed */
- char *cp; /* character pointer */
- char *wp; /* pointer to window start */
- char *tmp; /* temporary char pointer */
-
- extern int writemsg(short, short, short, char *, char *, short);
-
- /* display the prompt string and calculate response field width */
- putcur(row, col, pg);
- mfw = writemsg(row, col, width, mesg, NULL, pg);
- rfw = width - mfw;
- writea(attr, rfw, pg);
-
- /* collect the user's response */
- memset(lp->l_buf, '\0', size);
- wp = cp = lp->l_buf;
- putcur(row, col + mfw, pg);
- msgflag = 0;
- while ((k = getkey()) != K_RETURN) {
- if (msgflag) {
- /* clear old messages */
- errmsg("");
- putcur(row, ccol, pg);
- msgflag = 0;
- }
- if (isascii(k) && isprint(k)) {
- len = strlen(cp);
- if (cp + len - lp->l_buf < size - 1) {
- memcpy(cp + 1, cp, len);
- *cp = k;
- ++cp;
- }
- else {
- errmsg("input buffer full");
- ++msgflag;
- }
- }
- else
- switch (k) {
- case K_LEFT:
- /* move left one character */
- if (cp > lp->l_buf)
- --cp;
- break;
- case K_RIGHT:
- /* move right one character */
- if (*cp != '\0')
- ++cp;
- break;
- case K_UP:
- /* pop a line off the stack */
- if (lp->l_prev != NULL) {
- lp = lp->l_prev;
- wp = cp = lp->l_buf;
- }
- break;
- case K_DOWN:
- /* push a line onto the stack */
- if (lp->l_next != NULL) {
- lp = lp->l_next;
- wp = cp = lp->l_buf;
- }
- break;
- case K_HOME:
- /* beginning of buffer */
- cp = lp->l_buf;
- break;
- case K_END:
- /* end of buffer */
- while (*cp != '\0')
- ++cp;
- break;
- case K_CTRLH:
- if (cp > lp->l_buf) {
- tmp = cp - 1;
- memcpy(tmp, cp, strlen(tmp));
- --cp;
- }
- break;
- case K_DEL:
- /* delete character at cursor */
- memcpy(cp, cp + 1, strlen(cp));
- break;
- case K_ESC:
- /* cancel current input */
- lp->l_buf[0] = '\0';
- putcur(row, col, pg);
- writec(' ', width, pg);
- return (NULL);
- default:
- errmsg("unknown command");
- ++msgflag;
- break;
- }
-
- /* adjust the window pointer if necessary */
- if (cp < wp)
- wp = cp;
- else if (cp >= wp + rfw)
- wp = cp + 1 - rfw;
-
- /* display the reply window */
- ccol = col + mfw;
- writemsg(row, ccol, rfw, wp, NULL, pg);
-
- /* reposition the cursor */
- ccol = col + mfw + (cp - wp);
- putcur(row, ccol, pg);
- }
- putcur(row, col, pg);
- writec(' ', width, pg); /* blank message area */
- return (lp->l_buf);
- }
-
-
- GETSTATE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\GETSTATE.C
-
- /*
- * getstate -- update video state structure
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
-
- /* current video state/mode information */
- short Vmode;
- short Vwidth;
- short Vpage;
-
- /*
- * video tables -- these tables of video parameters use
- * a value of -1 to indicate that an item is not supported
- * and 0 to indicate that an item has a variable value.
- */
-
- /* video limit tables */
- short Maxrow[] = {
- /* CGA modes */
- 25, 25, 25, 25, 25, 25, 25,
- /* MDA mode */
- 25,
- /* PCjr modes */
- 25, 25, 25,
- /* not used */
- -1, -1,
- /* EGA modes */
- 25, 25, 25, 25, 43
- };
-
- short Maxcol[] = {
- /* CGA modes */
- 40, 40, 80, 80, 40, 40, 80,
- /* MDA mode */
- 80,
- /* PCjr modes */
- -1, 40, 80,
- /* not used */
- -1, -1,
- /* EGA modes */
- 80, 80, 80, 80
- };
-
- short Maxpage[] = {
- /* CGA modes */
- 8, 8, 4, 4, 1, 1, 1,
- /* MDA mode */
- 1,
- /* PCjr modes */
- 0, 0, 0,
- /* not used */
- -1, -1,
- /* EGA modes */
- 8, 4, 1, 1
- };
-
- int
- getstate()
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = GET_STATE;
- int86(VIDEO_IO, &inregs, &outregs);
-
- Vmode = outregs.h.al;
- Vwidth = outregs.h.ah;
- Vpage = outregs.h.bh;
-
- return (outregs.x.cflag);
- }
-
-
- GETSTR.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\14VIEW\GETSTR.C
-
- /*
- * getstr -- get a string from the keyboard
- */
-
- #include <stdio.h>
- #include <string.h>
- #include <local\std.h>
- #include <local\video.h>
- #include <local\keydefs.h>
-
- char *
- getstr(buf, width)
- char *buf;
- int width;
- {
- int row, col;
- char *cp;
-
- /* function prototypes */
- extern int putcur(int, int, int);
- extern int readcur(int *, int *, int);
- extern int writec(char, int, int);
- extern int getkey();
-
- /* gather keyboard input into a string buffer */
- cp = buf;
- while ((*cp = getkey()) != K_RETURN && cp - buf < width) {
- switch (*cp) {
- case K_CTRLH:
- /* destructive backspace */
- if (cp > buf) {
- readcur(&row, &col, Vpage);
- putcur(row, col - 1, Vpage);
- writec(' ', 1, Vpage);
- --cp;
- }
- continue;
- case K_ESC:
- /* cancel string input operation */
- return (char *)NULL;
- }
- put_ch(*cp, Vpage);
- ++cp;
- }
- *cp = '\0';
- return (buf);
- }
-
-
- GETTICKS.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\GETTICKS.C
-
- /*
- * getticks -- get the current bios clock ticks value
- */
-
- #include <dos.h>
- #include <local\bioslib.h>
-
- long
- getticks()
- {
- long count;
- union REGS inregs, outregs;
-
- /* get BIOS time of day as no. of ticks since midnight */
- inregs.h.ah = 0;
- int86(TOD, &inregs, &outregs);
-
- /* correct for possible rollover at 24 hours */
- count = (outregs.h.al != 0) ? 0x01800B0L : 0;
-
- /* add current day ticks */
- count += (outregs.x.dx + (outregs.x.cx << 16));
-
- return (count);
- }
-
-
- GETXLINE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\GETXLINE.C
-
- /*
- * getxline -- get a line of text while expanding tabs,
- * put text into an array, and return a pointer to the
- * resulting null-terminated line
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- #include <local\std.h>
-
- char *
- getxline(buf, size, fin)
- char *buf;
- int size;
- FILE *fin;
- {
- register int ch; /* input character */
- register char *cp; /* character pointer */
-
- extern BOOLEAN tabstop(int);
-
- cp = buf;
- while (--size > 0 && (ch = fgetc(fin)) != EOF) {
- if (ch == '\n') {
- *cp++ = ch;
- break;
- }
- else if (ch == '\t')
- do {
- *cp = ' ';
- } while (--size > 0 && (tabstop(++cp - buf) == FALSE)
- else
- *cp++ = ch & ASCII;
- }
- *cp = '\0';
- return ((ch == EOF && cp == buf) ? NULL : buf);
- }
-
-
- HEX.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\HEX.C
-
- /*
- * hex.c -- hex conversions routines
- */
-
- #define NIBBLE 0x000F
-
- char hextab[] = {
- '0', '1', '2', '3', '4', '5', '6', '7',
- '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
- };
-
- /*
- * byte2hex -- convert a byte to a string
- * representation of its hexadecimal value
- */
-
- char *
- byte2hex(data, buf)
- unsigned char data;
- char *buf;
- {
- register char *cp;
-
- cp = buf;
- *cp++ = hextab[(data >> 4) & NIBBLE];
- *cp++ = hextab[data & NIBBLE];
- *cp = '\0';
-
- return (buf);
- } /* end byte2hex() */
-
- /*
- * word2hex -- convert a word to a string
- * representation of its hexadecimal value
- */
-
- char *
- word2hex(data, buf)
- unsigned int data;
- char *buf;
- {
- register char *cp;
-
- cp = buf;
- *cp++ = hextab[(data >> 12) & NIBBLE];
- *cp++ = hextab[(data >> 8) & NIBBLE];
- *cp++ = hextab[(data >> 4) & NIBBLE];
- *cp++ = hextab[data & NIBBLE];
- *cp = '\0';
-
- return (buf);
- } /* end word2hex() */
-
-
- HEX.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\10DUMP\HEX.C
-
- /*
- * hex.c -- hex conversions routines
- */
-
- #define NIBBLE 0x000F
- #define BYTE 0x00FF
- #define WORD 0xFFFF
-
- char hextab[] = {
- '0', '1', '2', '3', '4', '5', '6', '7',
- '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
- };
-
- /*
- * byte2hex -- convert a byte to a string
- * representation of its hexadecimal value
- */
-
- char *
- byte2hex(data, buf)
- unsigned char data;
- char *buf;
- {
- char *cp;
- unsigned int d;
-
- d = data & BYTE;
- cp = buf;
- *cp++ = hextab[(d >> 4) & NIBBLE];
- *cp++ = hextab[d & NIBBLE];
- *cp = '\0';
-
- return (buf);
- }
-
- /*
- * word2hex -- convert a word to a string
- * representation of its hexadecimal value
- */
-
- char *
- word2hex(data, buf)
- unsigned int data;
- char *buf;
- {
- char *cp;
- unsigned int d;
-
- d = data & WORD;
- cp = buf;
- *cp++ = hextab[(d >> 12) & NIBBLE];
- *cp++ = hextab[(d >> 8) & NIBBLE];
- *cp++ = hextab[(d >> 4) & NIBBLE];
- *cp++ = hextab[d & NIBBLE];
- *cp = '\0';
-
- return (buf);
- }
-
-
- HEXDUMP.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\10DUMP\HEXDUMP.C
-
- /*
- * hexdump -- read data from an open file and "dump"
- * it in side-by-side hex and ASCII to standard output
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- #include <local\std.h>
-
- #define LINEWIDTH 80
- #define NBYTES 16
- #define WORD 0xFFFF
- #define RGHTMARK 179
- #define LEFTMARK 179
- #define DEL 0x7F
-
- int hexdump(fd, strip)
- int fd;
- BOOLEAN strip;
- {
- unsigned char i;
- int n; /* bytes per read operation */
- unsigned long offset; /* bytes from start of file */
- char inbuf[BUFSIZ + 1], outbuf[LINEWIDTH + 1];
- char hexbuf[5];
- register char *inp, *outp;
-
- extern char *byte2hex(unsigned char, char *);
- extern char *word2hex(unsigned int, char *);
-
- offset = 0;
- while ((n = read(fd, inbuf, BUFSIZ)) != 0) {
- if (n == -1)
- return FAILURE;
- inp = inbuf;
- while (inp < inbuf + n) {
- outp = outbuf;
-
- /* offset in hex */
- outp += sprintf(outp, "%08lX",
- offset + (unsigned long)(inp - inbuf));
- *outp++ = ' ';
-
- /* block of bytes in hex */
- for (i = 0; i < NBYTES; ++i) {
- *outp++ = ' ';
- strcpy(outp, byte2hex(*inp++, hexbuf));
- outp += 2;
- }
- *outp++ = ' ';
- *outp++ = ' ';
- *outp++ = (strip == TRUE) ? '|' : LEFTMARK;
-
- /* same block of bytes in ASCII */
- inp -= NBYTES;
- for (i = 0; i < NBYTES; ++i) {
- if (strip == TRUE && (*inp < ' ' || *inp >= D
- *outp = '.';
- else if (iscntrl(*inp))
- *outp = '.';
- else
- *outp = *inp;
- ++inp;
- ++outp;
- }
- *outp++ = (strip == TRUE) ? '|' : RGHTMARK;
- *outp++ = '\n';
- *outp = '\0';
- fputs(outbuf, stdout);
- }
- offset += n;
- }
- return SUCCESS;
- }
-
-
- INTERVAL.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\06USER\INTERVAL.C
-
- /*
- * interval -- report the interval given in seconds as
- * a human-readable null-terminated string
- */
-
- #include <stdio.h>
-
- char *
- interval(seconds, buf)
- long seconds;
- char *buf;
- {
- int hh, mm, ss;
- long remainder;
-
- /* calculate the values */
- hh = seconds / 3600;
- remainder = seconds % 3600;
- mm = remainder / 60;
- ss = remainder - (mm * 60);
- sprintf(buf, "%02d:%02d:%02d\0", hh, mm, ss);
-
- return (buf);
- }
-
-
- ISCOLOR.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\ISCOLOR.C
-
- /*
- * iscolor -- return TRUE if a color display system is
- * in use and is set to one of the text modes
- */
-
- #include <local\std.h>
- #include <local\video.h>
-
- BOOLEAN
- iscolor()
- {
- getstate();
- if (Vmode != CGA_C40 || Vmode != CGA_C80)
- return TRUE;
- return FALSE;
- }
-
-
- KBD_STAT.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\KBD_STAT.C
-
- /*
- * kbd_stat -- return the keyboard status
- * word (bit-significant)
- */
-
- #include <dos.h>
- #include <local\bioslib.h>
- #include <local\keybdlib.h>
-
- unsigned char
- kbd_stat()
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = KBD_STATUS;
- int86(KEYBD_IO, &inregs, &outregs);
-
- return ((unsigned char)(outregs.h.al));
- }
-
-
- KEYREADY.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\DOS\KEYREADY.C
-
- /*
- * keyready -- non-zero if the keyboard buffer
- * has any codes waiting
- */
-
- #include <dos.h>
- #include <local\doslib.h>
-
- int
- keyready()
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = CH_READY;
- intdos(&inregs, &outregs);
-
- return (outregs.h.al);
- }
-
-
- LAST_CH.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\LAST_CH.C
-
- /*
- * last_ch -- return a copy of the last character
- * before the NUL byte in a string
- */
-
- char
- last_ch(s)
- char *s;
- {
- register char *cp;
-
- /* find end of s */
- cp = s;
- while (*cp != '\0')
- ++cp;
-
- /* return previous character */
- --cp;
- return (*cp);
- }
-
-
- LINES.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\LINES.C
-
- /*
- * lines -- send newlines to the output stream
- */
-
- #include <stdio.h>
- #include <stdlib.h>
-
- int
- lines(n, fp)
- int n;
- FILE *fp;
- {
- register int i;
-
- for (i = 0; i < n; ++i)
- if (putc('\n', fp) == EOF && ferror(fp))
- break;
-
- /* return number of newlines emitted */
- return (i);
- }
-
-
- LS.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\08FILE\LS.C
-
- /*
- * ls -- display a directory listing
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <memory.h>
- #include <dos.h>
- #include <direct.h>
- #include <signal.h>
- #include <search.h>
- #include <local\std.h>
- #include <local\doslib.h>
- #include "ls.h"
-
- /* allocation quantities */
- #define N_FILES 256
- #define N_DIRS 16
-
- /* global data */
- int Multicol = 0;
- int Filetype = 0;
- int Hidden = 0;
- int Longlist = 0;
- int Reverse = 0;
- int Modtime = 0;
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- int ch, i;
- int errflag; /* error flag */
- char *ep; /* environment pointer */
- int status = 0; /* return status value */
- int fileattr; /* file attribute number */
- struct DTA buf; /* private disk buffer */
- char path[MAXPATH + 1]; /* working pathname */
- struct OUTBUF *fp, *fq; /* pointers to file array */
- char **dp, **dq; /* pointer to directory pointer array */
- int fbc = 1; /* file memory block allocation count */
- int dbc = 1; /* directory memory block allocation coun
- int nfiles; /* number of file elements */
- int ndirs; /* number of directory elements */
-
- static char pgm[MAXNAME + 1] = { "ls" };
-
- /* function prototypes */
- void getpname(char *, char *);
- extern int getopt(int, char **, char *);
- extern int optind, opterr;
- extern char *optarg;
- extern char *drvpath(char *);
- extern void fatal(char *, char *, int);
- extern void setdta(char *);
- extern int first_fm(char *, int);
- extern int next_fm();
- extern int ls_fcomp(struct OUTBUF *, struct OUTBUF *);
- extern int ls_dcomp(char *, char *);
- extern int ls_single(struct OUTBUF *, int);
- extern int ls_multi(struct OUTBUF *, int);
- extern int ls_dirx(char *, char *);
- int bailout();
-
- /* guarantee that needed DOS services are available */
- if (_osmajor < 2)
- fatal(pgm, "ls requires DOS 2.00 or later", 1);
-
- /* get program name from DOS (version 3.00 and later) */
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- /* useful aliases (DOS version 3.00 and later) */
- if (strcmp(pgm, "lc") == 0)
- ++Multicol;
- if (strcmp(pgm, "lf") == 0) {
- ++Multicol;
- ++Filetype;
- }
-
- /* prepare for emergencies */
- if (signal(SIGINT, bailout) == (int(*)())-1) {
- perror("Can't set SIGINT");
- exit(2);
- }
-
- /* process optional arguments first */
- errflag = 0;
- while ((ch = getopt(argc, argv, "aCFlrt")) != EOF)
- switch (ch) {
- case 'a':
- /* all files (hidden, system, etc.) */
- ++Hidden;
- break;
- case 'C':
- ++Multicol;
- break;
- case 'F':
- /* show file types (/=directory, *=executable) */
- ++Filetype;
- break;
- case 'l':
- /* long list (overrides multicolumn) */
- ++Longlist;
- break;
- case 'r':
- /* reverse sort */
- ++Reverse;
- break;
- case 't':
- /* sort by file modification time */
- ++Modtime;
- break;
- case '?':
- errflag = TRUE;
- break;
- }
- argc -= optind;
- argv += optind;
-
- /* check for command-line errors */
- if (argc < 0 || errflag) {
- fprintf(stderr, "Usage: %s [-aCFlrt] [pathname ...]", pgm);
- exit(3);
- }
-
- /* allocate initial file and directory storage areas */
- dp = dq = (char **)malloc(N_DIRS * sizeof (char *));
- if (dp == NULL)
- fatal(pgm, "Out of memory", 4);
- fp = fq = (struct OUTBUF *)malloc(N_FILES * sizeof (struct OUTBUF));
- if (fp == NULL)
- fatal(pgm, "Out of memory", 4);
- nfiles = ndirs = 0;
-
- /* use current directory if no args */
- if (argc == 0) {
- if (getcwd(path, MAXPATH) == NULL)
- fatal(pgm, "Cannot get current directory", 5);
- *dq = path;
- ndirs = 1;
- }
- else {
- /* use arguments as file and directory names */
- for ( ; argc-- > 0; ++argv) {
- strcpy(path, *argv);
- if (path[0] == '\\') {
- /* prepend default drive name */
- memcpy(path + 2, path, strlen(path) + 1);
- path[0] = 'a' + getdrive();
- path[1] = ':';
- }
- if (path[1] == ':' && path[2] == '\0' && drvpath(path
- fprintf(stderr, "%s: Cannot get drive path",
- continue;
- }
-
- /* establish private disk transfer area */
- setdta((char *)&buf);
-
- /* set file attribute for search */
- if (Hidden)
- fileattr = SUBDIR | HIDDEN | SYSTEM | READONL
- else
- fileattr = SUBDIR;
- if (first_fm(path, fileattr) != 0 && path[3] != '\0')
- fprintf(stderr, "%s -- No such file or direct
- continue;
- }
- if ((buf.d_attr & SUBDIR) == SUBDIR || path[3] == '\0
- /* path is a (sub)directory */
- *dq = strdup(path);
- if (++ndirs == dbc * N_DIRS) {
- ++dbc; /* increase space requi
- dp = (char **)realloc(dp, dbc * N_DIR
- if (dp == NULL)
- fatal(pgm, "Out of memory", 4
- dq = dp + dbc * N_DIRS;
- }
- else
- ++dq;
- }
- else {
- fq->o_name = strdup(path);
- fq->o_mode = buf.d_attr;
- fq->o_date = buf.d_mdate;
- fq->o_time = buf.d_mtime;
- fq->o_size = buf.d_fsize;
- if (++nfiles == fbc * N_FILES) {
- ++fbc;
- fp = (struct OUTBUF *)realloc(fp, fbc
- if (fp == NULL)
- fatal(pgm, "Out of memory", 4
- fq = fp + fbc * N_FILES;
- }
- else
- ++fq;
- }
- }
- }
-
- /* output file list, if any */
- if (nfiles > 0) {
- qsort(fp, nfiles, sizeof(struct OUTBUF), ls_fcomp);
- if (Longlist)
- ls_long(fp, nfiles);
- else if (Multicol)
- ls_multi(fp, nfiles);
- else
- ls_single(fp, nfiles);
- putchar('\n');
- }
- free(fp);
-
- /* output directory lists, if any */
- if (ndirs == 1 && nfiles == 0) {
- /* expand directory and output without header */
- if (ls_dirx(pgm, *dp))
- fprintf(stderr, "%s -- empty directory\n", strlwr(*dp
- }
- else if (ndirs > 0) {
- /* expand each directory and output with headers */
- dq = dp;
- qsort(dp, ndirs, sizeof(char *), ls_dcomp);
- while (ndirs-- > 0) {
- fprintf(stdout, "%s:\n", strlwr(*dq));
- if (ls_dirx(pgm, *dq++))
- fprintf(stderr, "%s -- empty directory\n",
- strlwr(*dq));
- putchar('\n');
- }
- }
-
- exit(0);
- }
-
- /*
- * bailout -- optionally terminate upon interrupt
- */
- int
- bailout()
- {
- char ch;
-
- signal(SIGINT, bailout);
- printf("\nTerminate directory listing? ");
- scanf("%1s", &ch);
- if (ch == 'y' || ch == 'Y')
- exit(1);
- }
-
-
- LS_DIRX.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\08FILE\LS_DIRX.C
-
- /*
- * ls_dirx -- expand the contents of a directory using
- * the DOS first/next matching file functions
- */
-
- #define DEBUG
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <malloc.h>
- #include <dos.h>
- #include <direct.h>
- #include <signal.h>
- #include <search.h>
- #include <local\std.h>
- #include <local\doslib.h>
- #include "ls.h"
-
- #define NFILES 1024
-
- extern int Recursive;
- extern int Longlist;
- extern int Multicol;
- extern int Hidden;
-
- int
- ls_dirx(pname, namep)
- char *pname;
- char *namep;
- {
- int status = 0; /* function return value */
- int n; /* number of items found */
- int fileattr; /* attributes of file-matching *
- struct DTA buf; /* disk transfer area */
- struct OUTBUF *bp, *bq; /* output buffer pointers */
- char path[MAXPATH + 1]; /* working path string */
-
- extern void setdta(char *);
- extern int first_fm(char *, int);
- extern int next_fm();
- extern int ls_fcomp(struct OUTBUF *, struct OUTBUF *);
- extern char last_ch(char *);
-
- /* allocate a buffer */
- bp = bq = (struct OUTBUF *)malloc(NFILES * sizeof(struct OUTBUF));
- if (bp == NULL)
- fatal(pname, "Out of memory");
-
- /* form name for directory search */
- strcpy(path, namep);
- if (last_ch(path) != '\\')
- strcat(path, "\\");
- strcat(path, "*.*");
-
- /* list the files found */
- n = 0;
- /* establish a private DTA */
- setdta((char *)&buf);
- /* select file attributes */
- if (Hidden)
- fileattr = SUBDIR | HIDDEN | SYSTEM | READONLY;
- else
- fileattr = SUBDIR;
- if (first_fm(path, fileattr) == 0) {
- /* add file or directory to the buffer */
- do {
- if (!Hidden && buf.d_fname[0] == '.')
- continue;
- bq->o_name = strdup(buf.d_fname);
- bq->o_mode = buf.d_attr;
- bq->o_size = buf.d_fsize;
- bq->o_date = buf.d_mdate;
- bq->o_time = buf.d_mtime;
- ++bq;
- ++n;
- setdta((char *)&buf); /* reset to our DTA */
- } while (next_fm() == 0);
-
- if (n > 0) {
- /* got some -- sort and list them */
- qsort(bp, n, sizeof(struct OUTBUF), ls_fcomp);
- if (Longlist)
- ls_long(bp, n);
- else if (Multicol)
- ls_multi(bp, n);
- else
- ls_single(bp, n);
- }
- }
- else
- ++status;
- free(bp);
-
- return (status);
- }
-
-
- LS_FCOMP.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\08FILE\LS_FCOMP.C
-
- /*
- * ls_fcomp -- file and directory comparison functions
- */
-
- #include <string.h>
- #include "ls.h"
-
- extern int Modtime;
- extern int Reverse;
-
-
- /*
- * ls_fcomp -- compare two "file" items
- */
-
- int
- ls_fcomp(s1, s2)
- struct OUTBUF *s1, *s2;
- {
- int result;
-
- if (Modtime) {
- if ((result = s1->o_date - s2->o_date) == 0)
- result = s1->o_time - s2->o_time;
- }
- else
- result = strcmp(s1->o_name, s2->o_name);
-
- return (Reverse ? -result : result);
- } /* end_fcomp() */
-
-
- /*
- * dcomp -- compare two "directory" items
- */
-
- int
- ls_dcomp(s1, s2)
- char *s1, *s2;
- {
- int result;
-
- result = strcmp(s1, s2);
-
- return (Reverse ? -result : result);
- } /* end ls_dcomp() */
-
-
- LS_LIST.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\08FILE\LS_LIST.C
-
- /*
- * ls_list -- list functions (long, single, multi) for ls
- */
-
- #include <stdio.h>
- #include <string.h>
- #include "ls.h"
-
- #define MAXCOL 80
- #define MONTH_SHIFT 5
- #define MONTH_MASK 0x0F
- #define DAY_MASK 0x1F
- #define YEAR_SHIFT 9
- #define DOS_EPOCH 80
- #define HOUR_SHIFT 11
- #define HOUR_MASK 0x1F
- #define MINUTE_SHIFT 5
- #define MINUTE_MASK 0x3F
-
- extern int Filetype;
-
- /*
- * ls_long -- list items in "long" format (mode time size name)
- */
-
- int
- ls_long(buf, nelem)
- struct OUTBUF *buf;
- int nelem;
- {
- int n = 0;
- char modebuf[5];
- static void modestr(unsigned short, char *);
-
- while (nelem-- > 0) {
- /* convert mode number to a string */
- modestr(buf->o_mode, modebuf);
- printf("%s ", modebuf);
-
- /* display file size in bytes */
- if ((buf->o_mode & SUBDIR) == SUBDIR)
- printf(" ");
- else
- printf("%7ld ", buf->o_size);
-
- /* convert date and time values to formatted presentation */
- printf("%02d-%02d-%02d ", (buf->o_date >> MONTH_SHIFT) & MONT
- buf->o_date & DAY_MASK, (buf->o_date >> YEAR_SHIFT) +
- printf("%02d:%02d ", (buf->o_time >> HOUR_SHIFT) & HOUR_MASK,
- (buf->o_time >> MINUTE_SHIFT) & MINUTE_MASK);
-
- /* display filenames as lowercase strings */
- printf("%s\n", strlwr(buf->o_name));
-
- ++buf;
- ++n;
- }
-
- /* tell caller how many entries were printed */
- return (n);
- } /* end ls_long() */
-
-
- /*
- * ls_single -- list items in a single column
- */
-
- int
- ls_single(buf, nelem)
- struct OUTBUF *buf;
- int nelem;
- {
- int n = 0;
-
- while (nelem-- > 0) {
- printf("%s", strlwr(buf->o_name));
- if (Filetype && (buf->o_mode & SUBDIR) == SUBDIR)
- putchar('\\');
- putchar('\n');
- ++buf;
- ++n;
- }
-
- /* tell caller how many entries were printed */
- return (n);
- } /* end ls_single() */
-
-
- /*
- * ls_multi -- list items in multiple columns that
- * vary in width and number based on longest item size
- */
-
- int
- ls_multi(buf, nelem)
- struct OUTBUF *buf;
- int nelem;
- {
- int i, j;
- int errcount = 0;
- struct OUTBUF *tmp; /* temporary buffer pointer */
- struct OUTBUF *base; /* buffer pointer for multi-col output */
- int n; /* number of items in list */
- int len, maxlen; /* pathname lengths */
- int ncols; /* number of columns to output */
- int nlines; /* number of lines to output */
-
- /*
- * get length of longest pathname and calculate number
- * of columns and lines (col width = maxlen + 1)
- */
- tmp = buf;
- n = 0;
- maxlen = 0;
- for (tmp = buf, n = 0; n < nelem; ++tmp, ++n)
- if ((len = strlen(tmp->o_name)) > maxlen)
- maxlen = len;
- /*
- * use width of screen - 1 to allow for newline at end of
- * line and leave two spaces between entries (one for optional
- * file type flag)
- */
- ncols = (MAXCOL - 1) / (maxlen + 2);
- nlines = n / ncols;
- if (n % ncols)
- ++nlines;
-
- /* output multi-column list */
- base = buf;
- for (i = 0; i < nlines; ++i) {
- tmp = base;
- for (j = 0; j < ncols; ++j) {
- len = maxlen + 2;
- len -= printf("%s", strlwr(tmp->o_name));
- if (Filetype && (tmp->o_mode & SUBDIR) == SUBDIR) {
- putchar('\\');
- --len;
- }
- while (len-- > 0)
- putchar(' ');
- tmp += nlines;
- if (tmp - buf >= nelem)
- break;
- }
- putchar('\n');
- ++base;
- }
-
- return (errcount);
- } /* end ls_multi() */
-
-
- static void
- modestr(mode, s)
- unsigned short mode; /* file mode number */
- char s[]; /* mode string buffer */
- {
-
- /* fill in the mode string to show what's set */
- s[0] = (mode & SUBDIR) == SUBDIR ? 'd' : '-';
- s[1] = (mode & HIDDEN) == HIDDEN ? 'h' : '-';
- s[2] = (mode & SYSTEM) == SYSTEM ? 's' : '-';
- s[3] = (mode & READONLY) == READONLY ? 'r' : '-';
- s[4] = '\0';
- } /* end modestr() */
-
-
- MEMCHK.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\MEMCHK.C
-
- /*
- * memchk -- look for random-access memory at
- * a specified location; return non-zero if found
- */
-
- #include <dos.h>
- #include <memory.h>
-
- int
- memchk(seg, os)
- unsigned int seg;
- unsigned int os;
- {
- unsigned char tstval, oldval, newval;
- unsigned int ds;
- struct SREGS segregs;
-
- /* get value of current data segment */
- segread(&segregs);
- ds = segregs.ds;
-
- /* save current contents of test location */
- movedata(seg, os, ds, (unsigned int)&oldval, 1);
-
- /* copy a known value into test location */
- tstval = 0xFC;
- movedata(ds, (unsigned int)&tstval, seg, os, 1);
-
- /* read test value back and comapre to value written */
- movedata(seg, os, ds, (unsigned int)&newval, 1);
- if (newval != tstval)
- return (0);
-
- /* restore original contents of test location */
- movedata(ds, (unsigned int)&oldval, seg, os, 1);
-
- return (1);
- }
-
-
- MEMSIZE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\MEMSIZE.C
-
- /*
- * memsize -- get memory size
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
-
- int
- memsize()
- {
- union REGS inregs, outregs;
-
- return (int86(MEM_SIZE, &inregs, &outregs));
- }
-
-
- MENUMODE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\13ANSI\MENUMODE.C
-
- /*
- * menumode -- process user commands interactively
- */
-
- #include <stdio.h>
- #include <local\ansi.h>
- #include <local\ibmcolor.h>
- #include <local\keydefs.h>
-
- /* maximum color number */
- #define MAX_CNUM 15
-
- void
- menumode()
- {
- register int ch;
- int foreground, background, border;
- extern void setattr(POSITION, int);
- extern void sc_cmds(int, int, int);
-
- /* default attributes */
- foreground = IBM_WHITE;
- background = IBM_BLACK;
- border = IBM_BLACK;
-
- ANSI_SGR(ANSI_NORMAL);
- setattr(FGND, foreground);
- setattr(BKGND, background);
- ANSI_ED;
- palette(0, border);
- sc_cmds(foreground, background, border);
- while ((ch = getkey()) != K_RETURN) {
- switch (ch) {
- case K_F1:
- /* decrement foreground color */
- if (--foreground < 0)
- foreground = MAX_CNUM;
- break;
- case K_F2:
- /* increment foreground color */
- if (++foreground > MAX_CNUM)
- foreground = 0;
- break;
- case K_F3:
- /* decrement background color */
- if (--background < 0)
- background = MAX_CNUM;
- break;
- case K_F4:
- /* increment background color */
- if (++background > MAX_CNUM)
- background = 0;
- break;
- case K_F5:
- /* decrement border color */
- if (--border < 0)
- border = MAX_CNUM;
- break;
- case K_F6:
- /* increment border color number */
- if (++border > MAX_CNUM)
- border = 0;
- break;
- default:
- continue;
- }
- ANSI_SGR(ANSI_NORMAL);
- setattr(FGND, foreground);
- setattr(BKGND, background);
- palette(0, border);
- ANSI_ED;
- sc_cmds(foreground, background, border);
- }
- return;
- }
-
-
- MESSAGE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\14VIEW\MESSAGE.C
-
- /*
- * message -- routines used to display and clear
- * messages in a reserved message area
- */
-
- #include "message.h"
-
- MESSAGE Ml;
- extern int writec(char, int, int);
-
- /*
- * set up the message-line manager
- */
-
- void
- initmsg(r, c, w, a, pg)
- int r; /* message row */
- int c; /* message column */
- int w; /* width of message field */
- unsigned char a; /* message field video attribute */
- int pg; /* active page for messages */
- {
- MESSAGE *mp;
- void clrmsg();
-
- mp = &Ml;
- mp->m_row = r;
- mp->m_col = c;
- mp->m_wid = w;
- mp->m_attr = a;
- mp->m_pg = pg;
- mp->m_flag = 1;
- clrmsg();
- }
-
-
- /*
- * showmsg -- display a message and set the message flag
- */
-
- void
- showmsg(msg)
- char *msg;
- {
- MESSAGE *mp;
-
- mp = &Ml;
- putcur(mp->m_row, mp->m_col, mp->m_pg);
- writec(' ', mp->m_wid, mp->m_pg);
- putstr(msg, mp->m_pg);
- mp->m_flag = 1;
- return;
- }
-
-
- /*
- * clrmsg -- erase the message area and reset the message flag
- */
-
- void
- clrmsg()
- {
- MESSAGE *mp;
-
- mp = &Ml;
- if (mp->m_flag != 0) {
- putcur(mp->m_row, mp->m_col, mp->m_pg);
- writec(' ', mp->m_wid, mp->m_pg);
- mp->m_flag = 0;
- }
- return;
- }
-
-
- MX.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\07CONFIG\MX.C
-
- /*
- * mx -- control Epson MX-series printer
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <local\std.h>
- #include <local\printer.h>
-
- extern PRINTER prt; /* printer data */
-
- main(argc, argv)
- int argc;
- char **argv;
- {
- int ch, font;
- BOOLEAN errflag; /* option error */
- BOOLEAN clrflag; /* clear special fonts */
- BOOLEAN rflag; /* hardware reset */
- BOOLEAN tflag; /* top-of-form */
- FILE *fout;
- static char pgm[MAXNAME + 1] = { "mx" };
-
- extern void fatal(char *, char *, int);
- extern char *getpname(char *, char *);
- extern int getopt(int, char **, char *);
- extern char *optarg;
- extern int optind, opterr;
- extern int setprnt();
- extern int clrprnt(FILE *);
- extern int setfont(int, FILE *);
-
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- if (setprnt() == -1) {
- fprintf(stderr, "%s: Bad printer configuration\n", pgm);
- exit(1);
- }
-
- /* interpret command line */
- errflag = clrflag = rflag = tflag = FALSE;
- font = 0;
- fout = stdprn;
- while ((ch = getopt(argc, argv, "bcdefino:prtu")) != EOF) {
- switch (ch) {
- case 'b':
- /* set bold */
- font |= EMPHASIZED;
- break;
- case 'c':
- /* set compressed */
- font |= CONDENSED;
- break;
- case 'd':
- /* set double strike */
- font |= DOUBLE;
- break;
- case 'e':
- /* set double strike */
- font |= EXPANDED;
- break;
- case 'i':
- /* set italic */
- font |= ITALICS;
- break;
- case 'n':
- /* set normal (clear all special fonts) */
- clrflag = TRUE;
- break;
- case 'o':
- /* use specified output stream */
- if ((fout = fopen(optarg, "w")) == NULL)
- fatal(pgm, "cannot open output stream", 1);
- break;
- case 'p':
- /* preview control strings on stdout */
- fout = stdout;
- break;
- case 'r':
- /* hardware reset */
- rflag = TRUE;
- break;
- case 't':
- /* top of form */
- tflag = TRUE;
- break;
- case 'u':
- /* set underline */
- font |= UNDERLINE;
- break;
- case '?':
- /* unknown option */
- errflag = TRUE;
- break;
- }
- }
-
- /* report errors, if any */
- if (errflag == TRUE || argc == 1) {
- fprintf(stderr, "Usage: %s -option\n", pgm);
- fprintf(stderr,
- "b=bold, c=compressed, d=double strike, e=expanded\n"
- fprintf(stderr,
- "i=italic, n=normal, o file=output to file\n");
- fprintf(stderr,
- "p=preview, r=reset, t=top-of-form, u=underline\n");
- exit(2);
- }
-
- /* do hardware reset and formfeed first */
- if (rflag == TRUE)
- fputs(prt.p_init, fout);
- else if (tflag == TRUE)
- fputc('\f', fout);
-
- /* clear or set the aggregate font */
- if (clrflag == TRUE)
- clrprnt(fout);
- else if (setfont(font, fout) == FAILURE) {
- fprintf(stderr, "%s: Bad font spec\n", pgm);
- exit(3);
- }
-
- exit(0);
- }
-
-
- NEXT_FM.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\DOS\NEXT_FM.C
-
- /*
- * next_fm - find next file match in work directory
- */
-
- #include <dos.h>
- #include <local\doslib.h>
-
- int
- next_fm()
- {
- union REGS inregs, outregs;
-
- /* find next matching file */
- inregs.h.ah = FIND_NEXT;
- (void)intdos(&inregs, &outregs);
-
- return (outregs.x.cflag);
- }
-
-
- NLERASE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\NLERASE.C
-
- /*
- * nlerase -- replace the first newline in a string
- * with a null character
- */
-
- char *
- nlerase(s)
- char *s;
- {
- register char *cp;
-
- cp = s;
- while (*cp != '\n' && *cp != '\0')
- ++cp;
- *cp = '\0';
-
- return (s);
- }
-
-
- NOTES1.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\04STDLIB\NOTES1.C
-
- /*
- * notes1 -- add an entry to a "notes" text file
- *
- * version 1: appends new data to NOTES.TXT in the
- * current directory -- uses local date/time stamp
- * as a header for each new entry
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <local\std.h>
-
- main()
- {
- FILE *fp;
- static char notesfile[MAXPATH + 1] = { "notes.txt" };
- char ch;
- long ltime;
- static char pgm[MAXNAME + 1] = { "notes1" };
-
- extern void fatal(char *, char *, int);
-
- /* try to open notes file in current directory */
- if ((fp = fopen(notesfile, "a")) == NULL)
- fatal(pgm, notesfile, 1);
-
- /* append a header and date/time tag */
- ltime = time(NULL);
- fprintf(stderr, "Appending to %s: %s",
- notesfile, ctime(<ime));
- fprintf(fp, "%s", ctime(<ime));
-
- /* append new text */
- while ((ch = getchar()) != EOF)
- putc(ch, fp);
-
- /* clean up */
- if (fclose(fp))
- fatal(pgm, notesfile, 2);
- exit(0);
- }
-
-
- NOTES2.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\04STDLIB\NOTES2.C
-
- /*
- * notes2 -- add a date/time stamped entry to a
- * "notes" data file. Allow user to optionally
- * edit the data file upon completion of the entry.
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <signal.h>
- #include <process.h>
- #include <local\std.h>
-
- /* length of date/time string */
- #define DT_STR 26
-
- main(argc, argv)
- int argc;
- char **argv;
- {
- int n; /* number of lines added */
- int exitcode = 0;
- FILE *fp;
- static char notesfile[MAXPATH + 1] = { "notes.txt" };
- static char editname[MAXPATH + 1] = { "edlin" };
- char ch;
- char dt_stamp[DT_STR];
- char *s;
- long ltime;
- static char pgm[MAXNAME + 1] = { "notes3" };
-
- extern void fatal(char *, char *, int);
- extern void getpname(char *, char *);
- static int addtxt(FILE *, FILE *);
-
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- /* locate the "notes" database file and open it */
- if (argc > 1)
- strcpy(notesfile, *++argv);
- else if (s = getenv("NOTESFILE"))
- strcpy(notesfile, s);
- if ((fp = fopen(notesfile, "a")) == NULL)
- fatal(pgm, notesfile, 1);
-
- /* disable Ctrl-Break interrupt */
- if (signal(SIGINT, SIG_IGN) == (int(*)())-1)
- perror("Cannot set signal");
-
- /* append a header and date/time tag */
- ltime = time(NULL);
- strcpy(dt_stamp, ctime(<ime));
- fprintf(stderr, "Appending to %s: %s", notesfile, dt_stamp);
- fprintf(fp, "\n%s", dt_stamp);
-
- /* add text to notes file */
- if ((n = addtxt(stdin, fp)) == 0) {
- fputs("No new text", stderr);
- if (fclose(fp))
- fatal(pgm, notesfile, 2);
- exit(0);
- }
- else
- fprintf(stderr, "%d line(s) added to %s\n", n, notesfile);
- if (fclose(fp))
- fatal(pgm, notesfile, 2);
-
- /* optionally edit text in the notes file */
- fprintf(stderr, "E + ENTER to edit; ENTER alone to quit: ");
- while ((ch = tolower(getchar())) != '\n')
- if (ch = 'e') {
- if (s = getenv("EDITOR"))
- strcpy(editname, s);
- if ((exitcode = spawnlp(P_WAIT, editname, editname,
- notesfile, NULL)) == -1)
- fatal(pgm, editname, 3);
- }
- exit(exitcode);
- }
-
- /*
- * addtxt -- append new text to notes file
- */
- static int addtxt(fin, fout)
- FILE *fin, *fout;
- {
- int ch;
- int col = 0; /* column */
- int n = 0; /* number of lines added */
-
- while ((ch = fgetc(fin)) != EOF) {
- if (ch == '.' && col == 0) {
- ch = fgetc(fin); /* trash the newline */
- break;
- }
- fputc(ch, fout);
- if (ch == '\n') {
- col = 0;
- ++n;
- }
- else
- ++col;
- }
- return (n);
- }
-
-
- PALETTE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\PALETTE.C
-
- /*
- * palette -- set graphics color values or border color
- */
-
- #include <dos.h>
- #include <local\bioslib.h>
-
- int
- palette(id, color)
- unsigned int id, color;
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = PALETTE;
- inregs.h.bh = id;
- inregs.h.bl = color;
- int86(VIDEO_IO, &inregs, &outregs);
-
- return(outregs.x.cflag);
- }
-
-
- PARSE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\13ANSI\PARSE.C
-
- /*
- * parse -- process a list of attribute specifications
- */
-
- #include <stdio.h>
- #include <local\ansi.h>
- #include <local\std.h>
- #include <local\ibmcolor.h>
-
- /* buffer length for string comparisons */
- #define NCHARS 3
- #define C_MASK 0x7
-
- void
- parse(nargs, argvec)
- int nargs; /* number of argument vectors */
- char *argvec[]; /* pointer to the argument vector array */
- {
- int i, intensity;
- int attribute;
- POSITION pos;
- char str[NCHARS + 1];
- extern int colornum(char *);
- extern void setattr(POSITION, int);
-
- /* clear all attributes */
- ANSI_SGR(ANSI_NORMAL);
-
- /* look for a single attribute specification */
- if (nargs == 2) {
- attribute = colornum(argvec[1]);
- switch (attribute) {
- case IBM_NORMAL:
- palette(0, IBM_BLACK);
- return;
- case IBM_REVERSE:
- ANSI_SGR(ANSI_REVERSE);
- palette(0, IBM_WHITE);
- return;
- case IBM_INVISIBLE:
- ANSI_SGR(ANSI_INVISIBLE);
- return;
- case IBM_BLINK:
- ANSI_SGR(ANSI_BLINK);
- return;
- }
- }
-
- /* must be separate attribute specifications */
- pos = FGND;
- intensity = 0;
- for (i = 1; i < nargs; ++i) {
- attribute = colornum(argvec[i]);
- if (attribute == -1) {
- ANSI_ED;
- fprintf(stderr, "\nIllegal parameter\n");
- exit (2);
- }
- if (attribute == IBM_BRIGHT) {
- intensity = IBM_BRIGHT;
- continue;
- }
- setattr(pos, attribute | intensity);
- if (pos == FGND)
- pos = BKGND;
- else if (pos == BKGND)
- pos = BDR;
- intensity = 0;
- }
- return;
- }
-
-
- PR.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\09PRINT\PR.C
-
- /*
- * pr -- file printer
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <dos.h>
- #include <local\std.h>
- #include "print.h"
-
- char Pagelist[MAXLINE];
-
- main(argc, argv)
- int argc;
- char **argv;
- {
- int ch;
- BOOLEAN errflag;
- extern PRINT pcnf;
- static char pgm[MAXNAME + 1] = { "pr" };
-
- extern char *getpname(char *, char *);
- extern int getopt(int, char **, char *);
- extern char *optarg;
- extern int optind, opterr;
- extern int pr_gcnf(char *);
- extern pr_file(char *, int, char **);
- extern void pr_help(char *);
- extern void fixtabs(int);
- extern int setprnt();
-
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- /* do configuration */
- if (pr_gcnf(pgm) != 0) {
- fprintf(stderr, "%s: Configuration error", pgm);
- exit(2);
- }
- if (setprnt() == -1) {
- fprintf(stderr, "%s: Bad printer configuration\n", pgm);
- exit(1);
- }
- fixtabs(pcnf.p_tabint);
-
- /* process command-line arguments */
- while ((ch = getopt(argc, argv, "efgh:l:no:ps:w:")) != EOF) {
- switch (ch) {
- case 'e':
- /* force "Epson-compatible " printer mode */
- pcnf.p_mode = 1;
- break;
- case 'f':
- /* use formfeed to eject a page */
- pcnf.p_ff = 1;
- break;
- case 'g':
- /* force "generic" printer mode */
- pcnf.p_mode = 0;
- break;
- case 'h':
- /* use specified header */
- strcpy(pcnf.p_hdr, optarg);
- break;
- case 'l':
- /* set lines per page */
- pcnf.p_len = atoi(optarg);
- break;
- case 'n':
- /* enable line numbering */
- pcnf.p_lnum = 1;
- break;
- case 'o':
- /* set left margin */
- pcnf.p_lmarg = atoi(optarg);
- break;
- case 'p':
- /* preview output on screen */
- strcpy(pcnf.p_dest, "");
- break;
- case 's':
- /* output selected pages */
- strcpy(Pagelist, optarg);
- break;
- case 'w':
- /* set page width in columns */
- pcnf.p_wid = atoi(optarg);
- break;
- case '?':
- /* unknown option */
- errflag = TRUE;
- break;
- }
- }
- if (errflag == TRUE) {
- pr_help(pgm);
- exit(3);
- }
-
- /* print the files */
- pr_file(pgm, argc - optind, argv += optind);
-
- exit(0);
- }
-
-
- PRINTER.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\PRINTER.C
-
- /*
- * printer -- interface functions for printer
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <local\std.h>
- #include <local\printer.h>
-
- PRINTER prt; /* printer data */
-
- /*
- * setprnt -- install printer codes from configuration
- * file for printer (defaults to Epson MX/FX series)
- */
-
- #define NSELEM 13
-
- int
- setprnt()
- {
- int n;
- char *s, line[MAXLINE];
- FILE *fp, *fconfig(char *, char *);
-
- /* use local or global config file, if any */
- if ((fp = fconfig("CONFIG", "printer.cnf")) != NULL) {
- n = 0;
- while (fgets(line, MAXLINE, fp) != NULL) {
- if ((s = strtok(line, " \t\n")) == NULL)
- return (-1);
- switch (n) {
- case 0:
- strcpy(prt.p_init, s);
- break;
- case 1:
- strcpy(prt.p_bold, s);
- break;
- case 2:
- strcpy(prt.p_ds, s);
- break;
- case 3:
- strcpy(prt.p_ital, s);
- break;
- case 4:
- strcpy(prt.p_cmp, s);
- break;
- case 5:
- strcpy(prt.p_exp, s);
- break;
- case 6:
- strcpy(prt.p_ul, s);
- break;
- case 7:
- strcpy(prt.p_xbold, s);
- break;
- case 8:
- strcpy(prt.p_xds, s);
- break;
- case 9:
- strcpy(prt.p_xital, s);
- break;
- case 10:
- strcpy(prt.p_xcmp, s);
- break;
- case 11:
- strcpy(prt.p_xexp, s);
- break;
- case 12:
- strcpy(prt.p_xul, s);
- break;
- default:
- /* too many lines */
- return (-1);
- }
- ++n;
- }
- if (n != NSELEM)
- /* probably not enough lines */
- return (-1);
- }
-
- /* or use Epson defaults */
- strcpy(prt.p_init, "\033@"); /* hardware reset */
- strcpy(prt.p_bold, "\033E"); /* emphasized mode */
- strcpy(prt.p_ds, "\033G"); /* double-strike mode */
- strcpy(prt.p_ital, "\0334"); /* italic mode */
- strcpy(prt.p_cmp, "\017"); /* condensed mode */
- strcpy(prt.p_exp, "\016"); /* expanded mode */
- strcpy(prt.p_ul, "\033-1"); /* underline mode */
- strcpy(prt.p_xbold, "\033F"); /* cancel emphasized mode */
- strcpy(prt.p_xds, "\033H"); /* cancel double-strike mode */
- strcpy(prt.p_xital, "\0335"); /* cancel italic mode */
- strcpy(prt.p_xcmp, "\022"); /* cancel condensed mode */
- strcpy(prt.p_xexp, "\024"); /* cancel expanded mode */
- strcpy(prt.p_xul, "\033-0"); /* cancel underline mode */
-
- return (0);
- }
-
- /*
- * clrprnt -- clear printer options to default values
- * (clears individual options to avoid the "paper creep"
- * that occurs with repeated printer resets and to avoid
- * changing the printer's notion of top-of-form position)
- */
-
- int
- clrprnt(fout)
- FILE *fout;
- {
- fputs(prt.p_xbold, fout); /* cancel emphasized mode */
- fputs(prt.p_xds, fout); /* cancel double-strike mode *
- fputs(prt.p_xital, fout); /* cancel italic mode */
- fputs(prt.p_xcmp, fout); /* cancel condensed mode */
- fputs(prt.p_xexp, fout); /* cancel expanded mode */
- fputs(prt.p_xul, fout); /* cancel underline mode */
- } /* end clrprnt() */
-
- /*
- * setfont -- set the printing font to the type specified
- * by the argument (may be a compound font specification)
- */
-
- int
- setfont(ftype, fout)
- int ftype; /* font type specifier */
- FILE *fout; /* output stream */
- {
- clrprnt(fout);
- if ((ftype & CONDENSED) == CONDENSED)
- if ((ftype & DOUBLE) == DOUBLE ||
- (ftype & EMPHASIZED) == EMPHASIZED)
- return FAILURE;
- else if (*prt.p_cmp)
- fputs(prt.p_cmp, fout);
- if (*prt.p_ds && (ftype & DOUBLE) == DOUBLE)
- fputs(prt.p_ds, fout);
- if (*prt.p_bold && (ftype & EMPHASIZED) == EMPHASIZED)
- fputs(prt.p_bold, fout);
- if (*prt.p_exp && (ftype & EXPANDED) == EXPANDED)
- fputs(prt.p_exp, fout);
- if (*prt.p_ital && (ftype & ITALICS) == ITALICS)
- fputs(prt.p_ital, fout);
- if (*prt.p_ul && (ftype & UNDERLINE) == UNDERLINE)
- fputs(prt.p_ul, fout);
-
- return SUCCESS;
- } /* end setfont() */
-
-
- PRTSTR.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\07CONFIG\PRTSTR.C
-
- /*
- * prtstr -- send text string(s) to standard printer
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <local\std.h>
-
- main(argc, argv)
- int argc;
- char **argv;
- {
- int ch;
- BOOLEAN errflag, lineflag;
- static char pgm[MAXNAME + 1] = { "prtstr" };
- FILE *fout;
-
- extern char *getpname(char *, char *);
- extern int getopt(int, char **, char *);
- extern int optind, opterr;
- extern char *optarg;
-
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- /* process options, if any */
- errflag = FALSE;
- lineflag = TRUE;
- fout = stdprn;
- while ((ch = getopt(argc, argv, "np")) != EOF)
- switch (ch) {
- case 'n':
- /* don't emit the trailing newline */
- lineflag = FALSE;
- break;
- case 'p':
- /* preview on stdout */
- fout = stdout;
- break;
- case '?':
- /* bad option */
- errflag = TRUE;
- break;
- }
- if (errflag == TRUE) {
- fprintf(stderr, "Usage: %s [-np] [string...]\n");
- exit(1);
- }
-
- /* print the string(s) */
- argc -= optind;
- argv += optind;
- while (argc-- > 1 ) {
- fputs(*argv++, fout);
- fputc(' ', fout);
- }
- fputs(*argv++, fout);
- if (lineflag == TRUE)
- fputc(' ', fout);
- if (lineflag == TRUE)
- fputc('\n', fout);
-
- exit(0);
- }
-
-
- PR_CPY.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\09PRINT\PR_CPY.C
-
- /*
- * pr_cpy -- copy input stream to output stream
- */
-
- #include <stdio.h>
- #include <string.h>
- #include <local\std.h>
- #include <local\printer.h>
- #include <sys\types.h>
- #include <sys\stat.h>
- #include <time.h>
- #include "print.h"
-
- extern PRINT pcnf;
- extern char Pagelist[MAXLINE];
- extern long Highest;
-
- int
- pr_cpy(fin, fout, fname)
- FILE *fin;
- FILE *fout;
- char *fname;
- {
- int errcount = 0;
- unsigned int p_line; /* page-relative line number */
- long f_line; /* file-relative line number */
- long f_page; /* file-relative page number */
- int lnlen; /* line length */
- char line[MAXLINE]; /* input line buffer */
- struct stat tbuf; /* file information */
- long ltime; /* date and time */
- FILE *fnull, *fx; /* additional output file pointers */
-
- extern void mkslist(char *); /* make a selection list */
- extern int selected(long); /* is item in the list? */
- extern int spaces(int, FILE *); /* emit string of spaces */
- extern int setfont(int, FILE *);/* set printer font type */
- extern int clrprnt(FILE *); /* clear special fonts */
- extern int lines(int, FILE *); /* emit string of blank lines *
- static int fit(int, int); /* will line fit on page? */
- extern int pr_line(char *, FILE *, unsigned int);
-
- /* install page selection list, if any */
- if (Pagelist[0] != '\0') {
- /* open the NUL device for dumping output */
- if ((fnull = fopen("NUL", "w")) == NULL) {
- perror("Error opening NUL device");
- exit(1);
- }
- mkslist(Pagelist);
- }
- else
- Highest = BIGGEST;
-
- /* get date and time stamp */
- if (*fname == '\0')
- /* using stdin -- use today's date and time */
- ltime = time(NULL);
- else {
- if (stat(fname, &tbuf) == -1)
- return (-1);
- /* use file's modification time */
- ltime = tbuf.st_mtime;
- }
- p_line = 0;
- f_line = 1;
- f_page = 1;
- while ((lnlen = pr_getln(line, MAXLINE, fin)) > 0 ) {
- /* if formfeed or no room for line, eject page */
- if (line[0] == '\f' || !fit(lnlen, p_line)) {
- /* to top of next page */
- if (pcnf.p_ff == 0)
- lines(pcnf.p_len - p_line, fx);
- else
- fputc('\f', fx);
- p_line = 0;
- }
-
- /* if at top of page, print the header */
- if (p_line == 0) {
- if (f_page > Highest)
- break;
- fx = selected(f_page) ? fout : fnull;
- p_line += lines(pcnf.p_top1, fx);
- if (pcnf.p_mode != 0)
- setfont(EMPHASIZED, fx);
- spaces(pcnf.p_lmarg, fx);
- if (*pcnf.p_hdr != '\0')
- fprintf(fx, "%s ", pcnf.p_hdr);
- else if (*fname != '\0')
- fprintf(fx, "%s ", strupr(fname));
- fprintf(fx, "Page %u ", f_page++);
- fputs(ctime(<ime), fx);
- ++p_line;
- if (pcnf.p_mode != 0)
- setfont(pcnf.p_font, fx);
- p_line += lines(pcnf.p_top2, fx);
- }
-
- /* OK to output the line */
- if (line[0] != '\f')
- p_line += pr_line(line, fx, f_line++);
- }
- if (ferror(fin) != 0)
- ++errcount;
- if (p_line > 0 && p_line < pcnf.p_len)
- if (pcnf.p_ff == 0)
- lines(pcnf.p_len - p_line, fx);
- else
- fputc('\f', fx);
-
- if (pcnf.p_mode != 0)
- clrprnt(fx);
- return (errcount);
- }
-
- /*
- * fit -- return non-zero value if enough physical
- * lines are available on the current page to take
- * the current logical line of text
- */
-
- NFLDWIDTH 8 /* width of number field */
-
- static int
- fit(len, ln)
- int len, ln;
- {
- int need, left; /* physical lines */
- int cols; /* columns of actual output */
- int lw; /* displayable line width */
-
- /* total need (columns -> physical lines) */
- cols = len + (pcnf.p_lnum > 0 ? NFLDWIDTH : 0);
- lw = pcnf.p_wid - pcnf.p_lmarg - pcnf.p_rmarg;
- need = 1 + cols / lw;
-
- /* lines remaining on page */
- left = pcnf.p_len - ln - pcnf.p_btm;
-
- return (need <= left ? 1 : 0);
- }
-
-
- PR_FILE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\09PRINT\PR_FILE.C
-
- /*
- * pr_file -- process each filename or standard input
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <local\std.h>
- #include "print.h"
-
- int
- pr_file(pname, ac, av)
- char *pname;
- int ac;
- char **av;
- {
- int ch, errcount = 0;
- FILE *fin, *fout;
- extern PRINT pcnf;
-
- extern void fatal(char *, char *, int);
- extern int pr_cpy(FILE *, FILE *, char *);
-
- /* open output stream only if not already open */
- if (*pcnf.p_dest == '\0' || strcmp(pcnf.p_dest, "CON") == 0)
- fout = stdout;
- else if (strcmp(pcnf.p_dest, "PRN") == 0)
- fout = stdprn;
- else if (strcmp(pcnf.p_dest, "AUX") == 0)
- fout = stdaux;
- else
- if ((fout = fopen(pcnf.p_dest, "w")) == NULL)
- fatal(pname, "Error open destination stream", 1);
-
- /* prepare input stream */
- if (ac == 0)
- pr_cpy(stdin, fout, "");
- else {
- for (; ac > 0; --ac, ++av) {
- if ((fin = fopen(*av, "r")) == NULL) {
- fprintf(stderr, "%s: Error opening %s",
- pname, *av);
- continue;
- }
- if (pr_cpy(fin, fout, *av) == -1) {
- fprintf(stderr, "%s: Cannot stat %s",
- pname, *av);
- continue;
- }
- if (fclose(fin) == EOF)
- fatal(pname, "Error closing input file", 2);
- }
- }
-
- return (errcount);
- }
-
-
- PR_GCNF.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\09PRINT\PR_GCNF.C
-
- /*
- * pr_gcnf -- get configuration for pr program
- */
-
- #include <stdio.h>
- #include <string.h>
- #include <local\std.h>
- #include <local\printer.h>
- #include "print.h"
-
- /* expected number of configuration items */
- #define N_NBR 12
-
- PRINT pcnf;
-
- int
- pr_gcnf(pname)
- char *pname;
- {
- char line[MAXLINE];
- char *s;
- int cnf[N_NBR];
- int n, errcount, good;
- FILE *fp, *fconfig(char *, char *);
-
- /* get configuration file values, if any */
- n = good = errcount = 0;
- if ((fp = fconfig("CONFIG", "pr.cnf")) != NULL) {
- while (n < N_NBR && (s = fgets(line, MAXLINE, fp)) != NULL) {
- cnf[n] = atoi(s);
- ++n;
- }
- if ((s = fgets(line, MAXLINE, fp)) == NULL)
- ++errcount;
- else
- strcpy(pcnf.p_dest, strtok(line, " \t\n"));
- if (n != N_NBR)
- ++errcount;
- if (errcount == 0)
- good = 1;
- if (fclose(fp) == -1)
- fatal(pname, "cannot close config file");
- }
-
- /* use config data is good; use defaults otherwise */
- pcnf.p_top1 = good ? cnf[0]: TOP1;
- pcnf.p_top2 = good ? cnf[1] : TOP2;
- pcnf.p_btm = good ? cnf[2] : BOTTOM;
- pcnf.p_wid = good ? cnf[3] : MAXPCOL;
- pcnf.p_lmarg = good ? cnf[4] : MARGIN;
- pcnf.p_rmarg = good ? cnf[5] : MARGIN;
- pcnf.p_len = good ? cnf[6] : PAGELEN;
- pcnf.p_lpi = good ? cnf[7] : LPI;
- pcnf.p_mode = good ? cnf[8] : 0;
- pcnf.p_lnum = good ? cnf[9] : 0;
- pcnf.p_ff = good ? cnf[10] : 0;
- pcnf.p_tabint = good ? cnf[11] : TABSPEC;
- if (!good)
- strcpy(pcnf.p_dest, "PRN");
- if (pcnf.p_mode == 1)
- pcnf.p_font = CONDENSED;
- strcpy(pcnf.p_hdr, "");
-
- return (errcount);
- }
-
-
- PR_GETLN.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\09PRINT\PR_GETLN.C
-
- /*
- * pr_getln -- get a line of text while expanding tabs;
- * put text into an array and return the length of the line
- * including termination to the calling function.
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <local\std.h>
-
- int
- pr_getln(s, lim, fin)
- char *s;
- int lim;
- FILE *fin;
- {
- int ch;
- register char *cp;
-
- extern int tabstop(); /* query tabstop array */
-
- cp = s;
- while (--lim > 0 && (ch = fgetc(fin)) != EOF && ch != '\n' && ch != '
- if (ch == '\t')
- /* loop and store spaces until next tabstop */
- do
- *cp++ = ' ';
- while (--lim > 0 && tabstop(cp - s) == 0);
- else
- *cp++ = ch;
- }
- if (ch == EOF && cp - s == 0)
- ;
- else if (ch == EOF || ch == '\n')
- *cp++ = '\n'; /* assure correct line termination */
- else if (ch == '\f' && cp - s == 0) {
- *cp++ = '\f';
- fgetc(fin); /* toss the trailing newline */
- }
- *cp = '\0';
-
- return (cp - s);
- }
-
-
- PR_HELP.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\09PRINT\PR_HELP.C
-
- /*
- * pr_help -- display an abbreviated manual page
- */
-
- #include <stdio.h>
- #include <local\std.h>
-
- void
- pr_help(pname)
- char *pname;
- {
- static char *m_str[] = {
- "The following options may be used singly or in combination:"
- "-e\t set Epson-compatible mode",
- "-f\t use formfeed to eject a page (default is newlines)",
- "-g\t use generic printer mode",
- "-h hdr\t use specified header instead of file name",
- "-l len\t set page length in lines (default = 66)",
- "-n\t enable line numbering (default = off)",
- "-o cols\t offset from left edge in columns (default = 5)",
- "-p\t preview output on screen (may be redirected)",
- "-s list\t print only selected pages",
- "-w cols\t line width in columns (default = 80)"
- };
- int i, n = sizeof (m_str)/ sizeof (char *);
-
- fprintf(stderr, "Usage: %s [options] file...\n\n", pname);
- for (i = 0; i < n; ++i)
- fprintf(stderr, "%s\n", m_str[i]);
-
- return;
- }
-
-
- PR_LINE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\09PRINT\PR_LINE.C
-
- /*
- * pr_line -- ouput a buffered logical line and
- * return a count of physical lines produced
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <local\std.h>
- #include "print.h"
-
- int
- pr_line(s, fout, rline)
- char *s; /* buffered line of text */
- FILE *fout; /* output stream */
- unsigned int rline; /* file-relative line number */
- {
- int c_cnt; /* character position in output line */
- int nlines; /* number of lines output */
- extern PRINT pcnf;
-
- extern int spaces(int, FILE *); /* emit string of spaces */
-
- nlines = 1;
- c_cnt = 0;
-
- /* output the left indentation, if any */
- c_cnt += spaces(pcnf.p_lmarg, fout);
-
- /* output the line number if numbering enabled */
- if (pcnf.p_lnum != 0)
- c_cnt += fprintf(fout, "%6u ", rline);
-
- /* output the text of the line */
- while (*s != '\0') {
- if (c_cnt > (pcnf.p_wid - pcnf.p_rmarg)) {
- fputc('\n', fout);
- ++nlines;
- c_cnt = 0;
- c_cnt = spaces(pcnf.p_lmarg, fout);
- }
- fputc(*s, fout);
- ++s;
- ++c_cnt;
- }
-
- return (nlines);
- }
-
-
- PUTCUR.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\PUTCUR.C
-
- /*
- * putcur -- put cursor at specified position (row, col)
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
-
- putcur(r, c, pg)
- unsigned int
- r, /* row */
- c, /* column */
- pg; /* screen page for writes */
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = CUR_POS;
- inregs.h.bh = pg & 0x07;
- inregs.h.dh = r & 0xFF;
- inregs.h.dl = c & 0xFF;
-
- int86(VIDEO_IO, &inregs, &outregs);
-
- return (outregs.x.cflag);
- } /* end putcur() */
-
-
- PUTFLD.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\PUTFLD.C
-
- /*
- * putfld -- display a string in the prevailing
- * video attribute while compressing runs of a
- * single character, and pad the field to full width
- * with spaces if necessary
- */
-
- int
- putfld(s, w, pg)
- register char *s; /* string to write */
- int w; /* field width */
- int pg; /* screen page for writes */
- {
- int r, c, cols;
- register int n;
-
- extern int putcur(int, int, int);
- extern int readcur(int *, int *, int);
- extern int writec(unsigned char, int, int);
-
- /* get starting (current) position */
- readcur(&r, &c, pg);
-
- /* write the string */
- for (n = 0; *s != '\0' && n < w; s += cols, n += cols) {
- putcur(r, c + n, pg);
- /* compress runs to a single call on writec() */
- cols = 1;
- while (*(s + cols) == *s && n + cols < w)
- ++cols;
- writec(*s, cols, pg);
- }
-
- /* pad the field, if necessary */
- if (n < w) {
- putcur(r, c + n, pg);
- writec(' ', w - n, pg);
- }
-
- return (w - n);
- }
-
-
- PUTSTR.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\PUTSTR.C
-
- /*
- * putstr -- display a character string in the
- * prevailing video attribute and return number
- * characters displayed
- */
-
- int
- putstr(s, pg)
- register char *s;
- unsigned int pg;
- {
- unsigned int r, c, c0;
-
- readcur(&r, &c, pg);
- for (c0 = c; *s != '\0'; ++s, ++c) {
- putcur(r, c, pg);
- writec(*s, 1, pg);
- }
- putcur(r, c, pg);
- return (c - c0);
- }
-
-
- PUT_CH.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\PUT_CH.C
-
- /*
- * put_ch -- display a character in the prevailing video
- * attribute and advance the cursor position
- */
-
- #include <local\video.h>
-
- int
- put_ch(ch, pg)
- register char ch;
- int pg;
- {
- int r, c, c0;
-
- readcur(&r, &c, pg);
- writec(ch, 1, pg);
- putcur(r, ++c, pg);
- return (1);
- }
-
-
- PWD.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\08FILE\PWD.C
-
- /*
- * pwd -- print (display actually) the current directory pathname
- */
-
- #include <stdio.h>
- #include <direct.h>
- #include <local\std.h>
-
- main()
- {
- char *path;
-
- if ((path = getcwd(NULL, MAXPATH)) == NULL) {
- perror("Error getting current directory");
- exit(1);
- }
- printf("%s\n", path);
- exit(0);
- }
-
- _setargv()
- {
- }
-
- _setenvp()
- {
- }
-
- _nullcheck()
- {
- }
-
-
- READCA.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\READCA.C
-
- /*
- * readca -- read character and attribute at current position
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
-
- int readca(ch, attr, pg)
- unsigned char *ch;
- unsigned char *attr;
- unsigned int pg; /* screen page for reads */
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = READ_CHAR_ATTR;
- inregs.h.bh = pg; /* display page */
-
- int86(VIDEO_IO, &inregs, &outregs);
-
- *ch = outregs.h.al; /* character */
- *attr = outregs.h.ah; /* attribute */
-
- /* return the value in AX register */
- return (outregs.x.cflag);
- } /* end readca() */
-
-
- READCUR.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\READCUR.C
-
- /*
- * readcur -- pass back the cursor position (row, col)
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
-
- unsigned int readcur(row, col, pg)
- unsigned int *row; /* current row */
- unsigned int *col; /* current column */
- unsigned int pg; /* screen page */
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = GET_CUR;
- inregs.h.bh = pg;
-
- int86(VIDEO_IO, &inregs, &outregs);
-
- *col = outregs.h.dl; /* col */
- *row = outregs.h.dh; /* row */
-
- return (outregs.x.cflag);
- } /* end readcur() */
-
-
- READDOT.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\READDOT.C
-
- /*
- * readdot -- read the value of a pixel
- * (in graphics mode only)
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
-
- int
- readdot(row, col, dcolor)
- int row, col;
- int *dcolor; /* pointer to dot color */
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = READ_DOT;
- inregs.x.cx = col;
- inregs.x.dx = row;
- int86(VIDEO_IO, &inregs, &outregs);
- *dcolor = outregs.h.al;
-
- return (outregs.x.cflag);
- }
-
-
- REPLAY.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\03DOS\REPLAY.C
-
- /*
- * replay -- echo the command-line arguments
- * to standard output
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <local\std.h>
-
- main(argc, argv)
- int argc;
- char **argv;
- {
- int i;
- char **p;
- static char pgm[MAXNAME + 1] = { "replay" };
-
- void getpname(char *, char *);
-
- /* get program name from DOS (version 3.00 and later) */
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- /* check for arguments */
- if (argc == 1)
- exit(1); /* none given */
-
- /* echo the argument list, one per line */
- p = argv;
- printf("%s arguments:\n\n", pgm);
- for (--argc, ++argv; argc > 0; --argc, ++argv)
- printf("argv[%d] -> %s\n", argv - p, *argv);
- exit(0);
- } /* end main() */
-
-
- RM.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\08FILE\RM.C
-
- /*
- * rm -- remove file(s)
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys\types.h>
- #include <sys\stat.h>
- #include <ctype.h>
- #include <io.h>
- #include <local\std.h>
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- int ch;
- BOOLEAN errflag,
- iflag;
-
- static char pgm[MAXNAME + 1] = { "rm" };
- extern void getpname(char *, char *);
- static void do_rm(char *, char *, BOOLEAN);
- extern int getopt(int, char **, char *);
- extern int optind, opterr;
- extern char *optarg;
-
- /* get program name from DOS (version 3.00 and later) */
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- /* process optional arguments first */
- errflag = iflag = FALSE;
- while ((ch = getopt(argc, argv, "i")) != EOF)
- switch (ch) {
- case 'i':
- /* interactive -- requires confirmation */
- iflag = TRUE;
- break;
- case '?':
- /* say what? */
- errflag = TRUE;
- break;
- }
- argc -= optind;
- argv += optind;
-
- if (argc <= 0 || errflag == TRUE) {
- fprintf(stderr, "%s [-i] file(s)\n", pgm);
- exit(1);
- }
-
- /* process remaining arguments */
- for (; argc-- > 0; ++argv)
- do_rm(pgm, *argv, iflag);
-
- exit(0);
- } /* end main() */
-
- /*
- * do_rm -- remove a file
- */
-
- static void
- do_rm(pname, fname, iflag)
- char *pname, *fname;
- BOOLEAN iflag;
- {
- int result = 0;
- struct stat statbuf;
- static BOOLEAN affirm();
-
- if (iflag == TRUE) {
- fprintf(stderr, "%s (y/n): ", fname);
- if (affirm() == FALSE)
- return;
- }
- if ((result = unlink(fname)) == -1) {
- fprintf(stderr, "%s: ", pname);
- perror(fname);
- }
- return;
- }
-
- /*
- * affirm -- return TRUE if the first character of the
- * user's response is 'y' or FALSE otherwise
- */
-
- #define MAXSTR 64
-
- static BOOLEAN
- affirm()
- {
- char line[MAXSTR + 1];
- char *response;
-
- response = fgets(line, MAXSTR, stdin);
- return (tolower(*response) == 'y' ? TRUE : FALSE);
- }
-
-
- RUN_ONCE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\04STDLIB\RUN_ONCE.C
-
- /*
- * run_once -- run a program one time and then
- * "hang" the system to prevent unwanted use
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <process.h>
- #include <local\std.h>
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- extern void fatal(char *, char *, int);
-
- /* skip over the program name */
- ++argv;
-
- /* run the specified command line [pgmname arg(s)] */
- if (spawnvp(P_WAIT, *argv, argv) == -1)
- fatal("run_once", "Error running specified program", 1);
- fprintf(stderr, "Please turn off the power to the computer.\n");
-
- /* do nothing */
- FOREVER
- ;
- }
-
-
- SB_BOX.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\12SBUF\SB_BOX.C
-
- /*
- * sb_box -- draw a box around the perimeter of a window
- * using the appropriate IBM graphics characters
- */
-
- #include <local\sbuf.h>
- #include <local\video.h>
- #include <local\box.h>
-
- int
- sb_box(win, type, attr)
- struct REGION *win;
- short type;
- unsigned char attr;
- {
- register short r; /* row index */
- short x; /* interior horizontal line length */
- short maxr, maxc; /* maximum row and col values */
- BOXTYPE *boxp; /* pointer to box drawing character str
- static BOXTYPE box[] = {
- '+', '+', '+', '+', '-', '-', '|', '|',
- ULC11, URC11, LLC11, LRC11, HBAR1, HBAR1, VBAR1, VBAR1,
- ULC22, URC22, LLC22, LRC22, HBAR2, HBAR2, VBAR2, VBAR2,
- ULC12, URC12, LLC12, LRC12, HBAR1, HBAR1, VBAR2, VBAR2,
- ULC21, URC21, LLC21, LRC21, HBAR2, HBAR2, VBAR1, VBAR1,
- BLOCK, BLOCK, BLOCK, BLOCK, HBART, HBARB, BLOCK, BLOCK
- };
-
- boxp = &box[type];
- maxc = win->c1 - win->c0;
- maxr = win->r1 - win->r0;
- x = maxc - 1;
-
- /* draw top row */
- sb_move(win, 0, 0);
- sb_wca(win, boxp->ul, attr, 1);
- sb_move(win, 0, 1);
- sb_wca(win, boxp->tbar, attr, x);
- sb_move(win, 0, maxc);
- sb_wca(win, boxp->ur, attr, 1);
-
- /* draw left and right sides */
- for (r = 1; r < maxr; ++r) {
- sb_move(win, r, 0);
- sb_wca(win, boxp->lbar, attr, 1);
- sb_move(win, r, maxc);
- sb_wca(win, boxp->rbar, attr, 1);
- }
-
- /* draw bottom row */
- sb_move(win, maxr, 0);
- sb_wca(win, boxp->ll, attr, 1);
- sb_move(win, maxr, 1);
- sb_wca(win, boxp->bbar, attr, x);
- sb_move(win, maxr, maxc);
- sb_wca(win, boxp->lr, attr, 1);
-
- return SB_OK;
- }
-
-
- SB_FILL.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\12SBUF\SB_FILL.C
-
- /*
- * sb_fill -- fill region routines
- */
-
- #include <local\sbuf.h>
-
- extern struct BUFFER Sbuf;
- extern union CELL Scrnbuf[SB_ROWS][SB_COLS];
-
- /*
- * sb_fill -- set all cells in a specified region
- * to the same character/attribute value
- */
-
- int
- sb_fill(win, ch, attr)
- struct REGION *win;
- unsigned char ch; /* fill character */
- unsigned char attr; /* fill attribute */
- {
- register int i, j;
- unsigned short ca;
-
- ca = (attr << 8) | ch;
- for (i = win->sr0; i <= win->sr1; ++i) {
- for (j = win->sc0; j <= win->sc1; ++j)
- Scrnbuf[i][j].cap = ca;
- if (win->sc0 < Sbuf.lcol[i])
- Sbuf.lcol[i] = win->sc0;
- if (win->sc1 > Sbuf.rcol[i])
- Sbuf.rcol[i] = win->sc1;
- }
- Sbuf.flags |= SB_DELTA;
-
- return SB_OK;
- }
-
-
- /*
- * sb_fillc -- set all cells in a specified region
- * to the same character value; leave attributes undisturbed
- */
-
- int
- sb_fillc(win, ch)
- struct REGION *win;
- unsigned char ch; /* fill character */
- {
- register int i, j;
-
- for (i = win->sr0; i <= win->sr1; ++i) {
- for (j = win->sc0; j <= win->sc1; ++j)
- Scrnbuf[i][j].b.ch = ch;
- if (win->sc0 < Sbuf.lcol[i])
- Sbuf.lcol[i] = win->sc0;
- if (win->sc1 > Sbuf.rcol[i])
- Sbuf.rcol[i] = win->sc1;
- }
- Sbuf.flags |= SB_DELTA;
-
- return SB_OK;
- }
-
-
- /*
- * sb_filla -- set all cells in a specified region
- * to the same attribute value; leave characters undisturbed
- */
-
- int
- sb_filla(win, attr)
- struct REGION *win;
- unsigned char attr; /* fill attribute */
- {
- register int i, j;
-
- for (i = win->sr0; i <= win->sr1; ++i) {
- for (j = win->sc0; j <= win->sc1; ++j)
- Scrnbuf[i][j].b.attr = attr;
- if (win->sc0 < Sbuf.lcol[i])
- Sbuf.lcol[i] = win->sc0;
- if (win->sc1 > Sbuf.rcol[i])
- Sbuf.rcol[i] = win->sc1;
- }
- Sbuf.flags |= SB_DELTA;
-
- return SB_OK;
- }
-
-
- SB_INIT.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\12SBUF\SB_INIT.C
-
- /*
- * sb_init -- initialize the buffered screen interface
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <local\sbuf.h>
-
- /* global data declarations */
- struct BUFFER Sbuf; /* control information */
- union CELL Scrnbuf[SB_ROWS][SB_COLS]; /* screen buffer array */
-
- int
- sb_init()
- {
- int i;
- char *um; /* update mode */
-
- /* set initial parameter values */
- Sbuf.bp = &Scrnbuf[0][0];
- Sbuf.row = Sbuf.col = 0;
- for (i = 0; i < SB_ROWS; ++i) {
- Sbuf.lcol[i] = SB_COLS;
- Sbuf.rcol[i] = 0;
- }
- Sbuf.flags = 0;
-
- /* set screen update mode */
- um = strupr(getenv("UPDATEMODE"));
- if (um == NULL || strcmp(um, "BIOS") == 0)
- Sbuf.flags &= ~SB_DIRECT;
- else if (strcmp(um, "DIRECT") == 0)
- Sbuf.flags |= SB_DIRECT;
- else
- return SB_ERR;
-
- return SB_OK;
- }
-
-
- SB_MOVE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\12SBUF\SB_MOVE.C
-
- /*
- * sb_move -- move the screen buffer "cursor"
- */
-
- #include <local\sbuf.h>
-
- extern struct BUFFER Sbuf;
- extern union CELL Scrnbuf[SB_ROWS][SB_COLS];
-
- int
- sb_move(win, r, c)
- struct REGION *win; /* window pointer */
- register short r, c; /* buffer row and column */
- {
- /* don't change anything if request is out of range */
- if (r < 0 || r > win->r1 - win->r0 || c < 0 || c > win->c1 - win->c0)
- return SB_ERR;
- win->row = r;
- win->col = c;
- Sbuf.row = r + win->r0;
- Sbuf.col = c + win->c0;
- return SB_OK;
- }
-
-
- SB_NEW.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\12SBUF\SB_NEW.C
-
- /*
- * sb_new -- prepare a new window (rectangular region)
- * and return a pointer to it
- */
-
- #include <stdio.h>
- #include <malloc.h>
- #include <local\sbuf.h>
-
- struct REGION *
- sb_new(top, left, height, width)
- int top; /* top row */
- int left; /* left column */
- int height; /* total rows */
- int width; /* total columns */
- {
- struct REGION *new;
-
- /* allocate the control data structure */
- new = (struct REGION *)malloc(sizeof (struct REGION));
- if (new != NULL) {
- new->r0 = new->sr0 = top;
- new->r1 = new->sr1 = top + height - 1;
- new->c0 = new->sc0 = left;
- new->c1 = new->sc1 = left + width - 1;
- new->row = new->col = 0;
- new->wflags = 0;
- }
- return (new);
- }
-
-
- SB_PUT.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\12SBUF\SB_PUT.C
-
- /*
- * sb_put -- routines to put characters and strings into the
- * screen buffer; the cursor location is altered
- */
-
- #include <local\sbuf.h>
- #include <ctype.h>
-
- extern struct BUFFER Sbuf;
- extern union CELL Scrnbuf[SB_ROWS][SB_COLS];
-
- /*
- * sb_putc -- put a character into a screen buffer window
- */
-
- int
- sb_putc(win, ch)
- struct REGION *win;
- unsigned char ch;
- {
- short cmax, rmax;
- short lim;
- short noscroll = 0, puterr = 0;
-
- /* calculate screen buffer position and limits */
- cmax = win->c1 - win->c0;
- rmax = win->r1 - win->r0;
- Sbuf.row = win->r0 + win->row;
- Sbuf.col = win->c0 + win->col;
-
- /* process the character */
- switch (ch) {
- case '\b':
- /* non-destructive backspace */
- if (win->col > 0) {
- --win->col;
- Sbuf.col = win->c0 + win->col;
- return SB_OK;
- }
- else
- return SB_ERR;
- case '\n':
- /* clear trailing line segment */
- while (win->col < cmax)
- if (sb_putc(win, ' ') == SB_ERR)
- ++puterr;
- break;
- case '\t':
- /* convert tab to required number of spaces */
- lim = win->col + 8 - (win->col & 0x7);
- while (win->col < lim)
- if (sb_putc(win, ' ') == SB_ERR)
- ++puterr;
- break;
- default:
- /* if printable ASCII, place the character in the buffer */
- if (isascii(ch) && isprint(ch))
- Scrnbuf[Sbuf.row][Sbuf.col].b.ch = ch;
- if (Sbuf.col < Sbuf.lcol[Sbuf.row])
- Sbuf.lcol[Sbuf.row] = Sbuf.col;
- if (Sbuf.col > Sbuf.rcol[Sbuf.row])
- Sbuf.rcol[Sbuf.row] = Sbuf.col;
- break;
- }
-
- /* update the cursor position */
- if (win->col < cmax)
- ++win->col;
- else if (win->row < rmax) {
- win->col = 0;
- ++win->row;
- }
- else if ((win->wflags & SB_SCROLL) == SB_SCROLL) {
- sb_scrl(win, 1);
- win->col = 0;
- win->row = rmax;
- }
- else
- ++noscroll;
-
- /* update screen buffer position */
- Sbuf.row = win->r0 + win->row;
- Sbuf.col = win->c0 + win->col;
- Sbuf.flags |= SB_DELTA;
-
- return ((noscroll || puterr) ? SB_ERR : SB_OK);
- } /* end sb_putc() */
-
-
- /*
- * sb_puts -- put a string into the screen buffer
- */
-
- int
- sb_puts(win, s)
- struct REGION *win;
- unsigned char *s;
- {
- while (*s)
- if (sb_putc(win, *s++) == SB_ERR)
- return SB_ERR;
- return SB_OK;
- } /* end sb_puts() */
-
-
- SB_READ.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\12SBUF\SB_READ.C
-
- /*
- * sb_read -- read character/attribute data
- */
-
- #include <local\sbuf.h>
-
- extern struct BUFFER Sbuf;
- extern union CELL Scrnbuf[SB_ROWS][SB_COLS];
-
- unsigned char
- sb_ra(win)
- struct REGION *win; /* window pointer */
- {
- return (Scrnbuf[win->r0 + win->row][win->c0 + win->col].b.attr);
- } /* end sb_ra() */
-
-
- /*
- * sb_rc -- read character from current location in screen buffer
- */
-
- unsigned char
- sb_rc(win)
- struct REGION *win; /* window pointer */
- {
- return (Scrnbuf[win->r0 + win->row][win->c0 + win->col].b.ch);
- } /* end sb_rc() */
-
-
- /*
- * sb_rca -- read character/attribute pair from current
- * location in screen buffer
- */
-
- unsigned short
- sb_rca(win)
- struct REGION *win; /* window pointer */
- {
- return (Scrnbuf[win->r0 + win->row][win->c0 + win->col].cap);
- } /* end sb_rca() */
-
-
- SB_SCRL.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\12SBUF\SB_SCRL.C
-
- /*
- * sb_scrl -- scrolling routines
- */
-
- #include <local\sbuf.h>
-
- extern struct BUFFER Sbuf;
- extern union CELL Scrnbuf[SB_ROWS][SB_COLS];
-
-
- /*
- * sb_scrl -- scroll the specified window
- * n lines (direction indicated by sign)
- */
-
- int
- sb_scrl(win, n)
- struct REGION *win;
- short n; /* number of rows to scroll */
- {
- register short r, c;
-
- if (n == 0)
- /* clear the entire region to spaces */
- sb_fillc(win, ' ');
- else if (n > 0) {
- /* scroll n rows up */
- for (r = win->sr0; r <= win->sr1 - n; ++r) {
- for (c = win->sc0; c <= win->sc1; ++c)
- Scrnbuf[r][c] = Scrnbuf[r + n][c];
- if (win->sc0 < Sbuf.lcol[r])
- Sbuf.lcol[r] = win->sc0;
- if (win->sc1 > Sbuf.rcol[r])
- Sbuf.rcol[r] = win->sc1;
- }
- for ( ; r <= win->sr1; ++r) {
- for (c = win->sc0; c <= win->sc1; ++c)
- Scrnbuf[r][c].b.ch = ' ';
- if (win->sc0 < Sbuf.lcol[r])
- Sbuf.lcol[r] = win->sc0;
- if (win->sc1 > Sbuf.rcol[r])
- Sbuf.rcol[r] = win->sc1;
- }
- }
- else {
- /* scroll n rows down */
- n = -n;
- for (r = win->sr1; r >= win->sr0 + n; --r) {
- for (c = win->sc0; c <= win->sc1; ++c)
- Scrnbuf[r][c] = Scrnbuf[r - n][c];
- if (win->sc0 < Sbuf.lcol[r])
- Sbuf.lcol[r] = win->sc0;
- if (win->sc1 > Sbuf.rcol[r])
- Sbuf.rcol[r] = win->sc1;
- }
- for ( ; r >= win->sr0; --r) {
- for (c = win->sc0; c <= win->sc1; ++c)
- Scrnbuf[r][c].b.ch = ' ';
- if (win->sc0 < Sbuf.lcol[r])
- Sbuf.lcol[r] = win->sc0;
- if (win->sc1 > Sbuf.rcol[r])
- Sbuf.rcol[r] = win->sc1;
- }
- }
- Sbuf.flags |= SB_DELTA;
- return SB_OK;
- } /* end sb_scrl() */
-
-
- /*
- * sb_set_scrl -- set the scroll region boundaries
- */
-
- int
- sb_set_scrl(win, top, left, bottom, right)
- struct REGION *win; /* window pointer */
- short top, left; /* upper-left corner */
- short bottom, right; /* lower-left corner */
- {
- if (top < 0 || left < 0 ||
- bottom > win->r1 - win->r0 || right > win->c1 - win->c0)
- return SB_ERR;
- win->sr0 = win->r0 + top;
- win->sc0 = win->c0 + left;
- win->sr1 = win->r0 + bottom - 1;
- win->sc1 = win->c0 + right - 1;
- return SB_OK;
- } /* end sb_set_scrl() */
-
-
- SB_SHOW.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\12SBUF\SB_SHOW.C
-
- /*
- * sb_show -- copy the screen buffer to display memory
- */
-
- #include <stdio.h>
- #include <dos.h>
- #include <memory.h>
- #include <local\sbuf.h>
- #include <local\video.h>
-
- #define MDA_SEG 0xB000
- #define CGA_SEG 0xB800
- #define NBYTES (2 * SB_COLS)
-
- /* macro to synchronize with vertical retrace period */
- #define VSTAT 0x3DA
- #define VRBIT 8
- #define VSYNC while ((inp(VSTAT) & VRBIT) == VRBIT); \
- while ((inp(VSTAT) & VRBIT) != VRBIT)
-
- extern struct BUFFER Sbuf;
- extern union CELL Scrnbuf[SB_ROWS][SB_COLS];
-
- int
- sb_show(pg)
- short pg;
- {
- register short r, c;
- short n;
- short count, ncols;
- unsigned int src_os, dest_os;
- struct SREGS segregs;
-
- if ((Sbuf.flags & SB_DIRECT) == SB_DIRECT) {
- /* use the direct-screen interface */
- segread(&segregs);
-
- /* determine extent of changes */
- n = 0;
- for (r = 0; r < SB_ROWS; ++r)
- if (Sbuf.lcol[r] <= Sbuf.rcol[r])
- ++n;
- src_os = dest_os = 0;
- if (n <= 2)
- /* copy only rows that contain changes */
- for (r = 0; r < SB_ROWS; ++r) {
- if (Sbuf.lcol[r] <= Sbuf.rcol[r]) {
- /* copy blocks during vertical retrac
- VSYNC;
- movedata(segregs.ds,
- (unsigned)&Scrnbuf[0][0] + sr
- CGA_SEG, dest_os, NBYTES);
- Sbuf.lcol[r] = SB_COLS;
- Sbuf.rcol[r] = 0;
- }
- src_os += SB_COLS;
- dest_os += NBYTES;
- }
- else {
- /* copy the entire buffer */
- count = 3 * NBYTES;
- ncols = 3 * SB_COLS;
- for (r = 0; r < SB_ROWS - 1; r += 3) {
- VSYNC;
- movedata(segregs.ds, (unsigned)&Scrnbuf[0][0]
- + src_os, CGA_SEG, dest_os, count);
- src_os += ncols;
- dest_os += count;
- }
- VSYNC;
- movedata(segregs.ds, (unsigned)&Scrnbuf[0][0] + src_o
- CGA_SEG, dest_os, NBYTES);
- for (r = 0; r < SB_ROWS; ++r) {
- Sbuf.lcol[r] = SB_COLS;
- Sbuf.rcol[r] = 0;
- }
- }
- }
- else
- /* use the BIOS video interface */
- for (r = 0; r < SB_ROWS; ++r)
- /* copy only changed portions of lines */
- if (Sbuf.lcol[r] < SB_COLS && Sbuf.rcol[r] > 0) {
- for (c = Sbuf.lcol[r]; c <= Sbuf.rcol[r]; ++c
- putcur(r, c, pg);
- writeca(Scrnbuf[r][c].b.ch,
- Scrnbuf[r][c].b.attr, 1, pg);
- }
- Sbuf.lcol[r] = SB_COLS;
- Sbuf.rcol[r] = 0;
- }
-
- /* the display now matches the buffer -- clear flag bit */
- Sbuf.flags &= ~SB_DELTA;
-
- return SB_OK;
- }
-
-
- SB_TEST.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\12SBUF\SB_TEST.C
-
- /*
- * sb_test -- driver for screen-buffer interface functions
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- #include <local\std.h>
- #include <local\keydefs.h>
- #include <local\sbuf.h>
- #include <local\video.h>
- #include <local\box.h>
- #include "sb_test.h"
-
- #define BEL 7
-
- extern struct BUFFER Sbuf;
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- char *s, line[MAXLINE];
- int k;
- short i;
- FILE *fp;
- char fname[MAXPATH];
- struct REGION *cmnd, *stat, *text, *help, *curwin;
- unsigned char cmndattr, statattr, textattr, helpattr, curattr;
- unsigned char ch, userattr;
-
- /* function prototypes */
- int sb_init();
- int sb_move(struct REGION *, short, short);
- struct REGION *sb_new(short, short, short, short);
- int sb_putc(struct REGION *, unsigned char);
- int sb_puts(struct REGION *, char *);
- int sb_show(short);
- int sb_fill(struct REGION *, unsigned char, unsigned char);
- char *get_fname(struct REGION *, char *, short);
-
- getstate();
- readca(&ch, &userattr, Vpage);
-
- /* set up the screen buffer */
- if (sb_init() == SB_ERR) {
- fprintf(stderr, "Bad UPDATEMODE value in environment\n");
- exit(1);
- }
-
- /* set up windows and scrolling regions */
- cmnd = sb_new(CMND_ROW, CMND_COL, CMND_HT, CMND_WID);
- stat = sb_new(STAT_ROW, STAT_COL, STAT_HT, STAT_WID);
- text = sb_new(TEXT_ROW, TEXT_COL, TEXT_HT, TEXT_WID);
- help = sb_new(HELP_ROW, HELP_COL, HELP_HT, HELP_WID);
- text->wflags |= SB_SCROLL;
- sb_set_scrl(help, 1, 1, HELP_HT - 1, HELP_WID - 1);
-
- /* display each primary window in its own attribute */
- cmndattr = GRN;
- statattr = (WHT << 4) | BLK;
- textattr = (BLU << 4) | CYAN;
- helpattr = (GRN << 4) | YEL;
- sb_fill(cmnd, ' ', cmndattr);
- if (sb_move(cmnd, 0, 0) == SB_OK)
- sb_puts(cmnd, "SB_TEST (Version 1.0)");
- sb_fill(stat, ' ', statattr);
- if (sb_move(stat, 0, 0) == SB_OK)
- sb_puts(stat, "*** STATUS AREA ***");
- for (i = 0; i <= text->r1 - text->r0; ++i) {
- sb_move(text, i, 0);
- sb_wca(text, i + 'a', textattr,
- text->c1 - text->c0 + 1);
- }
- if (sb_move(text, 10, 25) == SB_OK)
- sb_puts(text, " *** TEXT DISPLAY AREA *** ");
- sb_show(Vpage);
- curwin = text;
- curattr = textattr;
-
- /* respond to user commands */
- while ((k = getkey()) != K_ESC) {
- switch (k) {
- case K_UP:
- sb_scrl(curwin, 1);
- break;
- case K_DOWN:
- sb_scrl(curwin, -1);
- break;
- case K_PGUP:
- sb_scrl(curwin, curwin->sr1 - curwin->sr0);
- break;
- case K_PGDN:
- sb_scrl(curwin, -(curwin->sr1 - curwin->sr0));
- break;
- case K_ALTC:
- /* clear the current window */
- sb_fill(curwin, ' ', curattr);
- break;
- case K_ALTH:
- /* display help */
- curwin = help;
- curattr = helpattr;
- for (i = 0; i < help->r1 - help->r0; ++i) {
- sb_move(help, i, 0);
- sb_wca(help, i + 'a', helpattr,
- help->c1 - help->c0 + 1);
- }
- sb_box(help, BOXBLK, helpattr);
- break;
- case K_ALTS:
- /* fill the command area with letters */
- curwin = stat;
- curattr = statattr;
- sb_fill(stat, 's', statattr);
- break;
- case K_ALTT:
- /* fill the text area */
- curwin = text;
- curattr = textattr;
- for (i = 0; i <= text->r1 - text->r0; ++i) {
- sb_move(text, i, 0);
- sb_wca(text, i + 'a', textattr,
- text->c1 - text->c0 + 1);
- }
- break;
- case K_ALTR:
- /* read a file into the current window */
- sb_fill(stat, ' ', statattr);
- sb_move(stat, 0, 0);
- sb_puts(stat, "File to read: ");
- sb_show(Vpage);
- (void)get_fname(stat, fname, MAXPATH);
- if ((fp = fopen(fname, "r")) == NULL) {
- sb_fill(stat, ' ', statattr);
- sb_move(stat, 0, 0);
- sb_puts(stat, "Cannot open ");
- sb_puts(stat, fname);
- }
- else {
- sb_fill(stat, ' ', statattr);
- sb_move(stat, 0, 0);
- sb_puts(stat, "File: ");
- sb_puts(stat, fname);
- sb_show(Vpage);
- sb_fill(text, ' ', textattr);
- sb_move(text, 0, 0);
- putcur(text->r0, text->c0, Vpage);
- while ((s = fgets(line, MAXLINE, fp)) != NULL
- if (sb_puts(text, s) == SB_ERR) {
- clrscrn(userattr);
- putcur(0, 0, Vpage);
- fprintf(stderr, "puts error\n
- exit(1);
- }
- sb_show(Vpage);
- }
- if (ferror(fp)) {
- putcur(text->r0, text->c0, Vpage);
- fprintf(stderr, "Error reading file\n
- }
- fclose(fp);
- }
- break;
- default:
- /* say what? */
- fputc(BEL, stderr);
- continue;
- }
- if ((Sbuf.flags & SB_DELTA) == SB_DELTA)
- sb_show(Vpage);
- }
-
- clrscrn(userattr);
- putcur(0, 0, Vpage);
- exit(0);
- }
-
- /*
- * get_fname -- get a filename from the user
- */
-
- char *
- get_fname(win, path, lim)
- struct REGION *win;
- char *path;
- short lim;
- {
- int ch;
- char *s;
-
- s = path;
- sb_show(Vpage);
- while ((ch = getch()) != K_RETURN) {
- if (ch == '\b')
- --s;
- else {
- sb_putc(win, ch);
- *s++ = ch;
- }
- sb_show(Vpage);
- }
- *s = '\0';
- return (path);
- }
-
-
- SB_WRITE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\12SBUF\SB_WRITE.C
-
- /*
- * sb_write -- screen buffer write routines
- */
-
- #include <local\sbuf.h>
-
- extern struct BUFFER Sbuf;
- extern union CELL Scrnbuf[SB_ROWS][SB_COLS];
-
- /*
- * sb_wa -- write an attribute to a region of the screen buffer
- */
-
- int
- sb_wa(win, attr, n)
- struct REGION *win; /* window pointer */
- unsigned char attr; /* attribute */
- short n; /* repetition count */
- {
- short i;
- short row;
- short col;
-
- i = n;
- row = win->r0 + win->row;
- col = win->c0 + win->col;
- while (i--)
- Scrnbuf[row][col + i].b.attr = attr;
-
- /* marked the changed region */
- if (col < Sbuf.lcol[row])
- Sbuf.lcol[row] = col;
- if (col + n > Sbuf.rcol[row])
- Sbuf.rcol[row] = col + n;
- Sbuf.flags |= SB_DELTA;
-
- return (i == 0) ? SB_OK : SB_ERR;
- } /* end sb_wa() */
-
-
- /*
- * sb_wc -- write a character to a region of the screen buffer
- */
-
- int
- sb_wc(win, ch, n)
- struct REGION *win; /* window pointer */
- unsigned char ch; /* character */
- short n; /* repetition count */
- {
- short i;
- short row;
- short col;
-
- i = n;
- row = win->r0 + win->row;
- col = win->c0 + win->col;
- while (i--)
- Scrnbuf[row][col + i].b.ch = ch;
-
- /* marked the changed region */
- if (col < Sbuf.lcol[row])
- Sbuf.lcol[row] = col;
- if (col + n > Sbuf.rcol[row])
- Sbuf.rcol[row] = col + n;
- Sbuf.flags |= SB_DELTA;
-
- return (i == 0 ? SB_OK : SB_ERR);
- } /* end sb_wc() */
-
-
- /*
- * sb_wca -- write a character/attribute pair to a region
- * of the screen buffer
- */
-
- int
- sb_wca(win, ch, attr, n)
- struct REGION *win; /* window pointer */
- unsigned char ch; /* character */
- unsigned char attr; /* attribute */
- short n; /* repetition count */
- {
- int i;
- short row;
- short col;
-
- i = n;
- row = win->r0 + win->row;
- col = win->c0 + win->col;
- while (i--)
- Scrnbuf[row][col + i].cap = (attr << 8) | ch;
-
- /* marked the changed region */
- if (col < Sbuf.lcol[row])
- Sbuf.lcol[row] = col;
- if (col + n > Sbuf.rcol[row])
- Sbuf.rcol[row] = col + n;
- Sbuf.flags |= SB_DELTA;
-
- return (i == 0 ? SB_OK : SB_ERR);
- } /* end sb_wca() */
-
-
- SC.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\13ANSI\SC.C
-
- /*
- * SetColor (sc) -- set foreground, background, and border
- * attributes on systems equipped with color display systems
- *
- * Usage: sc [foreground [background [border]]]
- * sc [attribute]
- */
-
- #include <stdio.h>
- #include <dos.h>
- #include <local\std.h>
- #include <local\ansi.h>
- #include <local\ibmcolor.h>
-
- main(argc, argv)
- int argc;
- char **argv;
- {
- extern void ansi_tst();
- extern BOOLEAN iscolor();
- extern void setattr(POSITION, int);
- extern void menumode();
- extern parse(int, char **);
-
- ansi_tst();
- if (iscolor() == FALSE) {
- fprintf(stderr, "\n\nSystem not in a color text mode.\n");
- fprintf(stderr, "Use the MODE command to set the mode.\n");
- exit(2);
- }
-
- /* process either batch or interactive commands */
- if (argc > 1)
- /* batch mode processing */
- parse(argc, argv);
- else
- /* no command-line args -- interactive mode */
- menumode();
-
- ANSI_ED;
- exit (0);
- }
-
-
- SCROLL.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\SCROLL.C
-
- /*
- * scroll -- scroll a region of the "visual" screen
- * page up or down by n rows (0 = initialize region)
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
-
- int
- scroll(t, l, b, r, n, a)
- int t; /* top row of scroll region */
- int l; /* left column */
- int b; /* bottom row */
- int r; /* right column */
- int n; /* number of lines to scroll */
- /* sign indicates direction to scroll */
- /* 0 means scroll all lines in the region (initialize) */
- unsigned char a;/* attribute for new lines */
- {
- union REGS inregs, outregs;
-
- if (n < 0) {
- /* scroll visual page down n lines */
- inregs.h.ah = SCROLL_DN;
- inregs.h.al = -n;
- }
- else {
- /* scroll visual page up n lines */
- inregs.h.ah = SCROLL_UP;
- inregs.h.al = n;
- }
- inregs.h.bh = a; /* attribute of blank lines */
- inregs.h.bl = 0;
- inregs.h.ch = t; /* upper-left of scroll region */
- inregs.h.cl = l;
- inregs.h.dh = b; /* lower-right of scroll region */
- inregs.h.dl = r;
- int86(VIDEO_IO, &inregs, &outregs);
-
- return (outregs.x.cflag);
- }
-
-
- SC_CMDS.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\13ANSI\SC_CMDS.C
-
- /*
- * sc_cmds -- display command summary
- */
-
- #include <stdio.h>
- #include <local\ansi.h>
-
- void
- sc_cmds(fg, bkg, bdr)
- int fg, bkg, bdr;
- {
- static char *color_xlat[] = {
- "Black (0)", "Blue (1)", "Green (2)", "Cyan (3)",
- "Red (4)", "Magenta (5)", "Brown (6)", "White (7)",
- "Grey (8)", "Light blue (9)", "Light green (10)",
- "Light cyan (11)", "Light red (12)", "Light magenta (13)",
- "Yellow (14)", "Bright white (15)"
- };
-
- ANSI_CUP(2, 29);
- fputs("*** SetColor (SC) ***", stdout);
- ANSI_CUP(4, 17);
- fputs("Attribute Decrement Increment Current Value", stdout);
- ANSI_CUP(5, 17);
- fputs("--------- --------- --------- -------------", stdout);
- ANSI_CUP(6, 17);
- fputs("Foreground F1 F2", stdout);
- ANSI_CUP(7, 17);
- fputs("Background F3 F4", stdout);
- ANSI_CUP(8, 17);
- fputs("Border F5 F6", stdout);
- ANSI_CUP(6, 50);
- fputs(color_xlat[fg], stdout);
- ANSI_CUP(7, 50);
- fputs(color_xlat[bkg], stdout);
- ANSI_CUP(8, 50);
- fputs(color_xlat[bdr], stdout);
- ANSI_CUP(10, 17);
- fputs("Type RETURN to exit. SetColor/Version 2.2", stdout);
- return;
- }
-
-
- SELECT.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\SELECT.C
-
- /*
- * select -- functions to create a selection table and
- * to determine whether an item is an entry in the table
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <local\std.h>
-
- #define NRANGES 10
- #define NDIGITS 5
-
- struct slist_st {
- long int s_min;
- long int s_max;
- } Slist[NRANGES + 1];
-
- long Highest = 0;
-
- /*
- * mkslist -- create the selection lookup table
- */
-
- int
- mkslist(list)
- char *list;
- {
- int i;
- char *listp, *s;
- long tmp;
-
- static long save_range();
-
- /* fill in table of selected items */
- if (*list == '\0') {
- /* if no list, select all */
- Slist[0].s_min = 0;
- Slist[0].s_max = Highest = BIGGEST;
- Slist[1].s_min = -1;
- }
- else {
- listp = list;
- for (i = 0; i < NRANGES; ++i) {
- if ((s = strtok(listp, ", \t")) == NULL)
- break;
- if ((tmp = save_range(i, s)) > Highest)
- Highest = tmp;
- listp = NULL;
- }
- Slist[i].s_min = -1;
- }
- return (0);
- } /* end mkslist() */
-
- /*
- * selected -- return non-zero value if the number
- * argument is a member of the selection list
- */
-
- int
- selected(n)
- unsigned int n;
- {
- int i;
-
- /* look for converted number in selection list */
- for (i = 0; Slist[i].s_min != -1; ++i)
- if (n >= Slist[i].s_min && n <= Slist[i].s_max)
- return (1);
- return (0);
- } /* end selected() */
-
- /*
- * save_range -- convert a string number spec to a
- * numeric range in the selection table and return
- * the highest number in the range
- */
-
- static long
- save_range(n, s)
- int n;
- char *s;
- {
- int radix = 10;
- char *cp, num[NDIGITS + 1];
-
- /* get the first (and possibly only) number */
- cp = num;
- while (*s != '\0' && *s != '-')
- *cp++ = *s++;
- *cp = '\0';
- Slist[n].s_min = atol(num);
- if (*s == '\0')
- /* pretty narrow range, huh? */
- return (Slist[n].s_max = Slist[n].s_min);
-
- /* get the second number */
- if (*++s == '\0')
- /* unspecified top end of range */
- Slist[n].s_max = BIGGEST;
- else {
- cp = num;
- while (*s != '\0' && *s != '-')
- *cp++ = *s++;
- *cp = '\0';
- Slist[n].s_max = atol(num);
- }
- return (Slist[n].s_max);
- } /* end save_range() */
-
-
- SETATTR.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\13ANSI\SETATTR.C
-
- /*
- * setattr -- execute an attribute update
- */
-
- #include <stdio.h>
- #include <local\ansi.h>
- #include <local\ibmcolor.h>
-
- #define C_MASK 0x7
-
- void
- setattr(pos, attr)
- POSITION pos; /* attribute position */
- int attr; /* composite attribute number (base attr | intensity) */
- {
- static int ibm2ansi[] = {
- ANSI_BLACK, ANSI_BLUE, ANSI_GREEN, ANSI_CYAN,
- ANSI_RED, ANSI_MAGENTA, ANSI_BROWN, ANSI_WHITE
- };
-
- switch (pos) {
- case FGND:
- if (attr & IBM_BRIGHT)
- ANSI_SGR(ANSI_BOLD);
- ANSI_SGR(ibm2ansi[attr & C_MASK] + ANSI_FOREGROUND);
- break;
- case BKGND:
- if (attr & IBM_BRIGHT)
- ANSI_SGR(ANSI_BLINK);
- ANSI_SGR(ibm2ansi[attr & C_MASK] + ANSI_BACKGROUND);
- break;
- case BDR:
- palette(0, attr);
- break;
- }
- return;
- }
-
-
- SETCTYPE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\SETCTYPE.C
-
- /*
- * setctype -- set the cursor start and end raster scan lines
- */
-
- #include <dos.h>
- #include <local\bioslib.h>
-
- #define LO_NIBBLE 0x0F
- #define CURSOR_OFF 0x2
- #define MAXSCANLN 15
-
- int
- setctype(start, end)
- int start; /* starting raster scan line */
- int end; /* ending raster scan line */
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = CUR_TYPE;
- inregs.h.ch = start & LO_NIBBLE;
- inregs.h.cl = end & LO_NIBBLE;
- if (start >= MAXSCANLN) {
- inregs.h.ah |= CURSOR_OFF;
- inregs.h.al = MAXSCANLN;
- }
- int86(VIDEO_IO, &inregs, &outregs);
-
- return (outregs.x.cflag);
- }
-
-
- SETDTA.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\DOS\SETDTA.C
-
- /*
- * setdta -- tell DOS where to do disk transfers
- */
-
- #include <dos.h>
- #include <local\doslib.h>
-
- void
- setdta(bp)
- char *bp; /* pointer to byte-aligned disk transfer area */
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = SET_DTA;
- inregs.x.dx = (unsigned int)bp;
- (void)intdos(&inregs, &outregs);
- }
-
-
- SETFREQ.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\SETFREQ.C
-
- /*
- * setfreq -- sets PC's tone generator to run
- * continuously at the specified frequency
- */
-
- #include <conio.h>
- #include <local\timer.h>
-
- void
- setfreq(f)
- unsigned f; /* frequency in Hertz (approximate) */
- {
- unsigned divisor = TIMER_CLK / f;
-
- outp(TIMER_CTRL, TIMER_PREP); /* prepare timer */
- outp(TIMER_COUNT, (divisor & 0xFF)); /* low byte of divisor */
- outp(TIMER_COUNT, (divisor >> 8)); /* high byte of divisor */
- }
-
-
- SETMYDIR.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\03DOS\SETMYDIR.C
-
- /*
- * setmydir -- try to change the DOS environment
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <local\std.h>
-
- main(argc, argv)
- int argc;
- char **argv;
- {
- register char **p;
- static char var[] = { "MYDIR" };
- static char pgm[MAXNAME + 1] = { "setmydir" };
- extern void fatal(char *, char *, int);
- extern void getpname(char *, char *);
-
- /* use an alias if one is given to this program */
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- /* try to add the MYDIR variable to the environment */
- if (putenv("MYDIR=c:\\mydir") == -1)
- fatal(pgm, "Error changing environment", 1);
-
- /* display the environment for this process */
- for (p = environ; *p; p++) {
- printf("%s\n", *p);
- }
-
- exit(0);
- }
-
-
- SETPAGE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\SETPAGE.C
-
- /*
- * setpage -- select "visual" screen page for viewing
- * (the "active" page is the one being written to)
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
- #include <local\video.h>
-
- int
- setpage(pg)
- int pg; /* visual screen page number */
- {
- union REGS inregs, outregs;
-
- /* check page number against table */
- if (Maxpage[Vmode] > 0 && (pg < 0 || pg >= Maxpage[Vmode]))
- return (-1);
-
- /* change the visual page */
- inregs.h.ah = SET_PAGE;
- inregs.h.al = pg;
- int86(VIDEO_IO, &inregs, &outregs);
-
- return (outregs.x.cflag);
- }
-
-
- SETVMODE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\SETVMODE.C
-
- /*
- * setvmode -- set the video mode
- * (color/graphics systems only)
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
-
- /***********************************************************
- *
- * mode # (m) description
- * ------------- ---------------------------------
- * PC MODES:
- * 0 40x25 Mono text (c/g default)
- * 1 40x25 Color text
- * 2 80x25 Mono text
- * 3 80x25 Color text
- * 4 320x200 4-color graphics (med res)
- * 5 320x200 Mono graphics (med res)
- * 6 640x200 2-color graphics (hi res)
- * 7 80x25 on monochrome adapter
- *
- * PCjr MODES:
- * 8 160x200 16-color graphics
- * 9 320x200 16-color graphics
- * 10 640x200 4-color fraphics
- *
- * EGA MODES:
- * 13 320x200 16-color graphics
- * 14 620x200 16-color graphics
- * 15 640x350 mono graphics
- * 16 640x350 color graphics (4- or 16-color)
- ***********************************************************/
-
- int
- setvmode(vmode)
- unsigned int vmode; /* user-specified mode number */
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = SET_MODE;
- inregs.h.al = vmode; /* value not checked */
- int86(VIDEO_IO, &inregs, &outregs);
-
- /* update video structure */
- getstate();
-
- return (outregs.x.cflag);
- }
-
-
- SHOW.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\10DUMP\SHOW.C
-
- /*
- * show -- a filter that displays the contents of a file
- * in a way that is guaranteed to be displayable
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <io.h>
- #include <local\std.h>
-
- main(argc, argv)
- int argc;
- char **argv;
- {
- int ch;
- FILE *fp;
- BOOLEAN sflag = FALSE; /* strip non-ASCII characters */
- BOOLEAN vflag = FALSE; /* verbose mode */
- BOOLEAN wflag = FALSE; /* filter typical word processing codes
- BOOLEAN errflag = FALSE;
- static char pgm[] = { "show" };
-
- extern int getopt(int, char **, char *);
- extern char *optarg;
- extern int optind, opterr;
- extern int showit(FILE *, BOOLEAN, BOOLEAN);
- extern void fatal(char *, char *, int);
-
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- while ((ch = getopt(argc, argv, "svw")) != EOF) {
- switch (ch) {
- case 's': /* strip non-ASCII characters */
- sflag = TRUE;
- break;
- case 'v': /* verbose */
- vflag = TRUE;
- break;
- case 'w': /* use word-processing conventions */
- wflag = sflag = TRUE;
- break;
- case '?':
- errflag = TRUE;
- break;
- }
- }
-
- /* check for errors */
- if (errflag == TRUE) {
- fprintf(stderr, "Usage: %s [-sv] [file...]\n", pgm);
- exit(1);
- }
-
- /* if no file names, use standard input */
- if (optind == argc) {
- if (setmode(fileno(stdin), O_BINARY) == -1)
- fatal(pgm, "Cannot set binary mode on stdin", 2);
- showit(stdin, sflag, wflag);
- exit(0);
- }
-
- /* otherwise, process remainder of command line */
- for ( ; optind < argc; ++optind) {
- if ((fp = fopen(argv[optind], "rb")) == NULL) {
- fprintf(stderr,
- "%s: Error opening %s\n", pgm, argv[optind]);
- perror("");
- continue;
- }
- if (vflag == TRUE)
- fprintf(stdout, "\n%s:\n", argv[optind]);
- if (showit(fp, sflag, wflag) != 0) {
- fprintf(stderr,
- "%s: Error reading %s\n", pgm, argv[optind]);
- perror("");
- }
- if (fclose(fp) == EOF)
- fatal(pgm, "Error closing input file", 2);
- }
-
- exit(0);
- }
-
-
- SHOWENV.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\03DOS\SHOWENV.C
-
- /*
- * showenv -- display the values of any DOS variables
- * named on the invocation command line
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <local\std.h>
-
- main(argc, argv, envp)
- int argc;
- char **argv;
- char **envp;
- {
- register char *ep;
- static char pgm[MAXNAME + 1] = { "showenv" };
- extern void getpname(char *, char *);
-
- /* use an alias if one is given to this program */
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- /* if no arguments, show full environment list */
- if (argc == 1)
- for (; *envp; ++envp)
- printf("%s\n", *envp);
- else {
- /*
- * treat all args as DOS variable names and
- * display values of only specified variables
- */
- ++argv; /* skip past command name */
- --argc;
- while (argc > 0) {
- if ((ep = getenv(strupr(*argv))) == NULL)
- fprintf(stderr, "%s not defined\n", *argv);
- else
- printf("%s=%s\n", *argv, ep);
- ++argv;
- --argc;
- }
- }
- exit(0);
- }
-
-
- SHOWIT.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\10DUMP\SHOWIT.C
-
- /*
- * showit -- make non-printable characters in
- * the stream fp visible (or optionally strip them)
- */
-
- #include <stdio.h>
- #include <ctype.h>
- #include <local\std.h>
-
- int
- showit(fp, strip, wp)
- FILE *fp;
- BOOLEAN strip; /* strip non-ASCII codes */
- BOOLEAN wp; /* filter typical word processing codes */
- {
- int ch;
-
- clearerr(fp);
- while ((ch = getc(fp)) != EOF)
- if (isascii(ch) && (isprint(ch) || isspace(ch)))
- switch (ch) {
- case '\r':
- if (wp == TRUE) {
- if ((ch = getc(fp)) != '\n')
- ungetc(ch, fp);
- putchar('\r');
- putchar('\n');
- }
- else
- putchar(ch);
- break;
- default:
- putchar(ch);
- break;
- }
- else if (strip == FALSE)
- printf("\\%02X", ch);
- else if (wp == TRUE && isprint(ch & ASCII))
- putchar(ch & ASCII);
- return (ferror(fp));
- }
-
-
- SHOWTABS.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\07CONFIG\SHOWTABS.C
-
- /*
- * showtabs -- graphically display tabstop settings
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <local\std.h>
-
- #define MAXCOL 80
- #define TABWIDTH 8
-
- extern long Highest;
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- int ch, i;
- int interval, tablist[MAXLINE + 1], *p;
- char *tabstr;
- BOOLEAN errflag, fflag, vflag;
- static char pgm[MAXNAME + 1] = { "showtabs" };
-
- extern char *getpname(char *, char *);
- extern int getopt(int, char **, char *);
- extern char *optarg;
- extern int optind, opterr;
- extern int mkslist(char *);
- extern int selected(long);
- extern void fixtabs(int);
- extern void vartabs(int *);
- extern int tabstop(int);
-
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- /* process command-line options */
- errflag = fflag = vflag = FALSE;
- interval = 0;
- while ((ch = getopt(argc, argv, "f:v:")) != EOF) {
- switch (ch) {
- case 'f':
- /* used fixed tabbing interval */
- if (vflag == FALSE) {
- fflag = TRUE;
- interval = atoi(optarg);
- }
- break;
- case 'v':
- /* use list of tabs */
- if (fflag == FALSE) {
- vflag = TRUE;
- strcpy(tabstr, optarg);
- }
- break;
- case '?':
- errflag = TRUE;
- break;
- }
- }
- if (errflag == TRUE) {
- fprintf(stderr, "Usage: %s [-f interval | -v tablist]\n", pgm
- exit(2);
- }
-
- /* set the tabstops */
- if (vflag == TRUE) {
- /* user-supplied variable tab list */
- mkslist(tabstr);
- p = tablist;
- for (i = 0; i < MAXLINE && i < Highest; ++i)
- *p++ = selected((long)i + 1) ? i : 0;
- *p = -1; /* terminate the list */
- vartabs(tablist);
- }
- else if (fflag == TRUE)
- /* user-supplied fixed tabbing interval */
- fixtabs(interval);
- else
- /* hardware default tabbing interval*/
- fixtabs(TABWIDTH);
-
- /* display current tabs settings */
- for (i = 0; i < MAXCOL; ++i)
- if (tabstop(i))
- fputc('T', stdout);
- else if ((i + 1) % 10 == 0)
- fputc('+', stdout);
- else
- fputc('-', stdout);
- fputc('\n', stdout);
-
- exit(0);
- }
-
-
- SOUND.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\06USER\SOUND.C
-
- /*
- * sound -- produce a constant tone for a specified duration
- */
-
- #include <local\sound.h>
-
- void
- sound(f, dur)
- unsigned int f; /* frequency of pitch in hertz */
- float dur; /* in seconds and tenths of seconds */
- {
- extern void setfreq(unsigned int);
- extern void delay(float);
-
- /* set frequency in hertz */
- setfreq(f);
-
- /* turn the speaker on for specified duration */
- SPKR_ON;
- delay(dur);
- SPKR_OFF;
- }
-
-
- SOUNDS.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\06USER\SOUNDS.C
-
- /*
- * sounds -- make various sounds on demand
- */
-
- #include <stdio.h>
- #include <conio.h>
- #include <math.h>
-
- #define ESC 27
-
- extern void sound(unsigned int, float);
-
- main()
- {
- int ch;
-
- fprintf(stderr, "1=warble 2=error 3=confirm 4=warn\n");
- fprintf(stderr, "Esc=quit\n");
- while ((ch = getch()) != ESC)
- switch (ch) {
- case '1':
- warble();
- break;
- case '2':
- error();
- break;
- case '3':
- confirm();
- break;
- case '4':
- warn();
- break;
- }
- exit(0);
- }
-
- #define CYCLES 3
- #define LOTONE 600
- #define HITONE 1200
- #define PERIOD 0.1
-
- warble()
- {
- int i;
-
- for (i = 0; i < 2 * CYCLES; ++i)
- if (i % 2)
- sound(LOTONE, PERIOD);
- else
- sound(HITONE, PERIOD);
- }
-
- error()
- {
- float d = 0.15;
-
- sound(440, d);
- sound(220, d);
- }
-
- confirm()
- {
- float d = 0.15;
-
- sound(440, d);
- sound(880, d);
- }
-
- warn()
- {
- float d = 0.2;
-
- sound(100, d);
- }
-
-
- SPACES.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\SPACES.C
-
- /*
- * spaces -- send spaces (blanks) to the output stream
- */
-
- #include <stdio.h>
- #include <stdlib.h>
-
- int
- spaces(n, fp)
- int n;
- FILE *fp;
- {
- register int i;
-
- for (i = 0; i < n; ++i)
- if (putc(' ', fp) == EOF && ferror(fp))
- break;
-
- /* return number of spaces emitted */
- return (i);
- }
-
-
- SPKR.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\06USER\SPKR.C
-
- /*
- * spkr -- turn speaker ON/OFF
- *
- * no args => OFF
- * any arg(s) => ON
- */
-
- #include <local\sound.h>
-
- main(argc, argv)
- int argc;
- char **argv;
- {
- /* turn speaker on or off */
- if (argc == 1)
- SPKR_OFF;
- else
- SPKR_ON;
- exit(0);
- }
-
-
- ST.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\11SCREEN\ST.C
-
- /*
- * st -- screen test using cpblk function
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- #include <ctype.h>
- #include <dos.h>
- #include <local\std.h>
- #include <local\video.h>
-
- #define CG_SEG 0xB800
- #define MONO_SEG 0xB000
- #define NBYTES 0x1000
- #define PAGESIZ (NBYTES / 2)
- #define PG0_OS 0
- #define PG1_OS PG0_OS + NBYTES
- #define ESC 27
- #define MAXSCAN 14
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- int i;
- int k; /* user command character */
- int ca; /* character/attribute word */
- int ch; /* character value read */
- int row, col; /* cursor position upon entry */
- int c_start, c_end; /* cursor scan lines */
- unsigned char attr; /* saved video attribute */
- unsigned dseg; /* destination buffer segment *
- unsigned os; /* page offset in bytes */
- static unsigned sbuf[NBYTES]; /* screen buffer */
- unsigned *bp; /* screen element pointer */
- unsigned sseg; /* source segment */
- int special; /* use special copy routine */
- int apg, vpg; /* active and visual display pag
-
- /* segment register values */
- struct SREGS segregs;
-
- extern void swap_int(int *, int *);
-
- static char pgm[] = { "st" }; /* program name */
-
- /* save user's current video state */
- getstate();
- readcur(&row, &col, Vpage);
- putcur(row - 1, 0, Vpage);
- readca(&ch, &attr, Vpage);
- getctype(&c_start, &c_end, Vpage);
- setctype(MAXSCAN, c_end);
- clrscrn(attr);
- putcur(1, 1, Vpage);
-
- /* initialize destination segment */
- special = 1;
- fputs("ScreenTest (ST): ", stderr);
- if (Vmode == CGA_C80 || Vmode == CGA_M80) {
- dseg = CG_SEG;
- fprintf(stderr, "Using CGA mode %d", Vmode);
- }
- else if (Vmode == MDA_M80) {
- dseg = MONO_SEG;
- fprintf(stderr, "Using MDA (mode %d)", Vmode);
- special = 0;
- } else
- fprintf(stderr, "%s: Requires 80-column text mode\n", pgm);
-
- /* process command-line arguments */
- if (argc > 2) {
- fprintf(stderr, "Usage: %s [x]\n", pgm);
- exit(2);
- }
- else if (argc == 2)
- special = 0; /* bypass special block move */
-
- /* get data segment value */
- segread(&segregs);
- sseg = segregs.ds;
-
- /* set up "active" and "visual" display pages */
- apg = 1; /* page being written to */
- vpg = 0; /* page being viewed */
-
- /* display buffers on the user's command */
- fprintf(stderr, " -- Type printable text; Esc=exit");
- while ((k = getkey()) != ESC) {
- if (isascii(k) && isprint(k)) {
- /* fill the buffer */
- ca = ((k % 0xEF) << 8) | k;
- for (bp = sbuf; bp - sbuf < PAGESIZ; ++bp)
- *bp = ca;
- if (Vmode == MDA_M80)
- os = 0;
- else
- os = (apg == 0) ? PG0_OS : PG1_OS;
- if (special)
- cpblk(sbuf, sseg, os, dseg);
- else
- movedata(sseg, sbuf, dseg, os, NBYTES);
- if (Vmode != MDA_M80) {
- swap_int(&apg, &vpg);
- setpage(vpg);
- }
- }
- else {
- clrscrn(attr);
- putcur(0, 0, Vpage);
- writestr(" Type printable text; Esc = exit ", vpg);
- }
- }
-
- /* restore user's video conditions and return to DOS */
- setpage(Vpage);
- clrscrn(attr);
- putcur(0, 0, Vpage);
- setctype(c_start, c_end);
- exit(0);
- }
-
-
- STRDUP.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\14VIEW\STRDUP.C
-
- /*
- * strdup -- duplicate a string
- */
-
- #include <stdio.h>
- #include <malloc.h>
- #include <string.h>
-
- char *
- strdup(str)
- char *str;
- {
- char *buf;
-
- buf = malloc(strlen(str) + 1);
- return (buf == NULL ? buf : strcpy(buf, str));
- }
-
-
- STRING.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\STRING.C
-
- /*
- * string -- emit a sequence of n repetitions of the
- * character ch
- */
-
- #include <stdio.h>
- #include <stdlib.h>
-
- int
- string(n, ch, fp)
- int n;
- char ch;
- FILE *fp;
- {
- register int i;
-
- for (i = 0; i < n; ++i)
- if (fputc(ch, fp) == EOF && ferror(fp))
- break;
-
- /* return number of actual repetitions */
- return (i);
- }
-
-
- SWAP_INT.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\11SCREEN\SWAP_INT.C
-
- /*
- * swap_int -- exchange the values of the two integers
- */
-
- void
- swap_int(p1, p2)
- register int *p1;
- register int *p2;
- {
- int tmp;
-
- /* exchange the values */
- tmp = *p1;
- *p1 = *p2;
- *p2 = tmp;
- }
-
-
- SWEEP.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\06USER\SWEEP.C
-
- /*
- * sweep -- produce a sound that sweeps from
- * a low to a high frequency repeatedly until a
- * key is pressed
- */
-
- #include <conio.h>
- #include <local\sound.h>
-
- main()
- {
- unsigned int f;
- int d, n;
- extern void setfreq(unsigned int);
-
- SPKR_ON;
- while (1) {
- /* give user a way out */
- if (kbhit())
- break;
- n = 10;
- for (f = 100; f <= 5000; f += n) {
- setfreq(f);
- d = 1000;
- /* fake a short delay (machine dependednt) */
- while (d-- > 0)
- ;
- n += 10;
- }
- }
- SPKR_OFF;
- exit(0);
- }
-
-
- TABS.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\TABS.C
-
- /*
- * tabs -- a group of cooperating functions that set
- * and report the settings of "tabstops"
- */
-
- #include <local\std.h>
-
- static char Tabstops[MAXLINE];
-
- /*
- * fixtabs -- set up fixed-interval tabstops
- */
- void
- fixtabs(interval)
- register int interval;
- {
- register int i;
-
- for (i = 0; i < MAXLINE; i++)
- Tabstops[i] = (i % interval == 0) ? 1 : 0;
- } /* end fixtabs() */
-
- /*
- * vartabs -- set up variable tabstops from an array
- * integers terminated by a -1 entry
- */
- void
- vartabs(list)
- int *list;
- {
- register int i;
-
- /* initialize the tabstop array */
- for (i = 0; i < MAXLINE; ++i)
- Tabstops[i] = 0;
-
- /* set user-sprcified tabstops */
- while (*list != -1)
- Tabstops[*++list] = 1;
- } /* end vartabs() */
-
- /*
- * tabstop -- return non-zero if col is a tabstop
- */
- int
- tabstop(col)
- register int col;
- {
- return (col >= MAXLINE ? 1 : Tabstops[col]);
- } /* end tabstop() */
-
-
- TEE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\08FILE\TEE.C
-
- /*
- * tee -- a "pipe fitter" for DOS
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <local\std.h>
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- register int ch, n;
- static char openmode[] = { "w" };
- static char pgm[MAXPATH + 1] = { "tee" };
- FILE *fp[_NFILE]; /* array of file pointers */
-
- extern int getopt(int, char **, char *);
- extern int optind, opterr;
- extern char *optarg;
- extern void getpname(char *, char *);
-
- /* check for an alias */
- if (_osmajor >= 3)
- getpname(argv[0], pgm);
-
- /* process command-line options, if any */
- while ((ch = getopt(argc, argv, "a")) != EOF)
- switch (ch) {
- case 'a':
- strcpy(openmode, "a");
- break;
- case '?':
- break;
- }
- n = argc -= optind;
- argv += optind;
-
- /* check for errors */
- if (argc > _NFILE) {
- fprintf(stderr, "Too many files (max = %d)\n", _NFILE);
- exit(1);
- }
-
- /* open the output file(s) */
- for (n = 0; n < argc; ++n) {
- if ((fp[n] = fopen(argv[n], openmode)) == NULL) {
- fprintf(stderr, "Cannot open %s\n", argv[n]);
- continue;
- }
- }
-
- /* copy input to stdout plus opened file(s) */
- while ((ch = getchar()) != EOF) {
- putchar(ch);
- for (n = 0; n < argc; ++n)
- if (fp[n] != NULL)
- fputc(ch, fp[n]);
- }
-
- /* close file(s) */
- if (fcloseall() == -1) {
- fprintf(stderr, "Error closing a file\n");
- exit(2);
- }
-
- exit(0);
- }
-
-
- TIMEDATA.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\04STDLIB\TIMEDATA.C
-
- /*
- * timedata -- time zone and time value tests
- */
-
- #include <stdio.h>
- #include <time.h>
-
- main()
- {
- long now;
- struct tm *tbuf;
-
- /* get TZ data into global variables */
- tzset();
-
- /* display the global time values */
- printf("daylight savings time flag = %d\n", daylight);
- printf("difference (in seconds) from GMT = %ld\n", timezone);
- printf("standard time zone string is %s\n", tzname[0]);
- printf("daylight time zone string is %s\n", tzname[1]);
-
- /*
- * display the current date and time values for
- * local and universal time
- */
- now = time(NULL);
- printf("\nctime():\t%s\n", ctime(&now));
- tbuf = localtime(&now);
- printf("local time:\t%s\n", asctime(tbuf));
- tbuf = gmtime(&now);
- printf("universal time:\t%s\n", asctime(tbuf));
-
- exit(0);
- }
-
-
- TIMER.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\06USER\TIMER.C
-
- /*
- * timer -- general purpose timer program; uses the
- * PC's intra-application communication area (ICA) as
- * a time and date buffer
- */
-
- #include <dos.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <time.h>
- #include <memory.h>
- #include <local\std.h>
-
- #define NBYTES 16
- #define ICA_SEG 0x4F
- #define MAXTNUM 3
- #define TIMEMASK 0x3FFFFFFF
- #define FLAGBIT 0x80000000
- #define IDBIT 0x40000000
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- int ch;
- char *cp;
- int tn; /* timer number */
- int errflag; /* error flag */
- int eflag; /* elapsed time flag */
- int sflag; /* start timer flag */
- char dest[MAXPATH + 1]; /* destination file name */
- char timestr[MAXLINE]; /* buffer for elapsed time string */
- long now; /* current time */
- long then; /* previously recorded time */
- FILE *fout;
- unsigned long tdata[MAXTNUM];
-
- struct SREGS segregs;
-
- static char pgm[MAXNAME + 1] = { "timer" };
-
- static void usage(char *, char *);
- extern char interval(long, char *);
- extern char *getpname(char *, char *);
- extern int getopt(int, char **, char *);
- extern int optind, opterr;
- extern char *optarg;
-
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- /* process optional arguments */
- fout = stdout;
- tn = 0;
- errflag = eflag = sflag = 0;
- while ((ch = getopt(argc, argv, "0123ef:s")) != EOF) {
- switch (ch) {
- case 'e':
- /* report elapsed timing */
- ++eflag;
- break;
- case 'f':
- /* use specified log file or stream */
- strcpy(dest, optarg);
- if ((fout = fopen(dest, "a")) == NULL) {
- fprintf(stderr, "%s: Cannot open %s\n",
- pgm, dest);
- exit(1);
- }
- break;
- case 's':
- /* start (or restart) timing an interval */
- ++sflag;
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- /* use specified timer */
- tn = ch - 0x30;
- break;
- case '?':
- /* bad option flag */
- ++errflag;
- break;
- }
- }
- argc -= optind;
- argv += optind;
-
- /* check for errors */
- if (errflag > 0 || argc > 0)
- usage(pgm, "Bad command line option(s)");
-
- segread(&segregs);
-
- /* report current date and time */
- now = time(NULL);
- fprintf(fout, "%s", ctime(&now));
-
- /* control and report timer data */
- if (eflag) {
- /* report elapsed time for specified timer */
- movedata(ICA_SEG, 0, segregs.ds, tdata, NBYTES);
- then = tdata[tn];
- if ((then & FLAGBIT) != FLAGBIT || (then & IDBIT) != IDBIT) {
- fprintf(stderr, "Timer database corrupted or not set\
- exit(1);
- }
- interval(now - (then & TIMEMASK), timestr);
- fprintf(stdout, "Elapsed time = %s\n", timestr);
- }
- if (sflag) {
- /* start (or restart) specified timer */
- movedata(ICA_SEG, 0, segregs.ds, tdata, NBYTES);
- tdata[tn] = (now & TIMEMASK) | FLAGBIT | IDBIT;
- movedata(segregs.ds, tdata, ICA_SEG, 0, NBYTES);
- }
- fputc('\n', fout);
-
- exit(0);
- }
-
- /*
- * usage -- display a usage message and exit
- * with an error indication
- */
-
- static void
- usage(pname, mesg)
- char *pname;
- char *mesg;
- {
- fprintf(stderr, "%s\n", mesg);
- fprintf(stderr, "Usage: %s [-efs#]\n", pname);
- fprintf(stderr, "\t-e \tshow an elapsed time (must use start first)\n
- fprintf(stderr, "\t-f file\tappend output to specified file\n");
- fprintf(stderr, "\t-s \tstart (or restart) an interval timer\n");
- fprintf(stderr, "\t-# \tselect a timer (0 to 3; default is 0)\n");
- exit(2);
- }
-
-
- TONE.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\06USER\TONE.C
-
- /*
- * tone -- set the frequency of the sound generator
- */
-
- #include <stdio.h>
-
- main(argc, argv)
- int argc;
- char **argv;
- {
- extern void setfreq(unsigned int);
-
- if (argc != 2) {
- fprintf(stderr, "Usage: tone hertz\n");
- exit(1);
- }
-
- /* set the frequency in Hertz */
- setfreq(atoi(*++argv));
- exit(0);
- }
-
-
- TOUCH.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\08FILE\TOUCH.C
-
- /*
- * touch -- update modification time of file(s)
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- #include <sys\types.h>
- #include <sys\stat.h>
- #include <sys\utime.h>
- #include <io.h>
- #include <errno.h>
- #include <local\std.h>
-
- /* error return -- big enough not to be mistaken for a bad file count */
- #define ERR 0x7FFF
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- int ch;
- int i;
- int badcount; /* # of files that can't be updated */
- struct stat statbuf; /* buffer for stat results */
- BOOLEAN errflag, /* error flag */
- cflag, /* creation flag */
- vflag; /* verbose flag */
- FILE *fp;
-
- static char pgm[MAXNAME + 1] = { "touch" };
- extern int getopt(int, char **, char *);
- extern int optind, opterr;
- extern char *optarg;
- extern void getpname(char *, char *);
- static void usage(char *);
-
- /* get program name from DOS (version 3.00 and later) */
- if (_osmajor >= 3)
- getpname(argv[0], pgm);
-
- /* process optional arguments first */
- errflag = cflag = vflag = FALSE;
- badcount = 0;
- while ((ch = getopt(argc, argv, "cv")) != EOF)
- switch (ch) {
- case 'c':
- /* don't create files */
- cflag = TRUE;
- break;
- case 'v':
- /* verbose -- report activity */
- vflag = TRUE;
- break;
- case '?':
- errflag = TRUE;
- break;
- }
- argc -= optind;
- argv += optind;
-
- /* check for errors including no file names */
- if (errflag == TRUE || argc <= 0) {
- usage(pgm);
- exit(ERR);
- }
-
- /* update modification times of files */
- for (; argc-- > 0; ++argv) {
- if (stat(*argv, &statbuf) == -1) {
- /* file doesn't exist */
- if (cflag == TRUE) {
- /* don't create it */
- ++badcount;
- continue;
- }
- else if ((fp = fopen(*argv, "w")) == NULL) {
- fprintf(stderr, "%s: Cannot create %s\n",
- pgm, *argv);
- ++badcount;
- continue;
- }
- else {
- if (fclose(fp) == EOF) {
- perror("Error closing file");
- exit(ERR);
- }
- if (stat(*argv, &statbuf) == -1) {
- fprintf(stderr, "%s: Cannot stat %s\n
- ++badcount;
- continue;
- }
- }
- }
- if (utime(*argv, NULL) == -1) {
- ++badcount;
- perror("Error updating date/time stamp");
- continue;
- }
- if (vflag == TRUE)
- fprintf(stderr, "Touched file %s\n", *argv);
- }
-
- exit(badcount);
- } /* end main() */
-
- /*
- * usage -- display an informative usage message
- */
-
- static void
- usage(pname)
- char *pname;
- {
- fprintf(stderr, "Usage: %s [-cv] file ...\n", pname);
- fprintf(stderr, "\t-c Do not create any files\n");
- fprintf(stderr, "\t-v Verbose mode -- report activities\n");
- } /* end usage() */
-
- /*
- * dummy functions to show how to save a little space
- */
-
- _setenvp()
- {
- }
-
- #ifndef DEBUG
- _nullcheck()
- {
- }
- #endif
-
-
- TSTREPLY.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\06USER\TSTREPLY.C
-
- /*
- * tstreply -- test the getreply function
- */
-
- #include <stdio.h>
- #include <string.h>
- #include <local\std.h>
- #include <local\video.h>
- #include "linebuf.h"
-
- #define INPUT_ROW 0
- #define INPUT_COL 40
- #define WIDTH 40
-
- int Apage = 0;
- BOOLEAN Silent = FALSE;
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- unsigned int r, c, ch, attr, revattr;
- char reply[MAXPATH + 1];
- LINEBUF buf;
-
- extern char *getreply(short, short, short,
- char *, LINEBUF *, short, short, short);
-
- /* process command line */
- if (argc == 2 && strcmp(argv[1], "-s") == 0)
- Silent = TRUE;
- else if (argc > 2) {
- fprintf(stderr, "Usage: tstreply [-s]\n");
- exit(1);
- }
-
- /* initial setup */
- getstate();
- readca(&ch, &attr, Apage);
- revattr = ((attr << 4) | (attr >> 4)) & 0x77;
- clrscrn(attr);
- putcur(0, 0, Apage);
- writestr("TSTREPLY", Apage);
- putcur(1, 0, Apage);
- writec(HLINE, Maxcol[Vmode] - 1, Apage);
- buf.l_buf = reply;
- buf.l_next = buf.l_prev = (LINEBUF *)NULL;
-
- /* demo getreply() */
-
- if (getreply(INPUT_ROW, INPUT_COL, WIDTH, "File: ", &buf,
- MAXPATH, revattr, 0) == NULL) {
- putcur(INPUT_ROW, INPUT_COL, Apage);
- writeca(' ', attr, WIDTH, Apage);
- putcur(2, 0, Apage);
- fprintf(stderr, "input aborted\n");
- exit(1);
- }
- putcur(INPUT_ROW, INPUT_COL, Apage);
- writeca(' ', attr, WIDTH, Apage);
- putcur(2, 0, Apage);
- fprintf(stderr, "reply = %s\n", reply);
- exit(0);
- }
-
- #define MSG_ROW 24
- #define MSG_COL 0
-
- int
- errmsg(mesg)
- char *mesg;
- {
- int n;
- extern void sound(unsigned int, float);
-
- putcur(MSG_ROW, MSG_COL, Apage);
- if ((n = strlen(mesg)) > 0) {
- writestr(mesg, Apage);
- if (Silent == FALSE)
- sound(100, 0.2);
- }
- else
- writec(' ', Maxcol[Vmode] - 1 - MSG_COL, Apage);
- return (n);
- }
-
-
- TSTSEL.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\07CONFIG\TSTSEL.C
-
- /*
- * tstsel -- test driver for the "select" functions
- */
-
- #include <stdio.h>
- #include <local\std.h>
-
- #define MAXTEST 20
- #define NRANGES 10
- #define NDIGITS 5
-
- extern struct slist_st {
- long int s_min;
- long int s_max;
- } Slist[NRANGES + 1];
-
- main (argc, argv)
- int argc;
- char **argv;
- {
- int i;
- extern int mkslist(char *);
- extern int selected(unsigned int);
- static void showlist();
-
- if (argc != 2) {
- fprintf(stderr, "Usage: tstsel list\n");
- exit(1);
- }
- printf("argv[1] = %s\n", argv[1]);
- mkslist(argv[1]);
- showlist();
- for (i = 0; i < MAXTEST; ++i)
- printf("%2d -> %s\n", i, selected(i) ? "YES" : "NO");
- exit(0);
- }
-
- /*
- * showlist -- display the contents of the select list
- */
-
- static void
- showlist()
- {
- int i;
-
- /* scan the selection list and display values */
- for (i = 0; i <= NRANGES; ++i)
- printf("%2d %5ld %5ld\n", i, Slist[i].s_min, Slist[i].s_max);
- }
-
-
- USERATTR.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\13ANSI\USERATTR.C
-
- /*
- * userattr -- set video attributes to user-specified values
- * (DOS environment parameters) or to reasonable defaults and
- * return success or a failure indication for bad attributes
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <local\std.h>
- #include <local\ansi.h>
- #include <local\ibmcolor.h>
-
- int
- userattr(foreground, background, border)
- char *foreground, *background, *border;
- {
- register char *s;
- static int attrset(POSITION, char *);
-
- if ((s = getenv("FGND")) == NULL)
- s = foreground;
- if (attrset(FGND, s) == -1)
- return FAILURE;
-
- if ((s = getenv("BKGND")) == NULL)
- s = background;
- if (attrset(BKGND, s) == -1)
- return FAILURE;
-
- if ((s = getenv("BORDER")) == NULL)
- s = border;
- if (attrset(BDR, s) == -1)
- return FAILURE;
-
- return SUCCESS;
- }
-
- /*
- * attrset -- parse the color spec and try to set it.
- * return 0 if OK and -1 upon error (bad color number)
- */
- static int
- attrset(apos, str)
- POSITION apos;
- register char *str;
- {
- register int attr;
- extern int colornum(char *);
- extern void setattr(POSITION, int);
-
- if ((attr = colornum(strtok(str, " \t"))) == IBM_BRIGHT)
- attr |= colornum(strtok(NULL, " \t"));
- if (attr >= 0)
- setattr(apos, attr);
- else
- return (-1);
- return (0);
- }
-
-
- VER.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\DOS\VER.C
-
- /*
- * ver -- get the MS-DOS (or PC-DOS) version number
- */
-
- #include <local\doslib.h>
-
- /************************************************************
- * For MS-DOS versions prior to 2.00, the low byte (AL) of
- * the return value is zero. For versions 2.00 and beyond,
- * the low byte is the major version number and the high
- * byte (AH) is the minor version number.
- ************************************************************/
-
- int ver()
- {
- return(bdos(DOS_VERSION, 0, 0));
- }
-
-
- VF.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\14VIEW\VF.C
-
- /*
- * vf -- view a file using a full-screen window onto
- * an in-memory text file buffer
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <local\std.h>
- #include <local\video.h>
- #include "vf.h"
-
- extern int setctype(int, int);
- int Startscan, Endscan; /* cursor scan line range */
- unsigned char Attr; /* primary display attribute */
- unsigned char Revattr; /* reverse video for highlighting */
- unsigned char Usrattr; /* user's original attribute */
-
- main(argc, argv)
- int argc;
- char **argv;
- {
- int ch;
- unsigned char chr;
- BOOLEAN errflag;
- BOOLEAN numbers;
- int errcode;
- FILE *fp;
- extern char *optarg;
- extern int optind;
- static char pgm[MAXNAME + 1] = { "vf" };
-
- /* function prototypes */
- void clean();
- extern clrscrn(unsigned char);
- extern void getpname(char *, char *);
- extern void fixtabs(int);
- extern void initmsg(int, int, int, unsigned char, int);
- extern int getopt(int, char **, char *);
- extern int vf_cmd(FILE *, char *, BOOLEAN);
- extern int readca(unsigned char *, unsigned char *, unsigned int);
- extern int getctype(int *, int *, int);
-
- errcode = 0;
- fixtabs(TABWIDTH);
-
- /* get program name from DOS (version 3.00 and later) */
- if (_osmajor >= 3)
- getpname(*argv, pgm);
-
- /* be sure we have needed DOS support */
- if (_osmajor < 2) {
- fprintf(stderr, "%s requires DOS 2.00 or later\n", pgm);
- exit(1);
- }
-
- /* process optional arguments first */
- errflag = numbers = FALSE;
- while ((ch = getopt(argc, argv, "n")) != EOF)
- switch (ch) {
- case 'n':
- /* turn on line numbering */
- numbers = TRUE;
- break;
- case '?':
- /* bad option */
- errflag = TRUE;
- break;
- }
-
- /* check for command-line errors */
- argc -= optind;
- argv += optind;
- if (errflag == TRUE || argc == 0) {
- fprintf(stderr, "Usage: %s [-n] file...\n", pgm);
- exit(1);
- }
-
- /* get current video attribute and set VF attributes */
- getstate();
- readca(&chr, &Usrattr, Vpage); /* save user's attribute settin
- /*
- * These colors are modified from those presented in the
- * book so that VF will work on all monochrome and
- * color systems the same way -- change them to suit
- * your own shade of reality and operating conditions
- */
- Attr = Usrattr; /* basic text attributes */
- /* reverse video for highlighting */
- Revattr = ((Attr & 0x7) << 4) | (Attr >> 4);
- clrscrn(Attr);
-
- /* save user's cursor shape and turn cursor off */
- getctype(&Startscan, &Endscan, Vpage);
- setctype(MAXSCAN, MAXSCAN);
-
- /* set up the message line manager */
- initmsg(MSGROW, MSGCOL, Maxcol[Vmode] - MSGCOL, Attr, Vpage);
-
- /* display first screen page */
- putcur(0, 0, Vpage);
- putstr("ViewFile/1.0 H=Help Q=Quit Esc=Next", Vpage);
- putcur(1, 0, Vpage);
- writea(Revattr, Maxcol[Vmode], Vpage);
-
- for (; argc-- > 0; ++argv) {
- if ((fp = fopen(*argv, "r")) == NULL) {
- fprintf(stderr, "%s: cannot open %s -- ", pgm, *argv)
- perror("");
- ++errcode;
- continue;
- }
- if (vf_cmd(fp, *argv, numbers) != 0)
- break;
- fclose(fp);
- }
- clean();
- exit(errcode);
- }
-
-
- /*
- * clean -- restore the user's original conditions
- */
-
- void
- clean()
- {
- /* set screen to user's attribute */
- clrscrn(Usrattr);
- putcur(0, 0, Vpage);
-
- /* restore user's cursor shape */
- setctype(Startscan, Endscan);
- }
-
-
- VF_CMD.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\14VIEW\VF_CMD.C
-
- /*
- * vf_cmd -- ViewFile command processor
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- #include <local\std.h>
- #include <local\keydefs.h>
- #include <local\video.h>
- #include "vf.h"
- #include "message.h"
-
- extern unsigned char Attr;
-
- int
- vf_cmd(fp, fname, numbers)
- FILE *fp;
- char *fname;
- BOOLEAN numbers;
- {
- register int i; /* general index */
- unsigned int offset; /* horizontal scroll offset */
- unsigned int n; /* relative line number */
- int memerr; /* flag for memory allocation errors */
- char *s, lbuf[MAXLINE]; /* input line buffer and pointer */
- int k; /* key code (see keydefs.h) */
- int radix = 10; /* base for number-to-character conver
- char number[17]; /* buffer for conversions */
- int errcount = 0; /* error counter */
- DNODE *tmp; /* pointer to buffer control nodes */
- DIRECTION srchdir; /* search direction */
- char *ss; /* pointer to search string */
- static char srchstr[MAXSTR] = { "" }; /* search string buffer
- DNODE *head; /* pointer to starting node of text buffe
- DNODE *current; /* pointer to the current node (text l
- static DNODE *freelist; /* pointer to starting node of "free"
- /* initialized to 0 at runtime; retains value
-
- /* function prototypes */
- static void prtshift(int, int);
- extern DNODE *vf_mklst();
- extern DNODE *vf_alloc(int);
- extern DNODE *vf_ins(DNODE *, DNODE *);
- extern DNODE *vf_del(DNODE *, DNODE *);
- extern DNODE *search(DNODE *, DIRECTION, char *);
- extern DNODE *gotoln(DNODE *);
- extern char *getxline(char *, int, FILE *);
- extern char *getsstr(char *);
- extern int clrscrn(unsigned char);
- extern void showhelp(unsigned char);
- extern void clrmsg();
- extern void vf_dspy(DNODE *, DNODE *, int, BOOLEAN);
- extern int putstr(char *, int);
- extern int writec(char, int, int);
- extern char *nlerase(char *);
-
- /* display the file name */
- offset = 0;
- putcur(HEADROW, 0, Vpage);
- writec(' ', Maxcol[Vmode], Vpage);
- putstr("File: ", Vpage);
- putstr(fname, Vpage);
-
- /* establish the text buffer */
- memerr = 0;
- if ((head = vf_mklst()) == NULL)
- ++memerr;
- if (freelist == NULL && (freelist = vf_alloc(N_NODES)) == NULL)
- ++memerr;
- if (memerr) {
- clean();
- fprintf(stderr, "Memory allocation error\n");
- exit(1);
- }
-
- /* read the file into the buffer */
- current = head;
- n = 0;
- while ((s = getxline(lbuf, MAXLINE, fp)) != NULL) {
- /* add a node to the list */
- if ((freelist = vf_ins(current, freelist)) == NULL)
- ++memerr;
- current = current->d_next;
-
- /* save the received text in a line buffer */
- if ((current->d_line = strdup(nlerase(s))) == NULL)
- ++memerr;
- if (memerr) {
- clean();
- fprintf(stderr, "File too big to load\n");
- exit(1);
- }
- current->d_lnum = ++n;
- current->d_flags = 0;
- }
-
- /* show the file size as a count of lines */
- putstr(" (", Vpage);
- putstr(itoa(current->d_lnum, number, radix), Vpage);
- putstr(" lines)", Vpage);
- prtshift(offset, Vpage);
- current = head->d_next;
- vf_dspy(head, current, offset, numbers);
-
- /* process user commands */
- while ((k = getkey()) != K_ESC) {
- clrmsg();
- switch (k) {
- case 'b':
- case 'B':
- case K_HOME:
- current = head->d_next;
- break;
- case 'e':
- case 'E':
- case K_END:
- current = head->d_prev;
- i = NROWS - 1;
- while (i-- > 0)
- if (current->d_prev != head->d_next)
- current = current->d_prev;
- break;
- case K_PGUP:
- case 'u':
- case 'U':
- i = NROWS - OVERLAP;
- while (i-- > 0)
- if (current != head->d_next)
- current = current->d_prev;
- break;
- case K_PGDN:
- case 'd':
- case 'D':
- i = NROWS - OVERLAP;
- while (i-- > 0)
- if (current != head->d_prev)
- current = current->d_next;
- break;
- case K_UP:
- case '-':
- if (current == head->d_next)
- continue;
- current = current->d_prev;
- break;
- case K_DOWN:
- case '+':
- if (current == head->d_prev)
- continue;
- current = current->d_next;
- break;
- case K_RIGHT:
- case '>':
- case '.':
- if (offset < MAXLINE - SHIFTWIDTH)
- offset += SHIFTWIDTH;
- prtshift(offset, Vpage);
- break;
- case K_LEFT:
- case '<':
- case ',':
- if ((offset -= SHIFTWIDTH) < 0)
- offset = 0;
- prtshift(offset, Vpage);
- break;
- case K_ALTG:
- case 'g':
- case 'G':
- if ((tmp = gotoln(head)) == NULL)
- continue;
- current = tmp;
- break;
- case K_ALTH:
- case 'h':
- case 'H':
- case '?':
- showhelp(Attr);
- break;
- case K_ALTN:
- case 'n':
- case 'N':
- numbers = (numbers == TRUE) ? FALSE : TRUE;
- break;
- case K_ALTQ:
- case 'q':
- case 'Q':
- clrscrn(Attr);
- putcur(0, 0, Vpage);
- return (-1);
- case 'r':
- case 'R':
- case '\\':
- srchdir = BACKWARD;
- ss = getsstr(srchstr);
- if (ss == NULL)
- /* cancel search */
- break;
- if (strlen(ss) > 0)
- strcpy(srchstr, ss);
- if ((tmp = search(current, srchdir, srchstr)) == NULL
- continue;
- current = tmp;
- break;
- case 's':
- case 'S':
- case '/':
- srchdir = FORWARD;
- ss = getsstr(srchstr);
- if (ss == NULL)
- /* cancel search */
- break;
- if (strlen(ss) > 0)
- strcpy(srchstr, ss);
- if ((tmp = search(current, srchdir, srchstr)) == NULL
- continue;
- current = tmp;
- break;
- default:
- /* ignore all other keys */
- continue;
- }
- vf_dspy(head, current, offset, numbers);
- }
- clrmsg();
-
- /* release the allocated text buffer memory */
- while (head->d_next != head) {
- /* release text buffer */
- free(head->d_next->d_line);
-
- /* put node back on the freelist */
- freelist = vf_del(head->d_next, freelist);
- }
- /* release the list header node */
- free((char *)head);
-
- return (errcount);
- }
-
- /*
- * prtshift -- display the number of columns of horizontal shift
- */
-
- #define SHFTDSP 5
-
- static void
- prtshift(amt, pg)
- int amt, pg;
- {
- char number[17];
- int radix = 10;
-
- /* clear the shift display area */
- putcur(1, Maxcol[Vmode] - 1 - SHFTDSP, pg);
- writec(' ', SHFTDSP, pg);
-
- /* display the new shift amount, if any */
- if (amt > 0) {
- putstr(itoa(amt, number, radix), pg);
- putstr("->", pg);
- }
- }
-
-
- VF_DSPY.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\14VIEW\VF_DSPY.C
-
- /*
- * vf_dspy -- display a screen page
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- #include <local\video.h>
- #include <local\std.h>
- #include <local\bioslib.h>
- #include "vf.h"
-
- /* number field width */
- #define NFW 8
-
- void
- vf_dspy(buf, lp, os, numbers)
- DNODE *buf;
- register DNODE *lp;
- int os;
- BOOLEAN numbers;
- {
- register int i;
- int j;
- int textwidth;
- char *cp;
- char nbuf[NFW + 1];
-
- textwidth = Maxcol[Vmode];
- if (numbers == TRUE)
- textwidth -= NFW;
-
- for (i = 0; i < NROWS; ++i) {
- putcur(TOPROW + i, 0, Vpage);
- cp = lp->d_line;
- if (numbers == TRUE) {
- sprintf(nbuf, "%6u", lp->d_lnum);
- putfld(nbuf, NFW, Vpage);
- putcur(TOPROW + i, NFW, Vpage);
- }
- if (os < strlen(cp))
- putfld(cp + os, textwidth, Vpage);
- else
- writec(' ', textwidth, Vpage);
- if (lp == buf->d_prev) {
- ++i;
- break; /* no more displayable lines */
- }
- else
- lp = lp->d_next;
- }
-
- /* clear and mark any unused lines */
- for ( ; i < NROWS; ++i) {
- putcur(i + TOPROW, 0, Vpage);
- writec(' ', Maxcol[Vmode], Vpage);
- writec('~', 1, Vpage);
- }
- return;
- }
-
-
- VF_LIST.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\14VIEW\VF_LIST.C
-
- /*
- * vf_list -- linked list management functions
- */
-
- #include <stdio.h>
- #include <malloc.h>
- #include "vf.h"
-
- /*
- * vf_mklst -- create a new list by allocating a node,
- * making it point to itself, and setting its values
- * to zero (appropriately cast)
- */
-
- DNODE *
- vf_mklst()
- {
- DNODE *new;
-
- new = (DNODE *)malloc(sizeof (DNODE));
- if (new != NULL) {
- new->d_next = new;
- new->d_prev = new;
- new->d_lnum = new->d_flags = 0;
- new->d_line = (char *)NULL;
- }
- return (new);
- } /* end vf_mklst() */
-
-
- /*
- * vf_alloc -- create a pool of available nodes
- */
-
- DNODE *
- vf_alloc(n)
- int n;
- {
- register DNODE *new;
- register DNODE *tmp;
-
- /* allocate a block of n nodes */
- new = (DNODE *)malloc(n * sizeof (DNODE));
-
- /* if allocation OK, string the nodes in one direction */
- if (new != NULL) {
- for (tmp = new; 1 + tmp - new < n; tmp = tmp->d_next)
- tmp->d_next = tmp + 1;
- tmp->d_next = (DNODE *)NULL;
- }
-
- return (new); /* pointer to free list */
- } /* end vf_alloc() */
-
-
- /*
- * vf_ins -- insert a node into a list after the specified node
- */
-
- DNODE *
- vf_ins(node, avail)
- DNODE *node, *avail;
- {
- DNODE *tmp;
- DNODE *vf_alloc(int);
-
- /*
- * check freelist -- get another block of nodes
- * if the list is almost empty
- */
- if (avail->d_next == NULL)
- if ((avail->d_next = vf_alloc(N_NODES)) == NULL)
- /* not enough memory */
- return (DNODE *)NULL;
-
- /* get a node from the freelist */
- tmp = avail;
- avail = avail->d_next;
-
- /* insert the node into the list after node */
- tmp->d_prev = node;
- tmp->d_next = node->d_next;
- node->d_next->d_prev = tmp;
- node->d_next = tmp;
-
- /* point to next node in the freelist */
- return (avail);
- } /* end vf_ins() */
-
-
- /*
- * vf_del -- delete a node from a list
- */
-
- DNODE *
- vf_del(node, avail)
- DNODE *node, *avail;
- {
- /* unlink the node from the list */
- node->d_prev->d_next = node->d_next;
- node->d_next->d_prev = node->d_prev;
-
- /* return the deleted node to the freelist */
- node->d_next = avail;
- avail = node;
-
- /* point to the new freelist node */
- return (avail);
- } /* end vf_del() */
-
-
- VF_SRCH.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\14VIEW\VF_SRCH.C
-
- /*
- * vf_srch -- search functions
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <local\std.h>
- #include "vf.h"
-
- /*
- * search -- search for a literal string in the buffer
- */
-
- DNODE *
- search(buf, dir, str)
- DNODE *buf;
- DIRECTION dir;
- char *str;
- {
- int n;
- register DNODE *lp;
- register char *cp;
-
- extern void showmsg(char *);
-
- /* try to find a match -- wraps around buffer boundaries */
- n = strlen(str);
- lp = (dir == FORWARD) ? buf->d_next : buf->d_prev;
- while (lp != buf) {
- if ((cp = lp->d_line) != NULL) /* skip over header nod
- while (*cp != '\n' && *cp != '\0') {
- if (strncmp(cp, str, n) == 0)
- return (lp);
- ++cp;
- }
- lp = (dir == FORWARD) ? lp->d_next : lp->d_prev;
- }
- showmsg("Not found");
- return ((DNODE *)NULL);
- }
-
-
- /*
- * getsstr -- prompt the user for a search string
- */
-
- extern int Startscan, Endscan;
-
- char *
- getsstr(str)
- char *str;
- {
- char line[MAXSTR];
- char *resp;
-
- extern int putstr(char *, int);
- extern char *getstr(char *, int);
- extern int put_ch(char, int);
- extern void showmsg(char *);
- extern void clrmsg();
-
- static char prompt[] = { "Search for: " };
-
- /* get search string */
- showmsg(prompt);
- setctype(Startscan, Endscan); /* cursor on */
- resp = getstr(line, MAXSTR - strlen(prompt));
- setctype(MAXSCAN, MAXSCAN); /* cursor off */
- if (resp == NULL)
- return (char *)NULL;
- if (strlen(resp) == 0)
- return (str);
- showmsg(resp);
- return (resp);
- }
-
-
- VF_UTIL.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\14VIEW\VF_UTIL.C
-
- /*
- * vf_util -- utility functions for ViewFile
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <local\std.h>
- #include <local\video.h>
- #include <local\keydefs.h>
- #include "vf.h"
-
- extern int Startscan, Endscan;
-
- #define NDIGITS 6
-
- /*
- * gotoln -- jump to an absolute line number
- */
-
- DNODE *
- gotoln(buf)
- DNODE *buf;
- {
- register int ln;
- register DNODE *lp;
- char line[NDIGITS + 1];
-
- extern void showmsg(char *);
- extern char *getstr(char *, int);
-
- /* get line number from user */
- showmsg("Line number: ");
- setctype(Startscan, Endscan); /* cursor on */
- ln = atoi(getstr(line, NDIGITS + 1));
- setctype(MAXSCAN, MAXSCAN); /* cursor off */
-
- /* check boundary conditions */
- if (ln > buf->d_prev->d_lnum || ln <= 0) {
- showmsg("Line out of range");
- return ((DNODE *)NULL);
- }
-
- /* find the line */
- for (lp = buf->d_next; ln != lp->d_lnum; lp = lp->d_next)
- ;
- return (lp);
- }
-
-
- /*
- * showhelp -- display a help frame
- */
-
- #define HELPROW TOPROW + 3
- #define HELPCOL 10
- #define VBORDER 1
- #define HBORDER 2
-
- void
- showhelp(textattr)
- unsigned char textattr; /* attribute of text area */
- {
- register int i, n;
- int nlines, ncols;
- unsigned char helpattr;
- static char *help[] = {
- "PgUp (U) Scroll up the file one screen page",
- "PgDn (D) Scroll down the file one screen page",
- "Up arrow (-) Scroll up in the file one line",
- "Down arrow (+) Scroll down in the file one line",
- "Right arrow (>) Scroll right by 20 columns",
- "Left arrow (<) Scroll left by 20 columns",
- "Home (B) Go to beginning of file buffer",
- "End (E) Go to end of file buffer",
- "Alt-g (G) Go to a specified line in the buffer",
- "Alt-h (H or ?) Display this help frame",
- "Alt-n (N) Toggle line-numbering feature",
- "\\ (R) Reverse search for a literal text string",
- "/ (S) Search forward for a literal text string",
- "Esc Next file from list (quits if none)",
- "Alt-q (Q) Quit",
- "--------------------------------------------------------",
- " << Press a key to continue >>",
- (char *)NULL
- };
-
- /* prepare help window */
- ncols = 0;
- for (i = 0; help[i] != (char *)NULL; ++i)
- if ((n = strlen(help[i])) > ncols)
- ncols = n;
- nlines = i - 1;
- --ncols;
- helpattr = (RED << 4) | BWHT;
- clrw(HELPROW - VBORDER, HELPCOL - HBORDER,
- HELPROW + nlines + VBORDER, HELPCOL + ncols + HBORDER,
- helpattr);
- drawbox(HELPROW - VBORDER, HELPCOL - HBORDER,
- HELPROW + nlines + VBORDER, HELPCOL + ncols + HBORDER,
- Vpage);
-
- /* display the help text */
- for (i = 0; help[i] != (char *)NULL; ++i) {
- putcur(HELPROW + i, HELPCOL, Vpage);
- putstr(help[i], Vpage);
- }
-
- /* pause until told by a keypress to proceed */
- getkey();
-
- /* restore help display area to the text attribute */
- clrw(HELPROW - VBORDER, HELPCOL - HBORDER,
- HELPROW + nlines + VBORDER, HELPCOL + ncols + HBORDER,
- textattr);
- }
-
-
- WARN.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\UTIL\WARN.C
-
- /*
- * warn -- display a warning message in a highly
- * visible place; return number of characters written
- */
-
- #include <stdio.h>
-
- int
- warn(pname, mesg)
- char *pname, *mesg;
- {
- return (fprintf(stderr, "%s: %s\n", pname, mesg));
- }
-
-
- WRITEA.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\WRITEA.C
-
- /*
- * writea -- write attribute only to screen memory (faked by
- * reading char and attr and writing back the original
- * character and the new attribute at each position)
- */
-
- #include <local\std.h>
-
- int writea(a, n, pg)
- unsigned char a;/* video attribute */
- int n; /* number of positions to write */
- int pg; /* screen page */
- {
- int i;
- int status;
- unsigned short chx, attrx;
- unsigned short r, c;
-
- /* get starting (current) position */
- status = 0;
- status = readcur(&r, &c, pg);
- for (i = 0; i < n; ++i) {
- status += putcur(r, c + i, pg);
- status += readca(&chx, &attrx, pg);
- status += writeca(chx, a, 1, pg);
- }
-
- /* restore cursor position */
- status += putcur(r, c, pg);
-
- return (status);
- }
-
-
- WRITEC.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\WRITEC.C
-
- /*
- * writec -- write a character only
- * (leave attribute undisturbed)
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
-
- int
- writec(ch, count, pg)
- unsigned char ch; /* character */
- int count; /* repetitions */
- int pg; /* screen page for writes */
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = WRITE_CHAR;
- inregs.h.al = ch;
- inregs.h.bh = pg;
- inregs.x.cx = count;
- int86(VIDEO_IO, &inregs, &outregs);
-
- return (outregs.x.cflag);
- }
-
-
- WRITECA.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\WRITECA.C
-
- /*
- * writeca -- write character and attribute to the screen
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
-
- int
- writeca(ch, attr, count, pg)
- unsigned char ch; /* character */
- unsigned char attr; /* attribute */
- int count; /* number of repetitions */
- int pg; /* screen page for writes */
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = WRITE_CHAR_ATTR;
- inregs.h.al = ch;
- inregs.h.bh = pg;
- inregs.h.bl = attr;
- inregs.x.cx = count;
- int86(VIDEO_IO, &inregs, &outregs);
-
- return (outregs.x.cflag);
- }
-
-
- WRITEDOT.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\WRITEDOT.C
-
- /*
- * writedot -- display a dot at the specified position
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
-
- int
- writedot(r, c, color)
- int r, c; /* row and column cordinate */
- int color; /* dot (pixel) color */
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = WRITE_DOT;
- inregs.h.al = color;
- inregs.x.cx = c;
- inregs.x.dx = r;
- int86(VIDEO_IO, &inregs, &outregs);
-
- return (outregs.x.cflag);
- }
-
-
- WRITEMSG.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\WRITEMSG.C
-
- /*
- * writemsg -- displays a message in a field of the prevailing
- * video attribute and returns the number of displayable message
- * characters written; truncates the message if its too long
- * to fit in the field
- */
-
- #include <stdio.h>
- #include <local\std.h>
-
- int writemsg(r, c, w, s1, s2, pg)
- int r, c, w ;
- char *s1, *s2;
- int pg;
- {
- int n = 0;
- char *cp;
-
- /* display first part of the message */
- if (s1 != NULL)
- for (cp = s1; *cp != '\0' && n < w; ++n, ++cp) {
- putcur(r, c + n, pg);
- writec(*cp, 1, pg);
- }
-
- /* display second part of the message */
- if (s2 != NULL)
- for (cp = s2; *cp != '\0' && n < w; ++n, ++cp) {
- putcur(r, c + n, pg);
- writec(*cp, 1, pg);
- }
-
- /* pad the remainder of the field, if any, with spaces */
- if (n < w) {
- putcur(r, c + n, pg);
- writec(' ', w - n, pg);
- }
-
- return (n);
- }
-
-
- WRITESTR.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\WRITESTR.C
-
- /*
- * writestr -- write a string in
- * the prevailing video attribute
- */
-
- #include <local\std.h>
-
- int
- writestr(s, pg)
- register char *s; /* string to write */
- unsigned int pg; /* screen page for writes */
- {
- unsigned int r, c, c0;
-
- readcur(&r, &c, pg);
- for (c0 = c; *s != '\0'; ++s, ++c) {
- putcur(r, c, pg);
- writec(*s, 1, pg);
- }
-
- /* restore cursor position and return # of characters displayed */
- putcur(r, c0, pg);
- return (c - c0);
- }
-
-
- WRITETTY.C
- CD-ROM Disc Path: \SAMPCODE\PROF_C\05OSLIB\BIOS\WRITETTY.C
-
- /*
- * writetty -- write to screen using TTY interface
- */
-
- #include <dos.h>
- #include <local\std.h>
- #include <local\bioslib.h>
-
- int
- writetty(ch, attr, pg)
- unsigned char ch; /* character */
- unsigned char attr; /* video attribute */
- int pg; /* screen page for writes */
- {
- union REGS inregs, outregs;
-
- inregs.h.ah = WRITE_TTY;
- inregs.h.al = ch;
- inregs.h.bl = attr;
- inregs.h.bh = pg;
- int86(VIDEO_IO, &inregs, &outregs);
-
- return (outregs.x.cflag);
- }
- Quick-C Programming - Sample Code
-
-
- 12_10A.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\12_10A.C
-
- #include "texed.h"
- menu()
- {
- struct key_struct *kp, *Read_kbd();
- int cur_key, cur_move;
-
- kp = Read_kbd();
- cur_key = kp->key;
- cur_move = kp->move;
- if (cur_key == ERROR)
- return (cur_move);
- return (cur_key);
- }
-
-
- 12_10B.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\12_10B.C
-
- #include "texed.h"
- struct key_struct *Read_key()
- {
- struct key_struct k;
-
- k.key = getch();
- if (k.key == ERROR)
- k.move = getch();
- return (&k);
- }
-
-
- 12_8A.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\12_8A.C
-
- #define OK 1
- #define ERROR 0
- menu()
- {
- struct key_struct {
- char key;
- unsigned char move;
- } *kp, *Read_kbd();
- int cur_key, cur_move;
-
- kp = Read_kbd();
- cur_key = kp->key;
- cur_move = kp->move;
- if (cur_key == ERROR)
- return (cur_move);
- return (cur_key);
- }
-
-
- 12_8B.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\12_8B.C
-
- #define OK 1
- #define ERROR 0
- struct key_struct {
- char key;
- unsigned char move;
- };
-
- struct key_struct *Read_key()
- {
- struct key_struct k;
-
- k.key = getch();
- if (k.key == ERROR)
- k.move = getch();
- return (&k);
- }
-
-
- ACME.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP09\ACME.C
-
- /* acme.c -- illustrate an assortment of the */
- /* C library string-handling routines */
-
- <stdio.h> /* for NULL */
- <string.h> /* for strchr(), et al */
-
- #define NAME_PATTERN \
- "first<space>last or\n\
- first<space>middle<space>last"
-
- #define ADDRESS_PATTERN \
- "number<space>street<comma><space>city<comma>"
-
- char Buf[BUFSIZ]; /* global I/O buffer */
-
- main()
- {
- char *ocp, *cp, *first, *last, *street, *city;
- void Prompt(), Cant();
-
- printf("Acme Employment Questionaire\n");
-
- /*
- * Expect first<space>last or
- * first<space>middle<space>last
- */
- Prompt("Full Name");
- /* search forward for a space */
- if ((cp = strchr(Buf,' ')) == NULL)
- Cant("First Name", NAME_PATTERN);
- *cp = '\0';
- first = strdup(Buf);
- *cp = ' ';
-
- /* Search back from end for a space */
- if ((cp = strrchr(Buf,' ')) == NULL)
- Cant("Last Name", NAME_PATTERN);
- last = strdup(++cp);
-
- /*
- * Expect number<space>street<comma><space>city<comma>
- */
- Prompt("Full Address");
- /* search forward for a comma */
- if ((cp = strchr(Buf,',')) == NULL)
- Cant("Street", ADDRESS_PATTERN);
- *cp = '\0';
- street = strdup(Buf);
-
- /* Search forward from last comma for next comma */
- if ((ocp = strchr(++cp,',')) == NULL)
- Cant("City", ADDRESS_PATTERN);
- *ocp = '\0';
- city = strdup(++cp);
-
- printf("\n\nYou Entered:\n");
- printf("\tFirst Name: \"%s\"\n", first);
- printf("\tLast Name: \"%s\"\n", last);
- printf("\tStreet: \"%s\"\n", street);
- printf("\tCity: \"%s\"\n", city);
-
- }
-
- void Cant(char *what, char *pattern)
- {
- printf("\n\n\bFormat Error!!!\n");
- printf("Can't parse your %s.\n", what );
- printf("Expected an entry of the form:\n\n");
- printf("%s\n\nAborted\n", pattern);
- exit(1);
- }
-
- void Prompt(char *str)
- {
- while (1)
- {
- printf("\n%s: ", str );
- if (gets(Buf) == NULL || *Buf == '\0')
- {
- printf("Do you wish to quit? ");
- if (gets(Buf) == NULL || *Buf == 'y')
- exit (0);
- continue;
- }
- break;
- }
- }
-
-
- ALERT.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP06\ALERT.C
-
- /* alert.c -- sounds alarm by calling a */
- /* beep() function with a parameter */
-
- main()
- {
- void beep(times); /* function declaration */
- printf("*** Alert! Alert! ***\n");
- beep(3); /* call beep() with parameter */
- }
-
- void beep(times)
- int times; /* declare function parameter */
- {
- int count;
-
- /* check that parameter is between 1 and 4 */
- if ((times < 1) || (times > 4))
- {
- printf("Error in beep(): %d beeps specified.\n",
- times);
- printf("Specify one to four beeps");
- }
- else /* sound the beeps */
- for (count = 1; count <= times; count++)
- printf("\a"); /* "alert" escape sequence */
- }
-
-
- ALLCOLOR.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\ALLCOLOR.C
-
- /* allcolor.c -- shows _ERESCOLOR 64-color palette */
- /* If you load graphics.qlb, no program list is needed.*/
-
- /* Hit <g> to advance left palette, <G> to go back. */
- /* Hit <h> to advance right palette, <H> to go back. */
- /* Hit <Esc> to quit */
- #include <stdio.h>
- #include <graph.h>
- #include <conio.h>
- #define MAXCOLORS 64
- #define ESC '\033'
- long Ega_to_vga(int); /* color value conversion */
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- struct videoconfig vc;
- int mode = _ERESCOLOR;
- int xmax, ymax;
- int c1 = 1;
- int c2 = 4;
- char left[11];
- char right[11];
- int lpos, rpos;
- char ch;
-
- if (argc > 1)
- mode = atoi(argv[1]);
- if (_setvideomode(mode) == 0)
- {
- fprintf(stderr,"%d mode not supported\n", mode);
- exit(1);
- }
- _getvideoconfig(&vc);
- _setlogorg(vc.numxpixels/2, vc.numypixels/2);
-
- xmax = vc.numxpixels / 2 - 1;
- ymax = vc.numypixels / 2 - 1;
- lpos = vc.numxpixels/32 - 5;
- rpos = lpos + vc.numxpixels / 16;
- _setcolor(1);
- _rectangle(_GFILLINTERIOR, -xmax, -ymax, 0, ymax);
- _setcolor(4);
- _rectangle(_GFILLINTERIOR, 1, -ymax, xmax, ymax);
- sprintf(left,"<-G %2d g->", c1);
- sprintf(right,"<-H %2d h->", c2);
- _settextcolor(6);
- _settextposition(0, 0);
- _outtext("Press Esc to quit");
- _settextposition(24, lpos);
- _outtext(left);
- _settextposition(24, rpos);
- _outtext(right);
- while ((ch = getch()) != ESC)
- {
- switch (ch)
- {
- case 'g': c1 = (c1 + 1) % MAXCOLORS;
- _remappalette(1, Ega_to_vga(c1));
- break;
- case 'G': c1 = (c1 - 1) % MAXCOLORS;
- _remappalette(1, Ega_to_vga(c1));
- break;
- case 'h': c2 = (c2 + 1) % MAXCOLORS;
- _remappalette(4, Ega_to_vga(c2));
- break;
- case 'H': c2 = (c2 - 1) % MAXCOLORS;
- _remappalette(4, Ega_to_vga(c2));
- break;
- }
- sprintf(left,"<-G %2d ->g", c1);
- sprintf(right,"<-H %2d ->h", c2);
- _settextposition(0, 0);
- _outtext("Press Esc to quit");
- _settextposition(24, lpos);
- _outtext(left);
- _settextposition(24, rpos);
- _outtext(right);
- }
- _setvideomode(_DEFAULTMODE);
- }
- long Ega_to_vga(egacolor)
- int egacolor; /* ega color value */
- {
- static long vgavals[6] = {0x2A0000L, 0x002A00L, 0x00002AL,
- 0x150000L, 0x001500L, 0x000015L};
- long vgacolor = 0L; /* vga color value */
- int bit;
-
- for (bit = 0; bit < 6; bit++)
- vgacolor += ((egacolor >> bit) &1) * vgavals[bit];
- return (vgacolor);
- }
-
-
- ALLVGA.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\ALLVGA.C
-
- /* allvga.c -- shows _MRES256COLOR 256K colors */
- /* If you load graphics.qlb, no program list is needed.*/
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <graph.h>
- #include <conio.h>
- #define FULLBRIGHT 64
- #define ESC '\033'
- char label[2][7] = {"ACTIVE", " "};
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- struct videoconfig vc;
- int mode = _MRES256COLOR;
- int xmax, ymax;
- static long colors[2] = {_BLUE, _RED};
- char left[11];
- char right[11];
- int lpos, rpos;
- char ch;
- unsigned long blue = _BLUE >> 16;
- unsigned long green = 0L;
- unsigned long red = 0L;
- long color;
- short palnum = 0;
-
- if (argc > 1)
- mode = atoi(argv[1]);
- if (_setvideomode(mode) == 0)
- {
- fprintf(stderr,"%d mode not supported\n", mode);
- exit(1);
- }
- _getvideoconfig(&vc);
- _setlogorg(vc.numxpixels/2, vc.numypixels/2);
-
- xmax = vc.numxpixels / 2 - 1;
- ymax = vc.numypixels / 2 - 1;
- lpos = vc.numxpixels / 32 - 5;
- rpos = lpos + vc.numxpixels/16;
- _remappalette(2, _RED);
- _setcolor(1);
- _rectangle(_GFILLINTERIOR, -xmax, -ymax, 0, ymax);
- _setcolor(2);
- _rectangle(_GFILLINTERIOR, 1, -ymax, xmax, ymax);
- sprintf(left," %6lxH ", colors[0]);
- sprintf(right," %6lxH ", colors[1]);
- _settextcolor(6);
- _settextposition(1, 1);
- _outtext("Press Tab to toggle panels, Esc to quit.");
- _settextposition(2, 1);
- _outtext("B increases blue level, b decreases it. ");
- _settextposition(3, 1);
- _outtext("G and g control green, R and r red. ");
- _settextposition(24, lpos);
- _outtext(left);
- _settextposition(24, rpos);
- _outtext(right);
- _settextposition(5, 7);
- _outtext(label[0]);
- _settextposition(5, 27);
- _outtext(label[1]);
- while ((ch = getch()) != ESC)
- {
- switch (ch)
- {
- case '\t': _settextposition(5, 27);
- _outtext(label[palnum]);
- palnum ^= 1;
- blue = (colors[palnum] << 16) & 0x3F;
- green = (colors[palnum] << 8) & 0x3F;
- red = colors[palnum] & 0x3F;
- _settextposition(5, 7);
- _outtext(label[palnum]);
- break;
- case 'B': blue = (blue + 1) % FULLBRIGHT;
- colors[palnum] = blue << 16 |
- green << 8 | red;
- _remappalette(palnum + 1, colors[palnum]);
-
- break;
- case 'b': blue = (blue - 1) % FULLBRIGHT;
- colors[palnum] = blue << 16 |
- green << 8 | red;
- _remappalette(palnum + 1, colors[palnum]);
-
- break;
- case 'G': green = (green + 1) % FULLBRIGHT;
- colors[palnum] = blue << 16 |
- green << 8 | red;
- _remappalette(palnum + 1, colors[palnum]);
-
- break;
- case 'g': green = (green - 1) % FULLBRIGHT;
- colors[palnum] = blue << 16 |
- green << 8 | red;
- _remappalette(palnum + 1, colors[palnum]);
-
- break;
- case 'R': red = (red + 1) % FULLBRIGHT;
- colors[palnum] = blue << 16 |
- green << 8 | red;
- _remappalette(palnum + 1, colors[palnum]);
-
- break;
- case 'r': red = (red - 1) % FULLBRIGHT;
- colors[palnum] = blue << 16 |
- green << 8 | red;
- _remappalette(palnum + 1, colors[palnum]);
-
- break;
-
- }
- sprintf(left," %6lxH ", colors[0]);
- sprintf(right," %6lxH ", colors[1]);
- _settextposition(24, lpos);
- _outtext(left);
- _settextposition(24, rpos);
- _outtext(right);
- }
- _setvideomode(_DEFAULTMODE);
- }
-
-
- ALPHABET.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP04\ALPHABET.C
-
-
- /* ALPHABET.C -- uses for loop to */
- /* print lowercase alphabet */
-
- main()
- {
- int i;
- for (i = 'a'; i <= 'z'; i++)
- {
- printf("%c", i);
- }
- }
-
-
-
- ANIMATE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP04\ANIMATE.C
-
-
- /* ANIMATE.C -- animate a graphics character */
- /* until a key is pressed */
-
- /* Special characters */
- #define RTARROW 175
- #define LFTARROW 174
- #define BLANK 32
- #define BACKSPACE 8
-
- main()
- {
- int pos, i, j = 1;
- while ( !kbhit() )
- {
- pos = 1;
- while (pos < 79)
- {
- putch(RTARROW);
- i = 1;
- while (i < 1000)
- {
- j = i + 10;
- i++;
- }
- putch(BACKSPACE);
- putch(BLANK);
- pos++;
- }
- while (pos > 1)
- {
- putch(LFTARROW);
- i = 1;
- while (i < 1000)
- {
- j = i + 10;
- i++;
- }
- putch(BACKSPACE);
- putch(BLANK);
- putch(BACKSPACE);
- putch(BACKSPACE);
- pos--;
- }
- }
- }
-
-
-
- ARRAY1.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP07\ARRAY1.C
-
- /* array1.c -- how to declare arrays legally */
-
- #define SIZEOARRAY 26
-
- main()
- {
- char initials[26];
- int num_men[26], num_women[SIZEOARRAY];
- float ages[SIZEOARRAY * 2];
- }
-
-
- ARROW.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\ARROW.C
-
- /* arrow.c -- fill inside and outside of a line */
- /* drawing */
- /* If you load graphics.qlb, no program list is needed*/
-
- #include <stdio.h>
- #include <graph.h>
- #include <conio.h>
- #define ESC '\033'
- BKCOLS 16 /* use 16 background colors */
- long Bkcolors[BKCOLS] = {_BLACK, _BLUE, _GREEN, _CYAN,
- _RED, _MAGENTA, _BROWN, _WHITE,
- _GRAY, _LIGHTBLUE, _LIGHTGREEN,
- _LIGHTCYAN, _LIGHTRED, _LIGHTMAGENTA,
- _LIGHTYELLOW,_BRIGHTWHITE };
- char Mask[8] = {0x90, 0x68, 0x34, 0x19, 0x19, 0x34, 0x68,
- 0x90};
- char Outmask[8] = {0xff, 0x80, 0x80, 0x80, 0xff, 0x08, 0x08,
- 0x08};
- main(argc, argv)
- int argc;
- char *argv[];
- {
- struct videoconfig vc;
- int mode = _MRES4COLOR;
- float x1, y1, x2, y2, x3, y3, y4, x5, y5;
- long bk = _BLUE;
-
- if (argc > 1)
- mode = atoi(argv[1]);
- if (_setvideomode(mode) == 0)
- {
- printf("Can't set mode %d.\n", mode);
- exit(1);
- }
- _getvideoconfig(&vc);
-
- x1 = 0.1 * vc.numxpixels;
- x2 = 0.7 * vc.numxpixels;
- x3 = 0.6 * vc.numxpixels;
- x5 = 0.9 * vc.numxpixels;
- y1 = 0.45 * vc.numypixels;
- y2 = 0.55 * vc.numypixels;
- y3 = 0.3 * vc.numypixels;
- y4 = 0.7 * vc.numypixels;
- y5 = 0.5 * vc.numypixels;
- _selectpalette(0);
- _setcolor(1);
- _moveto(x1, y1);
- _lineto(x2, y1);
- _lineto(x3, y3);
- _lineto(x5, y5);
- _lineto(x3, y4);
- _lineto(x2, y2);
- _lineto(x1, y2);
- _lineto(x1, y1);
- _setcolor(2);
- _setfillmask(Mask);
- _floodfill(x2, y5, 1) ;
- _setcolor(3);
- _setfillmask(Outmask); /* restores default mask */
- _floodfill(5, 5, 1) ;
- _settextcolor(1);
- _settextposition(23, 0);
- _outtext("Press <enter> to change background.");
- _settextposition(24, 0);
- _outtext("Press <esc> to end.");
- while (getch() != ESC)
- _setbkcolor(Bkcolors[++bk % BKCOLS]);
- _setvideomode(_DEFAULTMODE);
- }
-
-
- ASGNKEY.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP13\ASGNKEY.C
-
- /* asgnkey.c -- uses ansi.sys to assign meanings */
- /* to several function keys. */
- /* Note: This requires ANSI.SYS to be installed. */
-
- #define KASSIGN(K, S) printf("\033[0;%d;\"%s\";13p", K, S)
- /* This macro assigns string S to key K */
- #define F5 63
- #define F6 64
- #define F7 65
- #define F8 66
- #define F9 67
- #define F10 68
- main()
- {
- KASSIGN(F5, "DIR *.C");
- KASSIGN(F6, "DIR *.H");
- KASSIGN(F7, "DIR *.OBJ");
- KASSIGN(F8, "DIR *.EXE");
- KASSIGN(F9, "DIR /W");
- KASSIGN(F10, "CD \\");
- }
-
-
- ASIMOV.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP07\ASIMOV.C
-
- /* asimov.c -- illustrates how to initialize an */
- /* array with starting values */
-
- #define MAXL 16
- char Letters[MAXL] = {
- 'e', 'I', 'a', 'N', 'o', 'R', 'O', 'o',
- 'u', 't', 'o', 'R', 'l', 'o', 'B', 'b',
- };
-
- main()
- {
- int num, i;
-
- printf("Guess my identity with numbers.\n");
- printf("(any non number quits)\n\n");
-
- while (scanf("%d", &num) == 1)
- {
- if (num <= 0)
- {
- printf("Guesses must be above zero\n");
- continue;
- }
- for (i = 1; i <= num; ++i)
- {
- printf("%c", Letters[(i * num) % MAXL]);
- }
- printf("\n");
- }
- }
-
-
- ATTRIB.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\ATTRIB.C
-
- /* attrib.c -- this program illustrates attributes */
- /* program list: attrib.c, scrfun.c */
- /* user include files: scrn.h */
- /* Note: activate Screen Swapping On in Debug menu */
- #include <stdio.h>
- #include <conio.h>
- #include "scrn.h"
- #define PAGE 0
- #define ESC '\033'
- char *Format = "This message is displayed using an "
- "attribute value of %2X hex (%s).";
- int Get_attrib(char *);
- void Print_attr(char *, unsigned char, unsigned char);
-
- main()
- {
-
- int attribute; /* value of attribute */
- char attr_str[9]; /* attr. in string form */
- char mesg[80];
-
- Clearscr();
- Home();
- printf("Enter an attribute as an 8-digit binary "
- "number, such as 00000111, and see a\n"
- "message displayed using that attribute."
- "Hit <Esc> to quit.\n"
- "Attribute = ");
- while ((attribute = Get_attrib(attr_str)) != -1)
- {
- Setcurs(10,0,PAGE);
- sprintf(mesg, Format, attribute, attr_str);
- Print_attr(mesg, attribute, PAGE);
- Setcurs(2, 12, PAGE);
- printf(" "); /* clear old display */
- Setcurs(2, 12, PAGE);
- }
- Clearscr();
- }
-
- /* The following function reads in a binary number */
- /* as a sequence of 1s and 0s. It places the 1 and 0 */
- /* characters in a string whose address is passed as */
- /* an argument. It returns the numeric value of the */
- /* binary number. Bad input is summarily rejected. */
- /* The function returns -1 when you press Esc. */
-
- int Get_attrib(a_str)
- char a_str[]; /* attribute as binary string */
- {
- int attrib[8];
- int index = 7;
- int ch;
- int attribute = 0; /* attrib. as numeric value */
- int pow;
-
- a_str[8] = '\0'; /* terminate string */
- while ((index >= 0) && (ch = getch()) != ESC)
- {
- if (ch != '0' && ch != '1') /* bad input */
- putch('\a');
- else
- {
- putch(ch);
- a_str[index] = ch; /* string form */
- attrib[index--] = ch - '0'; /* numeric */
- }
- }
- if (ch == ESC)
- return (-1);
- else /* convert numeric array to a number */
- {
- for(index = 0, pow = 1; index < 8;
- index++, pow *= 2)
- attribute += attrib[index] * pow;
- return attribute;
- }
- }
-
- /* The following function prints the string str using */
- /* attribute attr on the indicated page. */
- /* It uses functions from the scrfun.c file. */
-
- void Print_attr(str, attr, page)
- char *str;
- unsigned char attr, page;
- {
- while (*str != '\0')
- {
- Write_ch_atr(*str++, attr , page, 1);
- Cursrt();
- }
- }
-
-
- AVGTEMP.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\AVGTEMP.C
-
- /* avgtemp.c -- finds average temperature */
- /* for the week */
-
- main()
- {
- int t1, t2, t3, t4, t5, t6, t7;
- float avg;
-
- printf("Enter the high temperature for:\n");
- printf("Monday: ");
- scanf("%d", &t1);
- printf("Tuesday: ");
- scanf("%d", &t2);
- printf("Wednesday: ");
- scanf("%d", &t3);
- printf("Thursday: ");
- scanf("%d", &t4);
- printf("Friday: ");
- scanf("%d", &t5);
- printf("Saturday: ");
- scanf("%d", &t6);
- printf("Sunday: ");
- scanf("%d", &t7);
-
- /* calculate and display average */
- avg = (t1 + t2 + t3 + t4 + t5 + t6 + t7) / 7.0;
- /* divide by 7.0 to ensure float result */
- printf("The average high temperature for");
- printf(" this week was %5.2f degrees.\n", avg);
- }
-
-
- BACKWARD.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\BACKWARD.C
-
- /* backward.c -- the backwards word displayer */
-
- #include <stdio.h>
- #define SIZE 5
- char word[SIZE] = "trap";
- main()
- {
- unsigned int index;
-
- printf("%s backwards is ", word);
- for (index = SIZE - 2; index >= 0; index--)
- putchar(word[index]);
- putchar('\n');
- }
-
-
-
- BADPUTC.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\BADPUTC.C
-
- /* badputc.c -- misusing putc() */
-
- #include <stdio.h>
- main()
- {
- FILE *fp;
- int ch;
-
- if ((fp = fopen("junk", "w")) == NULL)
- exit(1);
-
- while ((ch = getchar()) != EOF)
- putc(fp, ch);
- fclose(fp);
- }
-
-
-
- BADREF.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\BADREF.C
-
- /* badref.c -- misusing a pointer */
- main()
- {
- char name[81];
- char *pt_ch;
-
- printf("Enter your first name: -> ");
- scanf("%s", name);
- *pt_ch = name[1];
- printf("The second letter of your name is %c\n",
- *pt_ch );
- }
-
-
-
- BADSIGN.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\BADSIGN.C
-
- /* badsign.c -- uncaught typo */
-
- main()
- {
- int i;
- int j = 1;
-
- for (i = 0; i < 10; i++)
- {
- j =+ 10; /* transposed += */
- printf("%4d ", j);
- }
- printf("\n");
- }
-
-
-
- BIFFRED.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP09\BIFFRED.C
-
- /* biffred.c -- strings in the string pool can be */
- /* manipulated via pointers */
-
- char Start[] = "start";
-
- main()
- {
- char *cp;
- int pass;
-
- for (pass = 0; pass < 2; ++pass)
- {
- printf("My name is FRED\n");
-
- cp = Start;
-
- while (*cp != 'F')
- ++cp;
-
- *cp = 'B';
- *++cp = 'I';
- *++cp = 'F';
- *++cp = 'F';
- }
- }
-
-
- BITOUT.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\BITOUT.C
-
- /* bitout.c -- compiles one way on an IBM-PC and */
- /* another on a 68000 chip-based machine */
-
- CHIP_80286 /* don't define on a 68000 machine */
- #include <stdio.h>
-
- main()
- {
- int num;
-
- printf("Enter an integer number and I will print"
- " it out in binary\nNumber: ");
-
- if (scanf("%d", &num) != 1)
- {
- fprintf(stderr, "Not an integer\n");
- exit(1);
- }
- Bitout(num);
- }
-
- Bitout(unsigned int num)
- {
- int i, j;
- unsigned char *cp;
-
- cp = (char *)#
-
- defined(CHIP_80286) /* IBM-PC */
- for (i = 1; i >= 0; --i)
- #endif
- !defined(CHIP_80286) /* otherwise 68000 machine */
- for (i = 0; i < 4; ++i)
- #endif
- {
- for (j = 7; j >= 0; --j)
- putchar((cp[i] & (1 << j)) ? '1' : '0');
- }
- putchar('\n');
- }
-
-
- BITWISE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP07\BITWISE.C
-
- /* bitwise.c -- demonstrate the bitwise operators */
-
- #include <stdio.h>
-
- main()
- {
- unsigned int val1, val2, result;
- int ch;
- extern void show();
-
- while(1)
- {
- printf("\nval1: ");
- if (scanf("%d", &val1) != 1)
- break;
-
- printf("val2: ");
- if (scanf("%d", &val2) != 1)
- break;
-
- printf("\tval1 = ");
- show(val1);
- printf("\tval2 = ");
- show(val2);
-
- printf("Bitwise Operator: ");
- while ((ch = getchar()) == '\n')
- {
- continue;
- }
- if (ch == EOF)
- break;
- switch (ch)
- {
- case '&':
- result = val1 & val2;
- printf("Executing: result = val1 & val2;\n");
- break;
- case '|':
- result = val1 |= val2;
- printf("Executing: result = val1 | val2;\n");
- break;
- case '^':
- result = val1 ^= val2;
- printf("Executing: result = val1 ^ val2;\n");
- break;
- case '~':
- result = ~val1;
- printf("Executing: result = ~val1;\n");
- printf("\tresult = ");
- show(result);
- result = ~val2;
- printf("Executing: result = ~val2;\n");
- break;
- case '<':
- result = val1 <<= val2;
- printf("Executing: result = val1 <<val2;\n");
- break;
- case '>':
- result = val1 >>= val2;
- printf("Executing: result = val1 >>val2;\n");
- break;
- case 'q':
- case 'Q':
- return(0);
- default:
- continue;
- }
- printf("\tresult = ");
- show(result);
- }
- }
-
- void bitout(unsigned char num[])
- {
- int bytes = 2, i, j;
-
- /* IBM PC stores ints low/hi. */
- for (i = bytes-1; i >= 0; --i)
- {
- for (j = 7; j >= 0; --j)
- {
- putchar((num[i]&(1<<j))?'1':'0');
- }
- }
- }
-
- void show(unsigned int val)
- {
- extern void bitout();
-
- printf("(%05u decimal)", val);
- bitout(&val);
- printf(" binary\n");
- }
-
-
- BLANK.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\BLANK.C
-
- /* blank.c -- blanks MDA screen */
- /* program list -- blank.c (outp() not in core lib) */
-
- #include <conio.h>
- CONTROLREG 0x3B8 /* control register MDA */
- #define DEFAULTSET 0x29
- #define VIDEOOFF 0x21
- main()
- {
- outp(CONTROLREG, VIDEOOFF);
- getch();
- outp(CONTROLREG, DEFAULTSET);
- }
-
-
- BOX.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP07\BOX.C
-
- /* box.c -- demonstrate the result of initializing */
- /* a three-dimensional array */
-
- main()
- {
- static int cube[3][3][3] = {
- 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 };
- int plane;
- extern void Draw_plane();
-
- for (plane = 0; plane < 3; ++plane)
- {
- Draw_plane(cube, plane);
- }
- }
-
- void Draw_plane(int box[3][3][3], int slice)
- {
- int row, col;
-
- printf("Plane[%d] =\n", slice);
- for (row = 0; row < 3; ++row)
- {
- for (col = 0; col < 3; ++col)
- {
- printf( "%2d ", box[slice][row][col]);
- }
- printf("\n");
- }
- printf("\n");
- }
-
-
- BREAK.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP05\BREAK.C
-
- /* break.c -- shows how to get out of loop with BREAK */
-
- #include <stdio.h>
- #define TRUE 1
-
- main()
- {
- int number;
- while (TRUE) /* endless loop */
- {
- /* get a random number between 0 and 32767 */
- number = rand();
- printf("%d\n", number);
-
- /* break out of loop if random number */
- /* is greater than 32000 */
- if (number > 32000)
- break; /* exit WHILE loop */
- }
- printf("Broken out of WHILE loop.\n");
- }
-
-
- BUBSORT.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP07\BUBSORT.C
-
- /* bubsort.c -- passing an array to a function */
- /* affects the original array */
-
- #define NUMINTS 6
-
- extern void Bub_sort();
- extern void Triple();
-
- main()
- {
- int num = 2, i;
- static int list[NUMINTS] = { 6, 5, 4, 3, 2, 1 };
-
- printf("num before Triple = %d\n", num);
- Triple(num);
- printf("num after Triple = %d\n", num);
- printf("list[0] before Triple = %d\n", list[0]);
- Triple(list[0]);
- printf("list[0] after Triple = %d\n", list[0]);
-
- printf("Before sorting -> ");
- for (i = 0; i < NUMINTS; ++i)
- {
- printf("%d ", list[i]);
- }
- printf("\n");
-
- Bub_sort(list);
- printf("After sorting -> ");
- for (i = 0; i < NUMINTS; ++i)
- {
- printf("%d ", list[i]);
- }
- printf("\n");
-
- }
-
- void Triple(int x) /* function doesn't affect original */
- {
- x *= 3;
- }
-
- void Bub_sort(int vals[NUMINTS]) /* function changes original */
- {
- int i, j, temp;
-
- for (i = (NUMINTS - 1); i > 0; --i)
- {
- for (j = 0; j < i; ++j)
- {
- if (vals[j] > vals[j+1])
- {
- temp = vals[j];
- vals[j] = vals[j+1];
- vals[j+1] = temp;
- }
- }
- }
- }
-
-
- BUG.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\BUG.C
-
- /* bug.c -- shows how different levels of debugging */
- /* output can be produced using #if */
-
- DEBUG_LEVEL 2 /* 0 = none, 1-2 for debug */
- #include <stdio.h>
-
- main()
- {
- int ret;
-
- #if (DEBUG_LEVEL == 2)
- fprintf(stderr, "Entering main()\n");
- #endif
-
- #if (DEBUG_LEVEL == 1)
- fprintf(stderr, "Calling sub()\n");
- #endif
-
- ret = sub();
-
- #if (DEBUG_LEVEL == 1)
- fprintf(stderr, "sub() returned %d\n", ret);
- #endif
-
- #if (DEBUG_LEVEL == 2)
- fprintf(stderr, "Leaving main()\n");
- #endif
-
- }
-
- sub()
- {
- return (5);
- }
-
-
- CARD.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP11\CARD.C
-
- /* card.c -- demonstrates how to declare structures */
- /* and how to use structure members */
-
- <stdio.h> /* for NULL and stdin */
- <string.h> /* for strdup() */
-
- #define MAXN 79
-
- struct cardstruct { /* global pattern */
- char *first, *last, *middle;
- long street_num;
- char *street, *city, *state;
- long zip;
- int area_code;
- long phone;
- };
-
- main()
- {
- char *Str_Input();
- long Lint_Input();
- struct cardstruct card1;
-
- card1.first = Str_Input("First Name");
- card1.last = Str_Input("Last Name");
- card1.middle = Str_Input("Middle Name");
- card1.street_num = Lint_Input("Street Number");
- card1.street = Str_Input("Street Name");
- card1.city = Str_Input("City");
- card1.state = Str_Input("State");
- card1.zip = Lint_Input("Zip Code");
- card1.area_code = (int)Lint_Input("Area Code");
- card1.phone = Lint_Input("Phone Number");
-
- printf("\n\n");
- printf("%s %s %s\n", card1.first, card1.middle,
- card1.last);
- printf("%ld %s, %s, %s %ld\n", card1.street_num,
- card1.street, card1.city, card1.state,
- card1.zip);
- printf("(%d) %ld\n", card1.area_code, card1.phone);
-
- return (0);
- }
-
- char *Str_Input(char *prompt)
- {
- char buf[MAXN+1], *ptr;
-
- printf("%s: ", prompt);
- if (fgets(buf, MAXN, stdin) == NULL)
- exit(0);
- buf[strlen(buf) - 1] = '\0'; /* strip '\n' */
- if (strlen(buf) == 0)
- exit(0);
- if ((ptr = strdup(buf)) == NULL)
- exit(0);
- return (ptr);
- }
-
- long Lint_Input(char *prompt)
- {
- char buf[MAXN + 1];
- long num;
-
- printf("%s: ", prompt);
- if (fgets(buf, MAXN, stdin) == NULL)
- exit(0);
- if (sscanf(buf, "%ld", &num) != 1)
- exit(0);
- return (num);
- }
-
-
- CARD2.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP11\CARD2.C
-
- /* card2.c -- demonstrates structure assignment and */
- /* how to pass a structure to a function */
-
- <stdio.h> /* for NULL and stdin */
- <string.h> /* for strdup() */
-
- #define MAXN 79
-
- struct cardstruct { /* global pattern */
- char *first, *last, *middle;
- long street_num;
- char *street, *city, *state;
- long zip;
- int area_code;
- long phone;
- };
-
- main()
- {
- int i;
- char *Str_Input();
- long Lint_Input();
- struct cardstruct card1, card2;
-
- for (i = 0; i < 2; i++) /* do twice */
- {
- printf("\nCard %d:\n\n", i + 1);
-
- card1.first = Str_Input("First Name");
- card1.last = Str_Input("Last Name");
- card1.middle = Str_Input("Middle Name");
- card1.street_num = Lint_Input("Street Number");
- card1.street = Str_Input("Street Name");
- card1.city = Str_Input("City");
- card1.state = Str_Input("State");
- card1.zip = Lint_Input("Zip Code");
- card1.area_code = (int)Lint_Input("Area Code");
- card1.phone = Lint_Input("Phone Number");
-
- if (i == 0)
- card2 = card1; /* structure assignment */
- }
- Showcard(card2);
- Showcard(card1);
-
- }
-
- Showcard(struct cardstruct card)
- {
- printf("\n\n");
-
- printf("%s %s %s\n", card.first, card.middle,
- card.last);
- printf("%ld %s, %s, %s %ld\n", card.street_num,
- card.street, card.city, card.state,
- card.zip);
- printf("(%d) %ld\n", card.area_code, card.phone);
- }
-
- char *Str_Input(char *prompt)
- {
- char buf[MAXN + 1], *ptr;
-
- printf("%s: ", prompt);
- if (fgets(buf, MAXN, stdin) == NULL)
- exit(0);
- buf[strlen(buf) - 1] = '\0'; /* strip '\n' */
- if (strlen(buf) == 0)
- exit(0);
- if ((ptr = strdup(buf)) == NULL)
- exit(0);
- return (ptr);
- }
-
- long Lint_Input(char *prompt)
- {
- char buf[MAXN + 1];
- long num;
-
- printf("%s: ", prompt);
- if (fgets(buf, MAXN, stdin) == NULL)
- exit(0);
- if (sscanf(buf, "%ld", &num) != 1)
- exit(0);
- return (num);
- }
-
-
- CARD3.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP11\CARD3.C
-
- /* card3.c -- demonstrates pointers to structures */
-
- <stdio.h> /* for NULL and stdin */
- <string.h> /* for strdup() */
-
- #define MAXN 79
-
- struct cardstruct { /* global pattern */
- char *first, *last, *middle;
- long street_num;
- char *street, *city, *state;
- long zip;
- int area_code;
- long phone;
- };
-
- main()
- {
- int i;
- char *Str_Input();
- long Lint_Input();
- struct cardstruct card1, card2;
-
- for (i = 0; i < 2; i++) /* do twice */
- {
- printf("\nCard %d:\n\n", i + 1);
-
- card1.first = Str_Input("First Name");
- card1.last = Str_Input("Last Name");
- card1.middle = Str_Input("Middle Name");
- card1.street_num = Lint_Input("Street Number");
- card1.street = Str_Input("Street Name");
- card1.city = Str_Input("City");
- card1.state = Str_Input("State");
- card1.zip = Lint_Input("Zip Code");
- card1.area_code = (int)Lint_Input("Area Code");
- card1.phone = Lint_Input("Phone Number");
-
- if (i == 0)
- card2 = card1;
- }
- Showcard(&card2); /* pass addresses of structures */
- Showcard(&card1);
-
- return (0);
- }
-
- Showcard(cardptr)
- struct cardstruct *cardptr; /* pointer receives an address */
- {
- printf("\n\n");
-
- printf("%s %s %s\n", cardptr->first, cardptr->middle,
- cardptr->last);
- printf("%ld %s, %s, %s %ld\n", cardptr->street_num,
- cardptr->street, cardptr->city, cardptr->state,
- cardptr->zip);
- printf("(%d) %ld\n", cardptr->area_code, cardptr->phone);
- }
-
- char *Str_Input(char *prompt)
- {
- char buf[MAXN + 1], *ptr;
-
- printf("%s: ", prompt);
- if (fgets(buf, MAXN, stdin) == NULL)
- exit(0);
- buf[strlen(buf) - 1] = '\0'; /* strip '\n' */
- if (strlen(buf) == 0)
- exit(0);
- if ((ptr = strdup(buf)) == NULL)
- exit(0);
- return (ptr);
- }
-
- long Lint_Input(char *prompt)
- {
- char buf[MAXN + 1];
- long num;
-
- printf("%s: ", prompt);
- if (fgets(buf, MAXN, stdin) == NULL)
- exit(0);
- if (sscanf(buf, "%ld", &num) != 1)
- exit(0);
- return (num);
- }
-
-
- CCOPY.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP10\CCOPY.C
-
- /* ccopy.c -- Copies a file, cutting blank lines and */
- /* leading space from lines of copy */
-
- <stdio.h> /* for FILE, BUFSIZ, NULL */
- <ctype.h> /* for iswhite() */
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- FILE *fp_in, *fp_out;
- char buf[BUFSIZ];
- char *cp;
-
- if (argc != 3)
- {
- printf("usage: ccopy infile outfile\n");
- exit(1);
- }
- if ((fp_in = fopen(argv[1], "r")) == NULL)
- {
- printf("Can't open %s for reading.\n", argv[1]);
- exit(1);
- }
- if ((fp_out = fopen(argv[2], "w")) == NULL)
- {
- printf("Can't open %s for writing.\n", argv[2]);
- exit(1);
- }
-
- printf("Copying and Crushing: %s->%s ...",
- argv[1], argv[2]);
-
- while (fgets(buf, BUFSIZ, fp_in) != NULL)
- {
- cp = buf;
- if (*cp == '\n') /* blank line */
- continue;
- while (isspace(*cp))
- {
- ++cp;
- }
- if (*cp == '\0') /* empty line */
- continue;
- if (fputs(cp, fp_out) == EOF)
- {
- printf("\nError writing %s.\n", argv[2]);
- exit(1);
- }
- }
- printf("Done\n");
- }
-
-
- CCOPY2.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP10\CCOPY2.C
-
- /* ccopy2.c -- copies a file, cutting blank lines and */
- /* leading space from lines of copy */
-
- /* Modified to demonstrate stdout and stderr */
-
- <stdio.h> /* for FILE, BUFSIZ, NULL */
- <ctype.h> /* for iswhite() */
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- FILE *fp_in, *fp_out;
- char buf[BUFSIZ];
- char *cp;
-
- if (argc < 2)
- {
- fprintf(stderr, "usage: ccopy infile {outfile}\n");
- exit(1);
- }
- if ((fp_in = fopen(argv[1], "r")) == NULL)
- {
- fprintf(stderr, "\"%s\": Can't open.\n", argv[1]);
- exit(1);
- }
- if (argc == 3)
- {
- if ((fp_out = fopen(argv[2], "w")) == NULL)
- {
- fprintf(stderr, "\"%s\": Can't open.\n", argv[2]);
- exit(1);
- }
- }
- else
- fp_out = stdout;
-
- while (fgets(buf, BUFSIZ, fp_in) != NULL)
- {
- cp = buf;
- if (*cp == '\n') /* blank line */
- continue;
- while (isspace(*cp))
- {
- ++cp;
- }
- if (*cp == '\0') /* empty line */
- continue;
- if (fputs(cp, fp_out) == EOF)
- {
- fprintf(stderr, "Error writing.\n");
- exit(1);
- }
- }
- if (! feof(fp_in)) /* error reading? */
- {
- fprintf(stderr, "\"%s\": Error reading.\n", argv[1]);
- exit(1);
- }
- }
-
-
- CH2000.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\CH2000.C
-
- /* ch2000.c -- fill screen with 2000 characters */
- /* This program demonstrates direct memory access */
- /* of video memory. It is set up for the MDA. */
- /* Assign CGAMEM instead of MONMEM to screen for */
- /* CGA and CGA-compatible modes. */
- /* Press a key to fill; press Esc to quit. */
- /* Note: activate Screen Swapping On in Debug menu */
-
- #include <conio.h>
- #include "scrn.h"
- typedef unsigned short (far * VIDMEM);
- MONMEM ((VIDMEM) (0xB000L << 16)) /* monochrome */
- CGAMEM ((VIDMEM) (0xB800L << 16)) /* cga, ega */
- #define ESC '\033'
- #define CHARS 2000
- AMASK 0xFF /* keep attribute in range */
- main()
- {
- unsigned ch; /* character to be displayed */
- unsigned attrib = 7; /* initial attribute */
- VIDMEM screen; /* pointer to video RAM */
- int offset; /* location on screen */
-
- screen = MONMEM; /* monochrome initialization */
- while ((ch = getch()) != ESC)
- {
- for (offset = 0; offset < CHARS; offset++)
- *(screen + offset) = ((attrib++ & AMASK) << 8)
- }
- }
-
-
- CH2001.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\CH2001.C
-
- /* ch2001.c -- fill screen with 2000 characters */
- /* This program demonstrates direct memory access */
- /* of video memory. It uses the current video mode */
- /* value to select the proper video RAM address. */
- /* Press a key to fill; press Esc to quit. */
- /* Program list: ch2001.c, scrfun.lib */
- /* Note: activate Screen Swapping On in Debug menu */
-
- #include <conio.h>
- #include "scrn.h"
- typedef unsigned short (far * VIDMEM);
- MONMEM ((VIDMEM) (0xB000L << 16)) /* monochrome */
- CGAMEM ((VIDMEM) (0xB800L << 16)) /* cga, ega */
- #define ESC '\033'
- #define CHARS 2000
- #define AMASK 0xFF
- main()
- {
- unsigned ch, mode;
- unsigned attrib = 7;
- VIDMEM screen; /* pointer to video RAM */
- int offset;
-
- if ((mode = Getvmode()) == TEXTMONO)
- screen = MONMEM;
- else if (mode == TEXTC80 || mode == TEXTBW80)
- screen = CGAMEM;
- else
- exit(1);
- while ((ch = getch()) != ESC)
- {
- for (offset = 0; offset < CHARS; offset++)
- *(screen + offset) = ((attrib++ & AMASK) << 8) | ch;
- }
- }
-
-
- CHANGE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP08\CHANGE.C
-
- /* change.c -- a changemaking program demonstrates */
- /* how pointers advance the correct */
- /* number of bytes based on type */
-
- #define NCOINS (4)
- CENT (0x9b) /* IBM PC cent character */
- #define WAIT printf("(Press any key to continue)"); \
- getch(); printf("\n\n")
-
- main()
- {
- static int coins[NCOINS] = {25, 10, 5, 1};
- int *coin_ptr, i = 0;
- int pennies1, pennies2, count;
- float amount;
-
- printf("Enter an amount and I will ");
- printf(" give you change.\nAmount: ");
- if (scanf("%f", &amount) != 1)
- {
- printf("I don't know how to change that!\n");
- exit(1);
- }
- pennies2 = pennies1 = (int)(amount * 100.0);
-
- coin_ptr = coins;
- for (i = 0; i < NCOINS; ++i)
- {
- WAIT;
- count = 0;
- while ((pennies1 -= coins[i]) >= -1)
- ++count;
- if (count > 0)
- {
- printf("%4d %2d%c", count, coins[i], CENT);
- printf(" coins by array offset.\n");
- }
- if (pennies1 == 0)
- break;
- pennies1 += coins[i];
-
- count = 0;
- while ((pennies2 -= *coin_ptr) >= -1)
- ++count;
- if (count > 0)
- {
- printf("%4d %2d%c", count, *coin_ptr, CENT);
- printf(" coins by pointer indirection.\n");
- }
- if (pennies2 == 0)
- break;
- pennies2 += *coin_ptr;
- ++coin_ptr;
- }
- }
-
-
- CHANGE2.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP08\CHANGE2.C
-
- /* change2.c -- modified to demonstrate passing */
- /* an address to a function */
-
- #define NCOINS (4)
- CENT (0x9b) /* IBM PC cent character */
-
- main()
- {
- static int coins[NCOINS] = {25, 10, 5, 1};
- int pennies;
- float amount;
-
- printf("Enter an amount and I will ");
- printf(" give you change.\nAmount: ");
- if (scanf("%f", &amount) != 1)
- {
- printf("I don't know how to change that!\n");
- exit(1);
- }
- pennies = (int)(amount * 100.0);
-
- Show_change( coins, &coins[NCOINS], pennies);
-
- }
-
- Show_change( int amts[], int *end, int due)
- {
- int count;
-
- while ( amts < end ) /* compare pointers */
- {
- count = 0;
- while ((due -= *amts) >= -1)
- {
- ++count;
- }
- if (count > 0)
- printf("%4d %2d%c\n", count, *amts, CENT);
- if (due == 0)
- break;
- due += *amts;
-
- ++amts; /* increment a pointer */
- }
- }
-
-
- CHARS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\CHARS.C
-
- /* chars.c -- shows some variables of type char */
- /* as both characters and integers */
-
- main()
- {
- char ch1 = 'A', ch2 = 'a';
-
- printf("The character %c has ASCII code %d\n", ch1, ch1);
- printf("If you add ten, you get %c\n", ch1 + 10);
- printf("The character %c has ASCII code %d\n", ch2, ch2);
- }
-
-
- CHOOSE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP08\CHOOSE.C
-
- /* choose.c -- an array of pointers to functions */
- /* used to create a menu */
-
- void Choice1(), Choice2(), Choice3();
-
- void (*Dochoice[3])() = {Choice1, Choice2, Choice3};
-
- main()
- {
- int ch;
-
- printf("Select 1, 2 or 3: ");
- ch = getch(); putch(ch);
- ch -= '1';
- if (ch < 0 || ch > 2)
- printf("\nNo such choice.\n");
- else
- Dochoice[ch]();
-
- }
-
- void Choice1(void)
- {
- printf("\nThis is choice 1\n");
- }
-
- void Choice2(void)
- {
- printf("\nThis is choice 2\n");
- }
-
- void Choice3(void)
- {
- printf("\nThis is choice 3\n");
- }
-
-
- COL256.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\COL256.C
-
- /* col256.c -- show 256 colors in mode 19 */
- /* If you load graphics.qlb, no program list is needed. */
-
- #include <stdio.h>
- #include <graph.h>
- #include <conio.h>
- #define ESC '\033'
- #define ROWS 16
- #define COLS 16
- main()
- {
- struct videoconfig vc;
- int mode = _MRES256COLOR;
- short xmax, ymax; /* screen size */
- short xcs[ROWS][COLS]; /* coordinates of the */
- short ycs[ROWS][COLS]; /* 256 rectangles */
- short row, col;
-
-
- if (_setvideomode(mode) == 0)
- {
- fprintf(stderr, "%d mode not supported\n", mode);
- exit(1);
- }
- _getvideoconfig(&vc);
-
- xmax = vc.numxpixels - 1;
- ymax = vc.numypixels - 1;
-
- /* Compute an interior point for each rectangle. */
- for (col = 0; col < COLS; col++)
- for (row = 0; row < ROWS; row++)
- {
- xcs[row][col] = col * xmax / COLS + 5;
- ycs[row][col] = row * ymax / ROWS + 5;
-
- }
-
- /* draw outside boundary */
- _setcolor(1);
- _rectangle(_GBORDER, 0, 0, xmax, ymax);
-
- /* draw gridwork */
- for (col = 1; col < COLS ; col++)
- {
- _moveto(col * (xmax + 1) / COLS, 0);
- _lineto(col * (xmax + 1) / COLS, ymax);
- }
- for (row = 1; row < ROWS; row++)
- {
- _moveto(0, row * (ymax + 1) / ROWS);
- _lineto(xmax, row * (ymax + 1) / ROWS);
- }
-
- /* fill in rectangles with palette colors */
- for (col = 0; col < COLS; col++)
- for (row = 0; row < ROWS; row++)
- {
- _setcolor(row * ROWS + col);
- _floodfill(xcs[row][col], ycs[row][col],1);
- }
-
- /* terminate program */
- getch();
- _setvideomode(_DEFAULTMODE);
- }
-
-
- CONDITN.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\CONDITN.C
-
- /* conditn.c -- attempt to use conditional op */
-
- main()
- {
- int n, m;
-
- n = 2;
- m = (n != 2) : 0 ? 1; /* almost right */
- printf("%d\n", m);
- }
-
-
- CONTINUE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP05\CONTINUE.C
-
- /* continue.c -- shows CONTINUE in loop */
-
- main()
- {
- int sw = 0;
- char ch;
- while (1) /* endless loop */
- {
- /* print current status */
- if (sw)
- printf("\nSwitch is ON\n");
- else
- printf("\nSwitch is OFF\n");
-
- printf("Do you want to quit? ");
- if (ch = getche() == 'y')
- break; /* exit loop on yes */
-
- printf("\nDo you want to toggle the switch? ");
- if (ch = getche() != 'y')
- continue; /* restart loop on yes */
-
- sw = !sw; /* toggle switch */
- }
- }
-
-
- CONTROL.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP09\CONTROL.C
-
- /* control.c -- demonstrate string justification */
- /* using printf() */
-
- char Some_text[] = "Some Text";
- char Left_control[] = "<<%-15s>>";
- char Right_control[] = "<<%15s>>";
-
- main()
- {
- char ch;
-
- while (1)
- {
- printf("Select l)eft r)ight or q)uit: ");
- ch = getch();
- putch( ch );
-
- printf("\n\n");
- switch((int) ch)
- {
- case 'l':
- case 'L':
- printf(Left_control, Some_text);
- break;
- case 'r':
- case 'R':
- printf(Right_control, Some_text);
- break;
- case 'q':
- case 'Q':
- exit (0);
- default:
- printf("Huh?");
- break;
- }
- printf("\n\n");
- }
- }
-
-
- CONVERT.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\CONVERT.C
-
- /* convert.c -- converts Farenheit temprature */
- /* to Centigrade; gets value from user */
-
- main()
- {
- float ftemp, ctemp;
-
- printf("What is the temprature in Farenheit? ");
- scanf("%f", &ftemp);
- ctemp = (ftemp - 32.0) * 5 / 9.0;
-
- printf("The temprature in Centigrade is %5.2f", ctemp);
- }
-
-
- DBLBAR.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP06\DBLBAR.C
-
- /* dblbar.c -- prints header using */
- /* line() function */
-
- #define DOUBLE_BAR 205
-
- main()
- {
- void line(); /* declare line() function */
-
- line(10); /* call line() function */
- printf("dblbar.c -- prints header using\n");
- printf("line() function\n");
- line(50); /* call line() again */
- }
-
- void line() /* function definition */
- {
- int pos;
- for (pos = 1; pos <= 40; pos++)
- putch(DOUBLE_BAR);
- printf("\n");
- }
-
-
- DEBUG.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP04\DEBUG.C
-
-
- /* DEBUG.C -- for practice with debugger */
-
- main()
- {
- char response;
- int number, max_numbers = 5, count = 0, total = 0;
- float average;
-
- printf("Continue (y/n)? ");
- response = getche();
- while ((response != 'n') && (count < max_numbers))
- printf("\nEnter a number: ");
- scanf("%d", &number);
- total += number;
- printf("Continue (y/n)? ");
- response = getche();
- average = total / count;
- printf("\nTotal is %d\n", total);
- printf("Average is %f\n", average);
- }
-
-
-
- DIALOG.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP09\DIALOG.C
-
- /* dialog.c -- a conversation using gets() and puts() */
-
- <stdio.h> /* for NULL and BUFSIZ */
-
- #define THE_QUESTION \
- "And what is your view on the current price of corn\n\
- and the stability of our trade import balance?"
-
- main()
- {
- char name[BUFSIZ],
- buf[BUFSIZ];
- extern char *gets();
-
- name[0] = '\0'; /* clear the name */
-
- puts("\n\nHi there. And what is your name?");
-
- if (gets(name) != NULL && name[0] != '\0')
- {
- printf("\nPleased to meet you, %s.\n", name);
- puts(THE_QUESTION);
-
- /*
- * force an extra <enter> before replying.
- */
- do
- {
- if (gets(buf) == NULL)
- break;
-
- } while (*buf != '\0'); /* wait for empty line */
-
- puts("Sorry. I needed to think about that.");
- printf("Nice talking to you, %s.\n", name);
- }
- else
- puts("How rude!");
-
- puts("Goodbye.");
- }
-
-
- DIGSUM.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\DIGSUM.C
-
- /* digsum.c -- sum digits in input */
- #include <stdio.h>
- main()
- {
- int ch;
- int digits = 0; /* number of digits in input */
- int others = 0; /* number of non-digits in input */
-
-
- while ((ch = getchar()) != EOF)
- if (ch <= '0' && ch >= '9')
- others++;
- else
- digits++;
- printf("digits = %d, others = %d", digits, others);
- }
-
-
- DIRX.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP10\DIRX.C
-
- /* dirx.c -- directory examples */
-
- #include <direct.h>
- #include <stdio.h>
-
- #define SUBDIR "SUBDIR"
- #define SUBSUBDIR "SUBSUB"
-
- main()
- {
- char *current_dir;
- void Err();
-
- if ((current_dir = getcwd(NULL, 0)) == NULL)
- Err("getcwd()", "Can't get current directory.");
-
- if (mkdir(SUBDIR) != 0)
- Err( SUBSUBDIR, "Can't make directory." );
-
- if (chdir(SUBDIR) != 0)
- Err( SUBDIR, "Can't cd into directory." );
-
- if (mkdir(SUBSUBDIR) != 0)
- Err( SUBSUBDIR, "Can't make directory." );
-
- if (chdir(current_dir) != 0)
- Err( SUBDIR, "Can't cd back to." );
-
- if (rmdir(SUBDIR) != 0)
- Err( SUBDIR, "Can't remove directory." );
-
- }
-
- void Err(char *what, char *msg)
- {
- fprintf(stderr, "\"%s\": %s\n", what, msg );
- exit (1);
- }
-
-
- DO.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP04\DO.C
-
-
- /* DO.C -- a simple do-while loop */
-
- main()
- {
- int i = 1;
- do
- {
- printf("%d\n", i);
- i++;
- }
- while (i < 11);
- printf("Done!\n");
- }
-
-
-
- DOTS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\DOTS.C
-
- /* dots.c -- illustrates the _setcolor(), _setpixel(), */
- /* and _selectpalette() functions from the */
- /* QuickC graphics library */
- /* If you load graphics.qlb, no program list is needed */
-
- #include <conio.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <graph.h>
- #define ESC '\033'
- BKCOLS 8 /* number of background colors */
- PALNUM 4 /* number of palettes */
- long Bkcolors[BKCOLS] = {_BLACK, _BLUE, _GREEN, _CYAN, _RED,
- _MAGENTA, _BROWN, _WHITE};
- main (argc, argv)
- int argc;
- char *argv[];
- {
- struct videoconfig vc;
- unsigned int col, row;
- short color = 0;
- int bkc_index = 1; /* blue background */
- short palette = 0; /* red, green, brown */
- int firstcol, firstrow, lastrow, lastcol;
- int mode = _MRES4COLOR;
- int ch;
-
- if (argc > 1)
- mode = atoi(argv[1]);
-
- if (_setvideomode(mode) == 0)
- {
- printf("Can't do that mode.\n");
- exit(1);
- }
- _getvideoconfig(&vc);
- firstcol = vc.numxpixels / 5;
- firstrow = vc.numypixels / 5;
- lastcol = 4 * vc.numxpixels / 5;
- lastrow = 4 * vc.numypixels / 5;
- _selectpalette(palette);
- _setbkcolor (Bkcolors[bkc_index]);
- for (col = firstcol; col <= lastcol; ++col)
- {
- _setcolor((++color / 3) % vc.numcolors);
- for (row = firstrow; row <= lastrow; ++row)
- _setpixel(col, row);
- }
- while ((ch = getch()) != ESC)
- {
- if (ch == 'p')
- _selectpalette(++palette % PALNUM);
- else if (ch == 'b')
- _setbkcolor(Bkcolors[++bkc_index % BKCOLS]);
- }
- _setvideomode(_DEFAULTMODE); /* reset orig. mode */
- }
-
-
- DOWHILE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\DOWHILE.C
-
- /* dowhile.c -- misuse of do while loop */
-
- main()
- {
- int i = 0;
-
- do while (i < 10)
- {
- printf("Happy Fourth of July!\n");
- i++;
- }
- printf("VOOOM\n");
- }
-
-
-
- DOWHILE2.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\DOWHILE2.C
-
- /* dowhile2.c -- ok use of do while loop */
-
- main()
- {
- int i = 0;
-
- do
- {
- printf("Happy Fourth of July!\n");
- i++;
- } while (i < 10) ;
- printf("VOOOM\n");
- }
-
-
- DRAWCHAR.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\DRAWCHAR.C
-
- /* drawchar.c -- drawing module for grafdraw.c */
- /* translates keystrokes to graphic characters, */
- /* manages cursor control and function keys */
-
- #include <conio.h>
- #include "keys.h"
- #include "scrn.h"
- #include "grafchar.h"
- extern unsigned char Grchr[]; /* defined in grafchar.c */
-
- void Draw_chars()
- {
- int ch, chout;
- unsigned char attrib = NORMAL;
- unsigned char draw = TRUE;
-
- chout = Grchr[0]; /* default graphics character */
- while ((ch = getch()) != ESC)
- {
- if (ch >= '0' && ch <= '_')
- chout = Grchr[ch - '0'];
- /* this maps the 0 key to the first */
- /* graphics character, etc. */
- else if (ch == SPACE)
- chout = SPACE;
- else if (ch == 0) /* process cursor keys */
- { /* and function keys */
- ch = getch();
- switch (ch)
- {
- case PU : draw = FALSE;
- break;
- case PD : draw = TRUE;
- break;
- case UP : if (draw)
- Write_ch_atr(chout, attrib,
- PAGE, 1);
- if (!Cursup())
- putch(BEEP);
- break;
- case DN : if (draw)
- Write_ch_atr(chout, attrib,
- PAGE, 1);
- if (!Cursdn_lim(BOTLINE))
- putch(BEEP);
- break;
- case LT : if (draw)
- Write_ch_atr(chout, attrib,
- PAGE, 1);
- if (!Curslt())
- putch(BEEP);
- break;
- case RT : if (draw)
- Write_ch_atr(chout, attrib,
- PAGE, 1);
- if (!Cursrt())
- putch(BEEP);
- break;
- case F1 : attrib = NORMAL; break;
- case F2 : attrib = VIDREV; break;
- case F3 : attrib ^= BLINK; break;
- case F4 : attrib ^= INTENSE; break;
- default : putch(BEEP);
- }
- }
- }
- }
-
-
- EGATOVGA.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\EGATOVGA.C
-
- /* egatovga.c -- converts ega color values to vga */
- /* color values. */
-
- long Ega_to_vga(egacolor)
- int egacolor; /* ega color value */
- {
- static long vgavals[6] = {0x2a0000L, 0x002a00L,
- 0x00002aL, 0x150000L,
- 0x001500L, 0x000015L};
- /* array holds VGA equivalents to EGA bits */
- long vgacolor = 0L; /* vga color value */
- int bit;
-
- /* convert each bit to equivalent, and sum */
- for (bit = 0; bit < 6; bit++)
- vgacolor += ((egacolor >> bit) &1) * vgavals[bit];
- return (vgacolor);
- }
-
-
- EGGS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\EGGS.C
-
- /* eggs.c -- draws colorful eggs */
- /* This program illustrates use of the video configuration */
- /* structure, the _ellipse() function, the effect of over- */
- /* lapping solid figures, and a the use of logical coordinates. */
- /* If you load graphics.qlb, no program list is needed. */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <graph.h>
- #include <conio.h>
- #define ESC '\033'
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- struct videoconfig vc;
- int mode = _MRES4COLOR;
- short xcent[3], ycent[3]; /* egg centers */
- short xsize, ysize; /* egg limits */
- int egg;
-
- if (argc > 1)
- mode = atoi(argv[1]);
- if (_setvideomode(mode) == 0)
- {
- printf("Can't open mode %d\n", mode);
- exit(1);
- }
- _getvideoconfig(&vc);
- xsize = 0.3 * vc.numxpixels;
- ysize = 0.3 * vc.numypixels;
- xcent[0] = 0.3 * vc.numxpixels;
- xcent[1] = 0.5 * vc.numxpixels;
- xcent[2] = 0.7 * vc.numxpixels;
- ycent[0] = ycent[2] = 0.4 * vc.numypixels;
- ycent[1] = 0.6 * vc.numypixels;
-
- _selectpalette(0);
- _setbkcolor(_MAGENTA);
- for (egg = 0; egg < 3; egg++)
- {
- _setlogorg(xcent[egg], ycent[egg]);
- _setcolor(egg + 1);
- _ellipse(_GFILLINTERIOR, -xsize, -ysize, xsize, ysize);
- }
- _settextposition(24, 0);
- _settextcolor(1);
- _outtext("Strike any key to terminate.");
- getch();
- _setvideomode(_DEFAULTMODE);
- }
-
-
- ERR.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\ERR.C
-
- /* err.c -- illustrates __FILE__ and __LINE__ in */
- /* tracing a small program */
-
- #define ERR printf("Tracing: \"%s\" line %d\n",\
- __FILE__, __LINE__);
- main()
- {
- ERR
- err1();
- ERR
- err2();
- ERR
- }
-
- err1()
- {
- ERR
- err2();
- }
-
- err2()
- {
- ERR
- }
-
-
- EXPO.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP06\EXPO.C
-
- /* expo.c -- uses exp() function to */
- /* calculate powers */
-
- main()
- {
- int expo(number, power);
- int number, power;
-
- printf("Enter a number: ");
- scanf("%d", &number);
- printf("Raise to what power? ");
- scanf("%d", &power);
-
- printf("Result: %d", expo(number, power));
- }
-
- int expo(number, power)
- {
- int count, value;
- int total = 1; /* store value of calculation */
- if (power < 0) /* reject negative exponents */
- {
- printf("Error in expo(): negative exponent\n");
- return(0);
- }
-
- if (power == 0) /* any number to 0 power is 1 */
- return(1);
-
- if (power == 1) /* any number to 1 power is itself */
- return(number);
-
- /* calculate for power > 1 */
- for (count = 1; count <= power; count++)
- total *= number;
- return(total);
- }
-
-
- EXTERNAL.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP06\EXTERNAL.C
-
- /* external.c -- shows an external variable */
-
- #define PI 3.14159
- int length; /* external (global) variable */
- /* declared before main () */
-
- main()
- {
- void square(), triangle(), circle();
-
- printf("What length do you want to use? ");
- scanf("%d", &length);
-
- square(); /* calculate areas */
- triangle();
- circle();
- }
-
- void square()
- {
- float area;
- area = length * length;
- printf("A square with sides of %d has an area of %f\n",
- length, area);
- }
-
- void triangle()
- {
- float area;
- area = (length * length) / 2;
- printf("A right triangle with sides of %d has an area %f\n",
- length, area);
- }
-
- void circle()
- {
- float area;
- area = (length * length * PI);
- printf("A circle with radius of %d has area of %f\n",
- length, area);
- }
-
-
- FIELDS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\FIELDS.C
-
- /* fields.c -- shows the same number with different */
- /* field widths and number of decimals */
-
- main()
- {
- float f = 123.4560;
-
- printf("%12.6f\n", f);
- printf("%8.4f\n", f);
- printf("%8.3f\n", f);
- printf("%8.2f\n", f);
- }
-
-
- FILE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\FILE.C
-
- /* file.c -- the file I/O routines for texed */
-
- Load_file()
- {
- printf("\nLoading ..... done.\n");
- }
-
- Save_file()
- {
- printf("\nSaving ...... done.\n");
- }
-
-
- FLOATS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\FLOATS.C
-
- /* floats.c -- show floating values in regular */
- /* and exponential format */
-
- main()
- {
- float f1 = 2500.125, f2 = 0.0033, f3 = -50.99;
-
- printf("%f\t %e\n\n", f1, f1);
- printf("%f\t %e\n\n", f2, f2);
- printf("%f\t %e\n", f3, f3);
- }
-
-
- FMENU.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP10\FMENU.C
-
- /* fmenu.c -- demonstrates file renaming, etc. */
-
- #include <direct.h>
- #include <stdio.h>
- #include <string.h>
-
- #define MAXPATH (80)
- char From_name[MAXPATH],
- To_name[MAXPATH];
-
- int Input(char *prompt, char buf[])
- {
- printf("%s: ", prompt);
- if (gets(buf) == NULL || *buf == '\0')
- return (0);
- return (1);
- }
- void Rename(void)
- {
- printf("->Rename/move\n");
- if (!Input("From", From_name)) return;
- if (!Input("To", To_name)) return;
- if (rename(From_name, To_name) != 0)
- perror("RENAME");
- else
- printf("Renamed: \"%s\" -> \"%s\"\n",
- From_name, To_name);
- }
- void Remove(void)
- {
- printf("->Remove\n");
- if (!Input("Remove", From_name)) return;
- if (!Input("Are You Sure", To_name)) return;
- if (*To_name != 'y' && *To_name != 'Y')
- return;
- if (remove(From_name) != 0)
- perror(From_name);
- else
- printf("Removed: \"%s\"\n", From_name);
- }
- void Maketemp(void)
- {
- printf("->Maketemp\n");
- if (!Input("In What Directory", From_name))
- return;
- (void)strcat(From_name, "\\XXXXXX");
- if (mktemp(From_name) == NULL)
- printf("Can't create a unique name.\n");
- else
- printf("Created: \"%s\"\n", From_name);
- }
- void Quit(void)
- {
- printf("->Quit\n");
- if (!Input("Are You Sure", From_name))
- return;
- if (*From_name != 'y' && *From_name != 'Y')
- return;
- exit(0);
- }
-
- main()
- {
- static void (*doit[])() = {Rename, Remove, Maketemp, Quit};
- int ch;
-
- while (1)
- {
- printf("--------------------------------------------\n");
- printf("1) Rename/move a file or rename a directory.\n");
- printf("2) Remove a file.\n");
- printf("3) Make a unique temporary file.\n");
- printf("4) Quit.\n");
- printf("--------------------------------------------\n");
- printf("Select: ");
-
- do
- {
- ch = getchar();
- } while (ch < '1' || ch > '4');
- getchar(); /* gobble trailing newline */
- printf("%c\n\n", ch);
- ch -= '1';
- doit[ch]();
- }
- }
-
-
- FORLOOP.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP04\FORLOOP.C
-
-
- /* FORLOOP.C -- a simple for loop that */
- /* counts to ten */
-
- main()
- {
- int i;
- for (i = 1; i <= 10; i++)
- {
- printf("%d\n",i); /* body of loop */
- }
- printf("All done!\n");
- /* executed when i > 10 */
- }
-
-
-
- FORMATS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\FORMATS.C
-
- /* formats.c -- shows what happens when format */
- /* doesn't match data type */
-
- main()
- {
- int i = 5;
- printf("As integer: %d\n", i);
- printf("As long integer: %ld\n", i);
- printf("As exponential: %e\n", i);
- printf("As float: %f\n", i);
- }
-
-
- GALAX.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP05\GALAX.C
-
- /* GALAX.C -- creates an ellipse by selecting */
- /* from random pixels */
-
- <graph.h> /* for graphics */
- <math.h> /* for sqrt() */
- <conio.h> /* for kbhit() */
-
- main()
- {
- int pixels, radius = 50;
- double center_x = 320, center_y = 100,
- xpos, ypos;
- srand(0);
- _setvideomode(_HRESBW);
- _setcolor(1);
- for (pixels = 1; pixels < 25000; pixels++)
- {
- /* draws filled ellipse, due */
- /* to dimensions of hires screen */
- /* generate random location */
- xpos = rand() % 639;
- ypos = rand() % 199;
- if (sqrt /* is distance within radius? */
- ((xpos - center_x) * (xpos - center_x)
- + (ypos - center_y) * (ypos - center_y))
- < radius)
- _setpixel(xpos, ypos);
- if (kbhit() )
- break; /* exit if key pressed */
- }
- getch(); /* freeze screen until key pressed */
- _setvideomode(_DEFAULTMODE);
- }
-
-
- GETCH.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP13\GETCH.C
-
- /* getch.c -- using getch() */
- #include <conio.h>
- main()
- {
- int count = 1;
-
- printf("Please enter a word.\n");
- while (getch() != '\r')
- printf("%d.. ", count++);
- printf("\n%d characters altogether\n", count - 1);
- }
-
-
- GETCHAR.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP13\GETCHAR.C
-
- /* getchar.c -- using getchar() */
-
- #include <stdio.h>
- main()
- {
- int count = 1;
-
- printf("Please enter a word.\n");
- while (getchar() != '\n') /* here it is */
- printf("%d.. ", count++);
- printf("\n%d characters altogether\n", count - 1);
- }
-
-
- GETCHE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP13\GETCHE.C
-
- /* getche.c -- using getche() */
- <conio.h> /* note different file included */
- main()
- {
- int count = 1;
-
- printf("Please enter a word.\n");
- while (getche() != '\r') /* changed comparison */
- printf("%d.. ", count++);
- printf("\n%d characters altogether\n", count - 1);
- }
-
-
- GETCLOSE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP06\GETCLOSE.C
-
- /* getclose.c -- a number game using */
- /* random numbers */
-
- #define TRUE 1
- #define FALSE 0
-
- /* external variables */
- int number, /* total number in current game */
- moves, /* number of moves in current game*/
- target, /* target number to reach */
- done, /* true if game is over */
- score, /* score of current game */
- wins = 0, /* number of games won */
- losses = 0, /* number of games lost */
- total = 0; /* total score */
-
- char move;
-
- /* function prototype declarations */
- void intro(void); /* tell player about game */
- char getyn(void); /* get yes/no response */
- int random(int num); /* random between 1 and num */
- void new_target(void); /* target number for game */
- char get_move(void); /* get player's move */
- void do_move(void); /* generate num from move */
- void check_move(void); /* won, lost, or continue? */
- void show_score(void); /* show score for game */
- void show_total(void); /* show total score */
-
- main()
- {
- intro(); /* print instructions */
-
- while (TRUE) /* new games until user quits */
- {
- printf("\nDo you want to continue? ");
- if (getyn() != 'y')
- break; /* exit program */
-
- done = FALSE;
- number = moves = score = 0;
- new_target(); /* target number for this game */
- while (!done) /* play one game */
- {
- get_move();/* user selects random number */
- do_move(); /* generate random number */
- /* and add */
- check_move(); /* win, lose, or continue? */
- }
- show_score(); /* score for this game */
- show_total(); /* total score */
- }
- }
-
- void intro(void)
- {
- printf("Welcome to Getclose\n\n");
- printf("The object of this game is to\n");
- printf("try to get as close to the target\n");
- printf("number as possible in as few\n");
- printf("moves as possible by choosing from\n");
- printf("various ranges of random numbers.\n");
- printf("You score if you get within 4 of the\n");
- printf("target; a 100 point bonus for hitting\n");
- printf("the target, but no score if you go over.\n\n");
- }
-
- char getyn(void)
- /* get yes or no answer */
- /* repeats until valid entry */
- {
- char ch; /* character to read and return */
-
- while (TRUE)
- {
- printf(" (y or n) ");
- ch = getche();
- printf("\n");
- if ((ch == 'y') || (ch == 'n'))
- /* valid response, break out of loop */
- break;
- /* give error message and loop again */
- printf("please enter ");
- }
- return(ch);
- }
-
- int random(int num)
- /* generate random number between 1 and num */
- /* doesn't use library function srand() because */
- /* we don't want the same seed each time */
- {
- long seconds, result;
- time(&seconds); /* randomize with system time */
- return (abs ((int)seconds * rand() % num) + 1);
- }
-
- void new_target(void)
- /* generate a new target number */
- /* between 50 and 99 */
- {
- target = 50 + random(49);
- printf("\nYour target for this game is %d\n",
- target);
- }
-
- char get_move(void)
- {
- while (TRUE)
- {
- printf("\nPick a random number from 1 to\n");
- printf("a) 5 b) 10 c) 25 d) 50 e) 100 ");
- move = getche();
- if ((move >= 'a') && (move <= 'e'))
- {
- ++moves; /* count the move */
- break; /* valid response */
- }
- /* invalid response, try again */
- printf("\nPlease type a, b, c, d, or e\n");
- }
- }
-
- void do_move(void)
- {
- int num = 0; /* random value to obtain */
- switch (move)
- {
- case 'a' :
- num = random(5);
- break;
- case 'b' :
- num = random(10);
- break;
- case 'c' :
- num = random(25);
- break;
- case 'd' :
- num = random(50);
- break;
- case 'e' :
- num = random(100);
- break;
- }
- number += num; /* add new number to total */
- printf("\n\nYou got a %d. Number is now: %d ", num, number);
- printf("(Target is %d)\n", target);
- }
-
- void check_move(void)
- {
- int temp;
- if (number > target)
- {
- printf("\nYou went over! ");
- printf("No score this game.\n");
- losses++;
- done = TRUE; /* to break out of loop */
- }
- if (number == target)
- {
- printf("\nYou hit the target ");
- printf("for 100 bonus points!\n");
- score = (100 / moves) + 100;
- total += score;
- wins++;
- done = TRUE;
- }
- if ((number >= (target - 4)) && (number < target))
- {
- temp = 100 / moves;
- /* does player want to go for broke? */
- printf("\nTake %d points (y) or continue (n)? ",
- temp);
- if (getyn() == 'y')
- {
- score = temp;
- total += score;
- wins++;
- done = TRUE;
- }
- }
- }
-
- void show_score(void)
- {
- printf("\nYou scored %d points in %d moves.\n",
- score, moves);
- }
-
- void show_total(void)
- {
- printf("You have won %d games ", wins);
- printf("and lost %d.\n", losses);
- printf("Your total score is %d\n", total);
- }
-
-
- GETPUT.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\GETPUT.C
-
- /* getput.c -- illustrates _getimage(), _putimage(), */
- /* the image-background interaction, and */
- /* the aspect ratio */
- /* If you load graphics.qlb, no program list is needed*/
-
- #include <stdio.h>
- <stdlib.h> /* declares malloc() */
- #include <graph.h>
- #include <conio.h>
- #define ESC '\033'
-
- /* The following variables describe various */
- /* coordinates and sizes. */
- /* They are declared externally so that they can be */
- /* shared easily by several functions. */
- int X1, Yb1, X2, Y2, Xdelta, Xside, Yside; /* image */
- int Xmid, Xmax, Ymid, Ymax; /* background */
- int Xps, Xpr, Xand, Xor, Xxor, Ytop, Ybot; /* copies */
- int X[3], Y[3];
- float Ar; /* aspect ratio */
-
- struct videoconfig Vc;
- char Mask[8] = {0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0};
- void Initialize(void), Drawfig(void),
- Drawbackground(void), Drawcopies(void);
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- int mode = _MRES4COLOR;
-
- if (argc > 1)
- mode = atoi(argv[1]);
- if (_setvideomode(mode) == 0)
- {
- fprintf(stderr, "Can't handle mode %d\n", mode);
- exit(1);
- }
- Initialize();
- Drawfig();
- Drawbackground();
- Drawcopies();
- _settextposition(1, 1);
- _outtext("Press a key to end");
- _settextposition(3, 1);
- _outtext("_GPSET _GPRESET _GAND");
- _settextposition(11, 5);
- _outtext("_GOR _GXOR");
- getch();
- _setvideomode(_DEFAULTMODE);
- }
-
- void Initialize()
- {
- _getvideoconfig(&Vc);
- Ar = (float) (10 * Vc.numypixels)/
- (6.5 * Vc.numxpixels);
- _setlogorg(0, 0);
- Xmid = Vc.numxpixels / 2;
- Ymid = Vc.numypixels / 2;
- Xmax = Vc.numxpixels - 1;
- Ymax = Vc.numypixels - 1;
- /* locate three background rectangles */
- X[0] = Xmid;
- Y[0] = 0;
- X[1] = Xmid;
- Y[1] = Ymid;
- X[2] = 0;
- Y[2] = Ymid;
- X1 = 0.2 * Vc.numxpixels;
- Yb1 = 0.2 * Vc.numypixels;
- Xdelta = 0.033 * Vc.numxpixels;
- Xside = 3 * Xdelta;
- Yside = 3 * Ar * Xdelta;
- X2 = X1 + Xside;
- Y2 = Yb1 + Yside;
- /* offsets for _putimage() */
- Xps = .05 * Vc.numxpixels;
- Xpr = .20 * Vc.numxpixels;
- Xand = 0.35 * Vc.numxpixels;
- Xor = .10 * Vc.numxpixels;
- Xxor = .30 * Vc.numxpixels;
- Ytop = .05 * Vc.numypixels;
- Ybot = 2 * Ytop + Yside;
- _selectpalette(0);
- }
-
- void Drawfig()
- {
- _setcolor(1);
- _rectangle(_GFILLINTERIOR, X1, Yb1,
- X1 + Xdelta , Y2);
- _setcolor(2);
- _rectangle(_GFILLINTERIOR,X1 + Xdelta + 1, Yb1,
- X1 + 2 * Xdelta, Y2);
- _setcolor(3);
- _rectangle(_GFILLINTERIOR,X1 + 2 * Xdelta + 1,
- Yb1, X2, Y2);
-
- }
-
- void Drawbackground()
- {
- _setfillmask(Mask);
- _setcolor(1);
- _rectangle(_GFILLINTERIOR, Xmid, 0, Xmax - 1, Ymid - 1);
- _setcolor(2);
- _rectangle(_GFILLINTERIOR, Xmid, Ymid, Xmax, Ymax);
- _setcolor (3);
- _rectangle(_GFILLINTERIOR, 0, Ymid, Xmid - 1, Ymax);
-
- }
-
- void Drawcopies()
- {
- int quad; /* quadrant used */
- char far *storage;
-
- storage = (char far *) malloc((unsigned)_imagesize(
- X1, Yb1, X2, Y2));
- _getimage(X1, Yb1, X2, Y2, storage);
-
- for (quad = 0; quad < 3; quad++)
- {
- _putimage(X[quad] + Xps, Y[quad] + Ytop,
- storage, _GPSET);
- _putimage(X[quad] + Xpr, Y[quad] + Ytop,
- storage, _GPRESET);
- _putimage (X[quad] + Xand, Y[quad] + Ytop,
- storage, _GAND);
- _putimage (X[quad] + Xor, Y[quad] + Ybot,
- storage, _GOR);
- _putimage(X[quad] + Xxor, Y[quad] + Ybot,
- storage, _GXOR);
- }
- }
-
-
- GETYN.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP06\GETYN.C
-
- /* getyn.c -- calls char function getyn() */
- /* with error checking */
-
- #define TRUE 1
-
- main()
- {
- char ch;
- char getyn();
-
- printf("Do you want to continue? ");
- if ((ch = getyn()) == 'y')
- printf("Answer was y\n");
- else
- printf("Answer was n\n");
- printf("Value of ch was %c\n", ch);
- }
-
- char getyn()
- {
- char ch;
- while (TRUE)
- {
- printf(" (y or n) ");
- ch = getche();
- printf("\n");
- if ((ch == 'y') || (ch == 'n'))
- /* valid response, break out of loop */
- break;
- /* give error message and loop again */
- printf("please enter ");
- }
- return(ch);
- }
-
-
- GRAPHBOX.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP04\GRAPHBOX.C
-
-
- /* GRAPHBOX.C -- defined to use PC-specific */
- /* graphics characters */
-
- #define NL 10
- #define CR 13
- #define BLANK 32
- #define UPLEFT 201
- #define UPRIGHT 187
- #define LOWLEFT 200
- #define LOWRIGHT 188
- #define LINE 205
- #define SIDE 186
-
- main()
- {
- int i, j, height, width;
-
- /* get height and width from user */
- printf("How high a box do you want? ");
- scanf("%d", &height);
- printf("How wide do you want it to be? ");
- scanf("%d", &width);
-
- /* draw top of box */
- putch(UPLEFT);
- for (i = 0; i < (width - 2); i++)
- putch(LINE);
- putch(UPRIGHT);
- putch(NL);
- putch(CR); /* go to next line */
-
- /* draw sides of box */
- for (i = 0; i < height - 2; i++) /* outer loop */
- {
- putch(SIDE); /* left side */
- for (j = 0; j < (width - 2); j++) /* inner loop */
- {
- putch(BLANK);
- }
- putch(SIDE); /* right side */
- putch(NL);
- putch(CR); /* move to next line */
- }
-
- /* draw bottom of box */
- putch(LOWLEFT);
- for (i = 0; i < (width - 2); i++)
- putch(LINE);
- putch(LOWRIGHT);
- putch(NL);
- putch(CR); /* box is done, move cursor to new line */
- }
-
-
-
- GRAPHCHA.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\GRAPHCHA.C
-
- /* grafchar.c -- draws graphics characters with */
- /* attributes on the screen */
- /* Program list : grafchar.c, initstuf.c, drawchar.c, */
- /* scrfun.c */
- /* User include files: keys.h, scrn.h, grafchar.h */
- /* Note: activate Screen Swapping On in Debug menu */
-
- #include "grafchar.h"
- unsigned char Grchr[NUMCHARS]; /* to store graphics set */
- void Init_stuff(void); /* in initstuf.c */
- void Draw_chars(void); /* in drawchar.c */
-
- main()
- {
- Init_stuff(); /* initialize vital elements */
- Draw_chars(); /* map keys to graphics characters */
- }
-
-
- HARDWARE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\HARDWARE.C
-
- /* hardware.c -- shows a mixture of int, */
- /* float, and char types */
-
- main()
- {
- int threads = 8; /* threads per inch */
- float length = 1.25, /* length in inches */
- diameter = 0.425, /* diameter in inches */
- price = 0.89; /* price per hundred */
- char bin = 'A'; /* kept in bin A */
- long quantity = 42300; /* number in bin */
-
- printf("Screws: %d threads/inch\n%f inches long\n",
- threads, length);
- printf("%f diameter\n\n", diameter);
- printf("Price per 100: %f\n", price);
- printf("Stored in bin: %c\nQuantity on hand: %ld",
- bin, quantity);
- }
-
-
- HELLO.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP09\HELLO.C
-
- /* hello.c -- legal ways to initialize strings as */
- /* arrays of char values */
-
- char Gphrase[] = {
- 'H','e','l','l','o','\n','\0' }; /* global initialization */
-
- main()
- {
- static char gphrase[] = {
- 'h','e','l','l','o','\n','\0' }; /* local initialization */
-
- printf("Global: %s\n", Gphrase);
- printf("Local: %s\n", gphrase);
-
- }
-
-
- HELP.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\HELP.C
-
- /* help.c -- uses paging and direct memory access */
- /* to display a help screen */
- /* Program list: help.c, writestr.c, writechr.c, */
- /* scrfun.c */
- /* User include files: scrn.h, color.h */
- /* Note: activate Screen Swapping On in Debug menu */
-
- #include <stdio.h>
- #include <conio.h>
- #include "color.h"
- #include "scrn.h"
- typedef unsigned int (far * VIDMEM);
- #define CGAMEM ((VIDMEM) (0xB800L << 16))
- #define PAGESIZE 2000
- #define PAGEOFFSET 0x800L
- #define ESC '\033'
- #define ATTR1 (BG_BLUE | YELLOW)
- #define ATTR2 (BG_YELLOW | BLUE)
- #define ATTR3 (BG_RED | YELLOW | BLINK | INTENSE)
- #define CH1 (unsigned short) '\xB1'
- char *str1 = "Press ? key for help.";
- char *str2 = "Press Enter key to return.";
- char *str3 = "Press Esc key to quit.";
- char *str4 = "\xB1HELP!\xB1";
- void Write_chars(VIDMEM, unsigned short, unsigned
- short, unsigned short);
- void Write_str(VIDMEM, unsigned short, char *);
-
- main()
- {
- int ch;
- unsigned char page = 0;
- unsigned char mode;
-
- mode = Getvmode();
- if (mode != TEXTC80 && mode != TEXTBW80)
- {
- printf("Only modes 2 and 3 supported. Bye.\n");
- exit(1);
- }
- Setpage (page);
- Write_chars(CGAMEM, '\0', ATTR2, PAGESIZE);
- Write_str(CGAMEM + 2 * COLS, ATTR1, str1);
- Write_str(CGAMEM + 2 * COLS, ATTR1, str1);
- Write_str(CGAMEM + 22 * COLS, ATTR1, str3);
- Write_chars(CGAMEM + PAGEOFFSET, '\0', ATTR1, PAGESIZE);
- Write_str(CGAMEM + PAGEOFFSET + 20 * COLS, ATTR2, str2);
- Write_str(CGAMEM + PAGEOFFSET + 22 * COLS, ATTR1, str3);
- Write_chars(CGAMEM + PAGEOFFSET + 10 * COLS + 36,
- CH1, ATTR3, 7);
- Write_str(CGAMEM + PAGEOFFSET + 11 * COLS + 36,
- ATTR3, str4);
- Write_chars(CGAMEM + PAGEOFFSET + 12 * COLS + 36,
- CH1, ATTR3, 7);
-
- while ((ch = getch()) != ESC)
- {
- if (ch == '?' && page == 0)
- Setpage (page = 1);
- else if (ch == '\r' && page == 1)
- Setpage(page = 0);
- }
- Write_chars(CGAMEM, '\0', NORMAL, PAGESIZE);
- Write_chars(CGAMEM + PAGEOFFSET, '\0', NORMAL, PAGESIZE);
- }
-
-
- HEXOUT.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP07\HEXOUT.C
-
- /* hexout.c -- print a floating point variable in */
- /* hexadecimal format */
-
- extern void Hexout();
-
- main()
- {
- float fary[1];
-
- printf("Enter a floating point number\n");
- printf("(Any nonnumeric entry quits)\n\n");
- while (scanf("%f", &fary[0]) == 1)
- {
- Hexout(fary);
- }
- return (0);
- }
-
- void Hexout(unsigned char chary[])
- {
- int i;
-
- for (i = 0; i < sizeof(float); ++i)
- {
- printf("%02X ", chary[i]);
- }
- printf("\n\n");
- }
-
-
- IBMIQ.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\IBMIQ.C
-
- /* ibmiq.c -- a short dialog */
-
- #include <stdio.h>
- main()
- {
- char name[80];
- int iq;
-
- printf("Enter your first name: -> ");
- scanf("%s", name);
- printf("Enter your IQ: -> ");
- scanf("%d", iq);
- printf("Well, %s, my IQ is %d!", name, 2 * iq - 1 );
- }
-
-
- IF.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP05\IF.C
-
- /* if.c -- simple IF statement */
-
- char ch;
- main()
- {
- printf("Do you want to continue y/n? "); /* prompt */
- if (ch = getche() == 'y')
- printf("\nLet's continue ...\n"); /* if true */
- printf("\nAll done.\n"); /* always executed */
- }
-
-
- IFELSE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP05\IFELSE.C
-
- /* ifelse.c -- IF with ELSE */
-
- char ch;
- int num;
- main()
- {
- printf("Are you a new user? y/n? ");
- if (ch = getche() == 'y')
- {
- /* executed if IF is true */
- printf("\n\nYou must register to use this\n");
- printf("bulletin board. Please read\n");
- printf("Bulletin #1 first. Thank You.\n");
- }
- else
- /* executed if IF is false */
- {
- printf("\n\nEnter your secret number: ");
- scanf("d", &num);
- }
- }
-
-
- INCDEC.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\INCDEC.C
-
- /* incdec.c -- shows effect of */
- /* increments and decrements */
-
- main()
- {
- int a = 10;
-
- printf("a is %d\n", a);
- printf("++a is %d\n", ++a);
- printf("--a sets a back to %d\n", --a);
- }
-
-
- INDEXER.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\INDEXER.C
-
- /* indexer.c -- use indices to display an array */
-
- #include <stdio.h>
- int code1[] = {2, 4, 6, 8};
- int code2[] = {1, 3, 7, 9};
- int code3[] = {5, 10, 15, 20};
- main()
- {
- int index;
- int size = (sizeof code2) / (sizeof (int));
-
- for ( index = 1; index <= size; size++)
- printf("%3d ", code2[index]);
- putchar('\n');
- }
-
-
-
- INDEXER2.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\INDEXER2.C
-
- /* indexer2.c -- use indices to display an array */
-
- #include <stdio.h>
- int code1[] = {2, 4, 6, 8};
- int code2[] = {1, 3, 7, 9};
- int code3[] = {5, 10, 15, 20};
- main()
- {
- int index;
- int size = (sizeof code2) / (sizeof (int));
- /* get number of elements in array */
-
- for ( index = 1; index <= size; index++)
- printf("%3d ", code2[index]);
- putchar('\n');
- }
-
-
- INFLATE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP04\INFLATE.C
-
-
- /* INFLATE.C -- shows multiple initialization */
- /* and calculations in for loop */
-
- main()
- {
- int year;
- float value, rate;
- printf("What do you think the inflation rate will be?");
- scanf("%f", &rate);
- printf("If the dollar is worth 100 cents in 1987\n");
- printf("and the inflation rate is %2.2f, then:\n", rate);
-
- for (year=1988, value = 1.0; year <=1999;
- value *= (1.0 - rate),
- printf("in %d the dollar will be worth", year),
- printf(" %2.0f cents\n", value * 100),
- ++year
- );
- }
-
-
-
- INITSTUF.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\INITSTUF.C
-
- /* initstuf.c -- initializing module for grafchar.c */
- /* assign graphics character codes to an array */
- /* and initialize screen */
-
- "scrn.h" /* Clearscr(), Home(), Setcurs() */
- #include "grafchar.h"
- extern unsigned char Grchr[]; /* defined in grafchar.c */
- void Print_attr(char *, unsigned char, unsigned char);
- void Init_stuff()
- {
- int i;
-
- /* initialize array with graphics characters */
- for (i = 0; i < NUMCHARS; i++)
- Grchr[i] = GCSTART + i;
- Clearscr();
- Home();
-
- /* show key meanings at bottom of screen */
- Setcurs(BOTLINE + 1, 0, PAGE);
- for (i = 0; i < 40; i++) /* graphics chars */
- {
- putch(Grchr[i]);
- putch(SPACE);
- }
- Setcurs(BOTLINE + 2, 0, PAGE);
- for (i = 0; i < 40; i++) /* key assignments */
- {
- putch('0' + i);
- putch(SPACE);
- }
- Setcurs(BOTLINE + 3, 0, PAGE);
- for (i = 40; i < NUMCHARS; i++) /* second row */
- {
- putch(Grchr[i]);
- putch(SPACE);
- }
- /* show function key assignments */
- printf(" SPACE : ERASE PgUp : No Draw ");
- printf(" PgDn : Draw ESC : Quit");
- Setcurs(BOTLINE + 4, 0, PAGE);
- for (i = 40; i < NUMCHARS; i++) /* second row */
- {
- putch('0' + i);
- putch(SPACE);
- }
- /* more function key assignments */
- Print_attr("F1 : Normal ", NORMAL, PAGE);
- Print_attr("F2 : Reverse Video ", VIDREV, PAGE);
- Setcurs(BOTLINE + 5, 16, PAGE);
- Print_attr("F3 : Blinking ", NORMAL | BLINK, PAGE);
- Print_attr("F4 : Intense ", NORMAL | INTENSE, PAGE);
- Home();
- }
-
- void Print_attr(str, attr, page)
- char *str;
- unsigned char attr, page;
- {
- while (*str != '\0')
- {
- Write_ch_atr(*str++, attr, page, 1);
- Cursrt();
- }
- }
-
-
- INTVARS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\INTVARS.C
-
- /* intvars.c -- declare, define, and print */
- /* some integer variables */
-
- main()
- {
- /* declare variables */
- int length, beam;
- unsigned int displacement;
- /* assign values to variables */
- length = 824;
- beam = 118;
- displacement = 41676;
-
- /* print out values */
- printf("The battleship Bismarck was %d feet long",
- length);
- printf(" with a beam of %d feet,\n", beam);
- printf("and displaced %u tons.\n", displacement);
- }
-
-
- INVERT.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP09\INVERT.C
-
- /* invert.c -- combines character classification and */
- /* transformation to invert text */
-
- <stdio.h> /* for NULL */
- <ctype.h> /* for toupper, et al */
-
- main()
- {
- char buf[BUFSIZ];
- int i;
-
- printf("Type in a line of text and I will invert it.\n");
-
- if (gets(buf) == NULL)
- exit(1);
-
- /* Print the string backwards. */
- for (i = (strlen(buf) -1); i >= 0; --i)
- {
- if (isupper(buf[i])) /* upper to lower */
- putchar(tolower(buf[i]));
- else if (islower(buf[i])) /* lower to upper */
- putchar(toupper(buf[i]));
- else
- putchar(buf[i]);
- }
- putchar('\n');
-
- }
-
-
- KEYS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\KEYS.C
-
- /* keys.c -- The keyboard input-handling routines */
- /* for the texed editor. */
-
- Edit_file()
- {
- char ch;
-
- printf("\nYou are now in the editor.\n");
- printf("Press 'Q' to exit back to main menu.\n");
-
- do
- {
- ch = getch();
- putch(ch);
- } while (ch != 'Q');
-
- printf("\n\n");
- }
-
-
- L2WORDS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP09\L2WORDS.C
-
- /* l2words.c -- employ an array of pointers to */
- /* strings to bust a line of text */
- /* into its component words */
-
- <stdio.h> /* for NULL and BUFSIZ */
-
- main()
- {
- char **Line2words(); /* declare function type */
- char **list; /* pointer to pointer */
- char buf[BUFSIZ]; /* buffer for input */
- int count, i, quote_flag;
-
- printf("Enter a line of text and I will break\n");
- printf("it up for you.\n");
-
- if (gets(buf) == NULL)
- exit(1);
-
- list = Line2words(buf, &count);
-
- for (i = 0; i < count; i++)
- {
- quote_flag = 0;
- printf("<");
- if (list[i] != buf)
- {
- if( list[i][-1] == '"') /* negative subscript */
- {
- ++quote_flag;
- printf("\"");
- }
- }
- printf("%s", list[i]);
-
- if (quote_flag)
- printf("\"");
-
- printf(">\n");
- }
- }
-
- #define MAXW 64
-
- char **Line2words(char *line, int *count)
- {
- static char *words[MAXW];
- int index;
-
- index = 0; /* zero internal index */
-
- while (*line != '\0')
- {
- /* turn spaces and tabs into zeros */
- if (*line == ' ' || *line == '\t')
- {
- *(line++) = '\0';
- continue;
- }
- words[index] = line++; /* found a word */
-
- /* is it quoted? */
- if ( *(words[index]) == '"')
- {
- /* Yes, advance pointer to just past quote. */
- ++words[index];
-
- /* find next quote. */
- while (*line && *line != '"')
- {
- ++line;
- }
-
- /* and turn it into a '\0'. */
- if (*line)
- *(line++) = '\0';
- }
- else
- {
- /* otherwise skip to next space */
- while (*line && *line != ' ' && *line != '\t')
- {
- ++line;
- }
- }
- if (++index == MAXW)
- break;
- }
- *count = index; /* set count via pointer */
- return (words); /* return address of array */
- }
-
-
- LEFTSTR.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\LEFTSTR.C
-
- /* leftstr.c -- a C version of BASIC's LEFT$ */
-
- #include <stdio.h>
-
- char *Leftstr(char *str, int cnt)
- {
- static char *cp = NULL;
- char *malloc();
-
- if (cnt > strlen(str))
- cnt = strlen(str);
- if (cp != NULL)
- free(cp);
- if ((cp = malloc(cnt + 1)) == NULL)
- return (NULL);
- strncpy(cp, str, cnt);
- return (cp);
- }
-
-
- LINES.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP06\LINES.C
-
- /* lines.c -- calls line() with */
- /* five parameters */
-
- #include <graph.h>
-
- main()
- {
- void line (x1, y1, x2, y2, color);
-
- int x1, x2, y1, y2, i, color;
-
- _setvideomode(_MRES16COLOR); /* 320 x 200 16 col. */
- srand(2); /* new random seed */
- for (i = 0; i < 100; i++)
- {
- x1 = rand() % 319; /* random coordinates */
- x2 = rand() % 319;
- y1 = rand() % 199;
- y2 = rand() % 199;
- color = (rand() % 14) + 1; /* random color 1-15 */
- line(x1, y1, x2, y2, color); /* draw a line */
- }
- while(!kbhit() ); /* wait for key to be hit */
-
- _setvideomode(_DEFAULTMODE); /* restore video mode */
- }
-
- void line (x1, y1, x2, y2, color)
- int x1, y1, x2, y2, color;
- {
- _moveto(x1, y1); /* position at first endpoint */
- _setcolor(color);
- _lineto(x2, y2); /* draw line to second endpoint */
- }
-
-
- LINES43.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\LINES43.C
-
- /* lines43.c -- leaves EGA in 43-line mode */
-
- #include <dos.h>
- #include <conio.h>
- #define VIDEO 0x10
- #define SETVMODE 0
- CHAR_GEN 0x11 /* an EGA BIOS function number */
- #define ROM8X8 0x12
- #define BLOCK 0
- #define TEXTC80 3
-
- main()
- {
- union REGS reg;
-
- reg.h.ah = SETVMODE; /* set text mode */
- reg.h.al = TEXTC80;
- int86(VIDEO, ®, ®);
-
- reg.h.ah = CHAR_GEN; /* char generator routine */
- reg.h.al = ROM8X8; /* use 8x8 ROM character box */
- reg.h.bl = BLOCK; /* copy to block 0 */
- int86(VIDEO, ®, ®);
- }
-
-
- LINE_CNT.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\LINE_CNT.C
-
- /* line_cnt.c -- An overly active line counter */
- #include <stdio.h>
- main()
- {
- int ch;
- int lines = 0;
-
- while ( (ch = getchar() ) != EOF )
- if ( ch = '\n')
- lines++;
- printf("There were %d lines\n", lines);
- }
-
-
-
- LOCAL.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP06\LOCAL.C
-
- /* local.c -- local variables defined */
- /* within functions */
-
- main()
- {
- int n = 12;
- int func1(), funct2();
- printf("n in main(): val %d ", n);
- printf("address %d\n", &n);
-
- printf("Calling func1()\n");
- func1();
- printf("Calling func2()\n");
- func2();
- }
-
- int func1()
- {
- int n = 8; /* local variable */
- printf("n in func1(): val %d ", n);
- printf("address %d\n", &n);
- }
-
- int func2()
- {
- int n = 20; /* local variable */
- printf("n in func2(): val %d ", n);
- printf("address %d\n", &n);
- }
-
-
- M.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP05\M.C
-
- /* m.c -- draw a letter M */
- /* using IF and CONTINUE */
-
- /* define characters */
-
- CH 'M' /* character to "draw" with */
- #define BLANK ' '
- #define NL 10
- #define CR 13
- LEFT 20 /* left side of M */
- RIGHT 46 /* right side of M */
- BOTTOM 22 /* last line to use */
- main()
- {
- int pos, line;
- /* space to left side */
- for (line = 1; line <= BOTTOM; line++)
- {
- for (pos = 1; pos < LEFT; pos++)
- {
- putch(BLANK);
- }
- putch(CH); /* draw left side */
-
- /* are we past midpoint? */
- if (line > ((RIGHT - LEFT) / 2))
- {
- /* yes, so just draw right side */
- for (pos = LEFT; pos < RIGHT; pos++)
- {
- putch(BLANK);
- }
- putch(CH);
- putch(NL);
- putch(CR);
- continue; /* start loop over, do next line */
- }
- /* not past midpoint, check for interior */
- for (pos = LEFT; pos < RIGHT; pos++)
- {
- if ((pos == (LEFT + line )) ||
- (pos == (RIGHT - line )))
- putch(CH);
- else
- putch(BLANK);
- }
- putch(CH);
- putch(NL);
- putch(CR); /* could also use printf("\n"); */
- }
- }
-
-
- MAGIC.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP07\MAGIC.C
-
- /* magic.c -- demonstrate use of a two-dimensional */
- /* array of type int */
-
- main()
- {
- static int square[3][3] = { 5, 8, 3, 4, 2, 0, 7, 1, 6 };
- int zrow = 1, zcol = 2; /* location of the zero */
- int num, row, col, i , j, rowdist, coldist;
-
- while (1)
- {
- printf("Swap what with zero?\n");
- printf("(Q to quit)\n");
-
- /* Print the square. */
- for (i = 0; i < 3; ++i)
- {
- for (j = 0; j < 3; ++j)
- {
- printf(" %d ", square[i][j] );
- }
- printf("\n");
- }
-
- /* Input the user number. */
- if ((num = getch()) == 'Q')
- exit(0);
- num -= '0';
- if (num < 1 || num > 9)
- {
- printf("Not a legal number.\n\n");
- continue;
- }
-
- /* Find that square. */
- for (row = 0; row < 3; ++row)
- {
- for(col = 0; col < 3; ++col)
- {
- if (num == square[row][col])
- {
- goto GOTIT;
- }
- }
- }
- GOTIT:
- /* Check for a legal move. */
- if (row > 2 || col > 2)
- {
- printf("Bad Box Specification\n\n");
- continue;
- }
- rowdist = zrow - row;
- if (rowdist < 0)
- rowdist *= -1;
- coldist = zcol - col;
- if (coldist < 0)
- coldist *= -1;
- if (rowdist > 1 || coldist > 1)
- {
- printf("Not A Neighbor\n\n");
- continue;
- }
-
- /* Make the move. */
- square[zrow][zcol] = square[row][col];
- square[row][col] = 0;
- zrow = row;
- zcol = col;
-
- /* See if done, and solved. */
- for (i = 0; i < 3; ++i)
- {
- for (j = 0; j < 3; ++j)
- {
- if (square[i][j] != ((i * 3) + j))
- {
- break;
- }
- }
- }
- if ((i * j) == 9)
- break;
- }
- printf("\n\aYOU GOT IT !!!\n");
- }
-
-
- MASKS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\MASKS.C
-
- /* masks.c -- illustrates _setfillmask() and */
- /* _floodfill() */
- /* Program list: masks.c */
- /* If you load graphics.qlb, no program list is needed*/
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- #include <graph.h>
- unsigned char Inversemask[8];
- unsigned char Masks[3][8] = {
- {0xff,0x00,0xff,0x00,0xff,0x00,0xff,0x00},
- {0xff,0x80,0x80,0x80,0xff,0x08,0x08,0x08},
- {0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa}};
- main(argc, argv)
- int argc;
- char *argv[];
- {
- struct videoconfig vc;
- int mode = _MRES4COLOR;
- short xc, yc;
- short box, i;
-
- if (argc > 1)
- mode = atoi(argv[1]);
- if (_setvideomode(mode) == 0)
- {
- fprintf(stderr,"Can't set mode %d\n", mode);
- exit(1);
- }
- _getvideoconfig(&vc);
- xc = vc.numxpixels / 2;
- yc = vc.numypixels / 2;
- for (i = 0; i < 8; i++)
- Inversemask[i] = ~Masks[1][i];
- _setlogorg(xc, yc);
- _selectpalette(0);
- _setcolor(1);
- _rectangle(_GBORDER, -xc + 1, -yc + 1, xc - 1, yc - 1);
- _moveto(-xc + 1, -yc / 3);
- _lineto(xc -1, -yc / 3);
- _moveto(-xc + 1, yc / 3);
- _lineto(xc -1, yc / 3);
- for (box = 0; box < 3; box++)
- {
- _setcolor(box + 1);
- _setfillmask(Masks[box]);
- _floodfill(0, (box - 1) * yc / 2, 1);
- }
- _settextposition(5, 10);
- _outtext("Press a key to continue");
- getch();
- _setcolor(3);
- _setfillmask(Inversemask);
- _floodfill (0, 0, 1);
- _setcolor(2);
- _setfillmask(Masks[0]);
- _floodfill(0, yc / 2, 1);
- _settextposition(5, 10);
- _outtext("Press a key to terminate");
- getch();
- _setvideomode(_DEFAULTMODE);
- }
-
-
- MATH.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\MATH.C
-
- /* math.c -- shows arithmetic and */
- /* precedence via expressions */
-
- main()
- {
- int a = 10, b = 4, c = 2;
-
- /* simple arithmetic expressions */
- printf("99 + 2 = %d\n", 99 + 2); /* ints */
- printf("5 - 12 = %d\n", 5 - 12);
- printf("7.25 + 3.5 = %f\n", 7.25 + 3.5);
- /* floats */
-
- /* compare presedence on these */
- printf("20 * 20 + 40 = %d\n", 20 * 20 + 40);
- printf("20 * (20 + 40) = %d\n", 20 * (20 + 40));
- printf("a * a - c + b = %d\n", a * a - c + b);
- printf("a * (a - (c + b)) = %d\n",
- a * (a - (c + b)));
-
- /* compare integer and float division */
-
- printf("Integers: 5 / 2 = %d\n", 5 / 2);
- printf("Floats: 5.0 / 2.0 = %f\n", 5.0 / 2.0);
- }
-
-
- MATHTEST.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\MATHTEST.C
-
- /* mathtest.c -- driver for do_math() */
- /* Program list: mathtest.c (to link math functions) */
-
- #include <stdio.h>
- double do_math(double);
- main()
- {
- double input, result;
-
- printf("Enter a number: ");
- while (scanf("%lf", &input) == 1)
- {
- result = do_math(input);
- printf("input = %.2e, result = %.2e\n", input,
- result);
- printf("Next number (q to quit): ");
- }
- }
-
- #include <math.h>
- double do_math(x)
- double x;
- {
- return (sin (x) * exp (-x));
- }
-
-
-
- MENU.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP13\MENU.C
-
- /* menu.c -- uses ansi.sys for cursor control and */
- /* for video reverse in a sample menu */
- /* Note: Requires that ANSI.SYS be installed. */
-
- #include <conio.h>
- ITEMS 5 /* number of menu items */
- UP 72 /* scan code for up arrow */
- DOWN 80 /* scan code for down arrow */
- VIDREV "\033[7m" /* reverse video attribute */
- ATTOFF "\033[0m" /* turn attributes off */
- ED() printf("\033[2J") /* erase display */
- HOME() printf("\033[H") /* home the cursor */
- CUU(Y) printf("\033[%dA",Y); /* cursor up */
- CUD(Y) printf("\033[%dB",Y); /* cursor down */
-
- char *Menu[ITEMS] = {"Add a number to the list",
- "Delete a number from the list",
- "Clear the list",
- "Sum the list",
- "Quit"};
- char *Heading =
- "Use arrow keys to highlight choice. "
- "Use Enter key to select choice.";
-
- void showmenu(int);
- int getmesg(int);
- main()
- {
- int messno = 0; /* message to be highlighted */
- ED();
- showmenu(messno);
- while (messno != ITEMS - 1)
- {
- messno = getmesg(messno);
- ED();
- switch (messno)
- {
- case 0 :
- case 1 :
- case 2 :
- case 3 : printf("...pretending to work ...");
- printf("Hit any key to continue\n");
- getch();
- ED();
- showmenu(messno);
- break;
- case 4 : printf("Quitting!\n");
- break;
- default: printf("Programming error!\n");
- break;
- }
- }
- }
-
- /* showmenu() displays the menu */
- void showmenu(highlite)
- int highlite; /* message number to be highlighted */
- {
- int n;
- char *start;
-
- HOME();
- printf("%s", Heading);
- for (n = 0; n < ITEMS; n++)
- {
- if (n == highlite)
- start = VIDREV; /* turn on reverse video */
- else
- start = ATTOFF;
- printf("\n\n%s%s%s", start, Menu[n], ATTOFF);
- }
- HOME();
- CUD(2 + 2 * highlite);
- }
-
- /* getmesg() selects a menu item */
- int getmesg(mnum)
- int mnum; /* current message number */
- {
- char ch;
-
- while ((ch = getch()) != '\r')
- if (ch == 0)
- {
- ch = getch();
- switch (ch)
- {
- case UP : if (mnum > 0)
- {
- CUU(2);
- showmenu (--mnum);
- }
- else
- {
- CUD(2 * ITEMS - 2);
- showmenu(mnum=ITEMS-1);
- }
- break;
- case DOWN : if (mnum < ITEMS - 1)
- {
- CUD(2);
- showmenu(++mnum);
- }
- else
- {
- CUU(2 * ITEMS - 2);
- showmenu(mnum = 0);
- }
- break;
- }
- }
- return mnum;
- }
-
-
- MIDSTR.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\MIDSTR.C
-
- /* midstr.c -- a C version of BASIC's MID$ */
-
- #include <stdio.h>
-
- char *Midstr(char *str, int where, int cnt)
- {
- static char *cp = NULL;
- char *malloc();
-
- if (cnt > strlen(str + where))
- cnt = strlen(str + where);
- if (cp != NULL)
- free(cp);
- if ((cp = malloc(cnt + 1)) == NULL)
- return (NULL);
- strncpy(cp, str+where, cnt);
- return (cp);
- }
-
-
-
- MISIDENT.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\MISIDENT.C
-
- /* misident.c -- careless typing */
-
- #defne BIG 3
- main()
- {
- char ltr;
- integer num;
-
- num = 2 + BIG;
- lrt = 'a';
- printf("%c %d\n", ltr, num);
- }
-
-
-
- MIXED.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\MIXED.C
-
- /* mixed.c -- shows the effects of mixing */
- /* data types in an expression */
-
- main()
- {
- int i = 50, iresult;
- long l = 1000000, lresult;
- float f = 10.5, fresult;
- double d = 1000.005, dresult;
-
- fresult = i + f; /* int + float to float */
- printf("%f\n", fresult);
-
- fresult = i * f; /* int * float to float */
- printf("%f\n", fresult);
-
- lresult = l + f; /* long + int to long */
- printf("%f\n", lresult);
-
- printf("%f\n", d * f); /* double * float */
- /* to double */
- fresult = d * f; /* assigned to a float */
- printf("%f\n", fresult); /* loses some precision */
-
- /* debugging a division problem */
-
- iresult = i / l; /* int / long to int */
- printf("%d\n", iresult); /* whoops! loses result */
- printf("%ld\n", iresult); /* this won't fix it */
- fresult = i / l; /* store in float result */
- printf("%f\n", fresult); /* doesn't work */
- dresult = i / l; /* try a double */
- printf("%f\n", dresult); /* doesn't work */
- fresult = (float) i / l; /* try type cast */
- printf("%f\n", fresult); /* correct result */
- }
-
-
- MIXLOOPS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP04\MIXLOOPS.C
-
-
- /* MIXLOOPS.C -- reads characters, */
- /* beeps for ASCII count */
- /* uses a while and a for */
-
- #include <conio.h>
-
- main()
- {
- char ch;
- int i;
-
- while ((ch = getche()) != ' ') /* get a char. */
- {
- for (i = 'a'; i <= ch; ++i) /* count up to */
- { /* alphabet pos.*/
- printf("In FOR loop!\n");
- printf("\a"); /* sound beep each time */
- }
- }
- }
-
-
-
- MIXTYPES.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP06\MIXTYPES.C
-
- /* mixtypes.c -- shows problem with calling */
- /* a function with wrong type parameter */
-
- main()
- {
- /* didn't bother to declare int function */
- float n = 5.0;
- int i;
-
- printf("n in main() is %f\n", n);
- i = examine(n); /* pass float to function */
- printf("examine() returned n as %d\n", i);
- }
-
- examine(num) /* function didn't declare return type */
- {
- printf("examine() says n is %d\n", num);
- return(num);
- }
-
-
-
- MODEINFO.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\MODEINFO.C
-
- /* modeinfo.c -- set modes and obtain information */
- /* Demonstrates _setvideomode() and _getvideoconfig() */
- /* If you load graphics.qlb, no program list is needed.*/
-
- #include <conio.h>
- #include <graph.h>
- struct videoconfig vc;
- int modes[15] ={_TEXTBW40, _TEXTC40, _TEXTBW80, _TEXTC80,
- _MRES4COLOR, _MRESNOCOLOR, _HRESBW, _TEXTMONO,
- _MRES16COLOR, _HRES16COLOR, _ERESNOCOLOR, _ERESCOLOR,
- _VRES2COLOR, _VRES16COLOR, _MRES256COLOR};
- char *Adapt(short), *Display(short);
- main()
- {
- int i;
-
- for (i = 0; i < 15; i++)
- {
- if (_setvideomode(modes[i]))
- {
- _getvideoconfig(&vc);
- printf("video mode is %d\n", vc.mode);
- printf("number of columns is %d\n", vc.numtextcols);
- printf("number of colors is %d\n", vc.numcolors);
- printf("number of pages is %d\n", vc.numvideopages);
- printf("adapter is %s\n", Adapt(vc.adapter));
- printf("display is %s\n", Display(vc.monitor));
- printf("the adapter has %dK of memory\n",
- vc.memory);
- }
- else
- printf("mode %d not supported\n", modes[i]);
- printf("strike a key for next mode\n");
- getch();
- }
- _setvideomode (_DEFAULTMODE);
- }
-
- /* Adapt() returns a pointer to a string describing */
- /* the adapter characterized by adapt_num. */
- char *Adapt(adapt_num)
- short adapt_num; /* videoconfig.adapter value */
- {
- static char *anames[6] = {"Monochrome", "CGA", "EGA",
- "MCGA", "VGA", "Not known"};
- char *point;
-
- switch (adapt_num)
- {
- case _MDPA : point = anames[0];
- break;
- case _CGA : point = anames[1];
- break;
- case _EGA : point = anames[2];
- break;
- case _MCGA : point = anames[3];
- break;
- case _VGA : point = anames[4];
- break;
- default : point = anames[5];
- }
- return point;
- }
-
- /* Display() returns a pointer to a string describing */
- /* the monitor characterized by disp. */
- char *Display(disp)
- short disp; /* videoconfig.monitor value */
- {
- static char *types[5] = {"monochrome", "color",
- "enhanced color", "analog",
- "unknown"};
- char *point;
-
- if (disp & _MONO)
- point = types[0];
- else if (disp & _COLOR)
- point = types[1];
- else if (disp & _ENHCOLOR)
- point = types[2];
- else if (disp & _ANALOG)
- point = types[3];
- else
- point = types[4];
- return point;
- }
-
-
- MOIRE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\MOIRE.C
-
- /* moire.c -- variation on dots.c */
- /* If you load graphics.qlb, no program list is needed*/
- #include <conio.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <graph.h>
- #define ESC '\033'
- BKCOLS 8 /* number of background colors */
- PALNUM 4 /* number of palettes */
- long Bkcolors[BKCOLS] = {_BLACK, _BLUE, _GREEN, _CYAN, _RED,
- _MAGENTA, _BROWN, _WHITE};
- main (argc, argv)
- int argc;
- char *argv[];
- {
- struct videoconfig vc;
- unsigned int col, row;
- short color = 0;
- int bkc_index = 1; /* blue background */
- short palette = 0; /* red, green, brown */
- int firstcol, firstrow, lastrow, lastcol;
- int mode = _MRES4COLOR;
- int ch;
-
- if (argc > 1)
- mode = atoi(argv[1]);
-
- if (_setvideomode(mode) == 0)
- {
- printf("Can't do that mode.\n");
- exit(1);
- }
- _getvideoconfig(&vc);
- firstcol = vc.numxpixels / 5;
- firstrow = vc.numypixels / 5;
- lastcol = 4 * vc.numxpixels / 5;
- lastrow = 4 * vc.numypixels / 5;
- _selectpalette(palette);
- _setbkcolor (Bkcolors[bkc_index]);
- for (col = firstcol; col <= lastcol; ++col)
- {
-
- for (row = firstrow; row <= lastrow; ++row)
- {
- _setcolor(((row*row + col*col)/10)%vc.numcolors);
- _setpixel(col, row);
- }
- }
- while ((ch = getch()) != ESC)
- {
- if (ch == 'p')
- _selectpalette(++palette % PALNUM);
- else if (ch == 'b')
- _setbkcolor(Bkcolors[++bkc_index % BKCOLS]);
- }
- _setvideomode(_DEFAULTMODE); /* reset orig. mode */
- }
-
-
- NARROW.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\NARROW.C
-
- /* narrow.c -- a choppy C program */
-
- main( )
- {
- printf
- ("Hello, and welcome to QuickC!\n");
- }
-
-
- ONELINE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\ONELINE.C
-
- /* oneline.c -- shows how printf() continues */
- /* on the same line */
-
- main()
- {
- printf("All displayed on");
- printf("the same line, with no space");
- printf(" unless specified.");
- /* note added space in line above */
- }
-
-
- OPEQUAL.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\OPEQUAL.C
-
- /* opequal.c -- shows combination math/assignment */
- /* operators and increment operators */
-
- main()
- {
- int m = 10, n = 5;
- printf("Starting values: m = %d n = %d\n",
- m, n);
-
- /* combination of arithmetic and assignment */
- printf("m += 2 makes m %d\n", m += 2);
- printf("m -= n makes m %d\n", m -= n);
- printf("m *= 2 makes m %d\n", m *= 2);
-
- /* two ways to increment m */
- printf("m = m + 1 makes m %d\n",
- m = m + 1);
- printf("m += 1 makes m %d\n",
- m += 1);
- }
-
-
- PACK.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\PACK.C
-
- /* pack.c -- demonstrates structure packing with */
- /* the #pragma pack() directive */
-
- pack(4) /* 1, 2 or 4 */
-
- main()
- {
- struct {
- char ch1;
- int int1;
- char ch2;
- long int2;
- } s;
-
- printf("ch1 -> %lu\n", (unsigned long)(&s.ch1));
- printf("int1 -> %lu\n", (unsigned long)(&s.int1));
- printf("ch2 -> %lu\n", (unsigned long)(&s.ch2));
- printf("int2 -> %lu\n", (unsigned long)(&s.int2));
- }
-
-
- PASSWORD.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP13\PASSWORD.C
-
- /* password.c -- requires a password to complete the */
- /* program; illustrates a use of getch() */
-
- #include <stdio.h>
- #include <conio.h>
- #include <string.h>
- #define GUESS_LIMIT 4
- WORD_LIMIT 10 /* maximum length of password */
- #define TRUE 1
- #define FALSE 0
- char *Password = "I'mOk";
- main()
- {
- int g_count = 0; /* guesses taken */
- int w_count; /* letters accepted */
- int in_count; /* letters entered */
- char entry[WORD_LIMIT + 1];
- char ch;
- int correct, go_on;
-
- do
- {
- puts("Enter the secret password.");
- in_count = w_count = 0;
- /* the following loop accepts no more chars */
- /* than entry[] will hold, but keeps track */
- /* of total number typed */
- while ((ch = getch()) != '\r')
- {
- if (w_count < WORD_LIMIT)
- entry[w_count++] = ch;
- in_count++;
- }
- entry[w_count] = '\0';
- if (in_count != w_count)
- correct = FALSE; /* too many chars */
- else
- correct = (strcmp(entry, Password) == 0);
- g_count++;
- go_on = !correct && g_count < GUESS_LIMIT;
- if (go_on)
- puts("\nNo good; try again.");
- } while (go_on);
- if (!correct)
- {
- puts("Sorry, no more guesses. Bye.");
- return(1);
- }
- puts("Welcome to Swiss bank account 2929100.");
- puts("Your current balance is $10,232,862.61.");
- return(0);
- }
-
-
- PEEK.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP08\PEEK.C
-
- /* peek.c -- demonstrates how to cast an int to a */
- /* pointer */
-
- main()
- {
- char *mem_ptr;
- unsigned int address;
-
- while (1)
- {
- printf("Examine what memory location?\n");
- printf("Enter location in decimal: ");
- if (scanf("%u", &address) != 1)
- break;
-
- mem_ptr = (char *)address; /* cast */
-
- printf("The value in %u is 0x%02X\n",
- address, (unsigned char)*mem_ptr);
- }
- }
-
-
- PHONE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP10\PHONE.C
-
- /* phone.c -- a telephone number mini-database that */
- /* demonstrates fseek() */
-
- <stdio.h> /* for FILE, BUFSIZ, NULL */
-
- #define MAXL (128)
- char Name[MAXL];
- char Number[MAXL];
- char File[] = "C:\\TMP\\PHONE.DB";
- int Count;
- FILE *Fp;
- int Distance = (MAXL * MAXL);
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- if (argc == 1)
- Ask();
- else
- Find(argv[1]);
-
- return (0);
- }
-
- Find(char *str)
- {
- int i;
-
- if ((Fp = fopen(File, "r")) == NULL)
- {
- fprintf(stderr, "\"%s\": Can't Read\n", File);
- exit (1);
- }
- if (fread(&Count, 1, sizeof(int), Fp) != sizeof(int))
- {
- fprintf(stderr,"\"%s\": Error Reading\n", File);
- exit (1);
- }
- for (i = 0; i < Count; i++)
- {
- fread(Name, 1, MAXL, Fp);
- fread(Number, 1, MAXL, Fp);
- if (ferror(Fp))
- {
- fprintf(stderr, "\"%s\": Error Reading.\n", File);
- exit (1);
- }
- if (strcmp(*str, *Name) == 0)
- {
- printf("Name: %s\n", Name);
- printf("Number: %s\n", Number);
- return;
- }
- }
- fprintf(stderr, "\"%s\": Not in database.\n", str);
- return;
- }
-
- Ask()
- {
- if ((Fp = fopen(File, "r+")) == NULL)
- Make();
- else if (fread(&Count, 1, sizeof(int),Fp) != sizeof(int))
- {
- fprintf(stderr, "\"%s\": Error Reading\n", File);
- exit (1);
- }
- printf("Name: ");
- if (gets(Name) == NULL || *Name == '\0')
- return;
- printf("Number: ");
- if (gets(Number) == NULL || *Number == '\0')
- return;
- if (fseek(Fp, (long)(Distance * Count), SEEK_CUR) != 0)
- {
- fprintf(stderr, "\"%s\": Error Seeking.\n", File);
- exit (1);
- }
- fwrite(Name, 1, MAXL, Fp);
- fwrite(Number, 1, MAXL, Fp);
- if (ferror(Fp))
- {
- fprintf(stderr, "\"%s\": Error Writing.\n", File);
- exit (1);
- }
- if (fseek(Fp, 0L, SEEK_SET) != 0)
- {
- fprintf(stderr, "\"%s\": Error Seeking.\n", File);
- exit (1);
- }
- ++Count;
- if (fwrite(&Count, 1, sizeof(int),Fp) != sizeof(int))
- {
- fprintf(stderr, "\"%s\": Error Writing\n", File);
- exit (1);
- }
- return;
- }
-
- Make()
- {
- if ((Fp = fopen(File, "w+")) == NULL)
- {
- fprintf(stderr, "\"%s\": Can't Create\n", File);
- exit (1);
- }
- Count = 0;
- if (fwrite(&Count, 1, sizeof(int), Fp) != sizeof(int))
- {
- fprintf(stderr," \"%s\": Error Creating\n", File);
- exit (1);
- }
- }
-
-
- PHWORD.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP08\PHWORD.C
-
- /* phword.c -- generate all the possible words */
- /* in a phone number; demonstrates */
- /* functions that return addresses */
-
- MAXD (7) /* 7 digits max */
-
- main()
- {
- int digits[MAXD], ndigits = 0, line = 0;
- char *letters;
- signed char digit;
- int a, b, c, d, e, f, g;
- extern char *Range();
-
- printf("Enter Phone Number (7 digits): ");
- do
- {
- digit = getch() - '0';
- if (digit == ('-' - '0'))
- continue;
- if (digit < 0 || digit > 9)
- {
- printf("\nAborted: Non Digit\n");
- return(1);
- }
- digits[ndigits++] = digit;
- printf("%d", digit);
- } while (ndigits < 7);
- printf("\n");
-
- for( a = 0; a < 3; ++a)
- for( b = 0; b < 3; ++b)
- for( c = 0; c < 3; ++c)
- for( d = 0; d < 3; ++d)
- for( e = 0; e < 3; ++e)
- for( f = 0; f < 3; ++f)
- for( g = 0; g < 3; ++g)
- {
- printf("%c", Range(digits[0])[a]);
- printf("%c", Range(digits[1])[b]);
- printf("%c", Range(digits[2])[c]);
- printf("%c", Range(digits[3])[d]);
- printf("%c", Range(digits[4])[e]);
- printf("%c", Range(digits[5])[f]);
- printf("%c", Range(digits[6])[g]);
- printf("\n");
- if (++line == 20)
- {
- printf("Press Any key for More");
- printf(" (or q to quit): ");
- if (getch() == 'q')
- return (0);
- printf("\n");
- line = 0;
- }
- }
- }
-
- char *Range(int key)
- {
- static char keys[10][3] = {
- {'0', '0', '0' },
- {'1', '1', '1' },
- {'a', 'b', 'c' },
- {'d', 'e', 'f' },
- {'g', 'h', 'i' },
- {'j', 'k', 'l' },
- {'m', 'n', 'o' },
- {'p', 'r', 's' },
- {'t', 'u', 'v' },
- {'w', 'x', 'y' }
- };
-
- return (keys[key]);
- }
-
-
- PIXELS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP05\PIXELS.C
-
- /* pixels.c -- create shapes */
- /* from random pixels */
-
- <graph.h> /* for graphics */
-
- main()
- {
- int pixels, xpos, ypos;
- /* window coordinates */
- int xmin = 100, xmax = 540;
- int ymin = 50, ymax = 150;
-
- srand(0); /* init random nums */
- _setvideomode(_HRESBW); /* CGA 640 x 200 */
- _setcolor(1); /* white foreground */
-
- /* generate random pixel locations */
- for (pixels = 1; pixels < 10000; pixels++)
- {
- xpos = rand() % 639;
- ypos = rand() % 199;
-
- /* set pixel if within window */
- if ((xpos > xmin && xpos < xmax) &&
- (ypos > ymin && ypos < ymax))
- _setpixel(xpos, ypos);
- }
- getch(); /* freeze screen until key pressed */
- /* restore original video mode */
- _setvideomode(_DEFAULTMODE);
- }
-
-
- POINTER.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP08\POINTER.C
-
- /* pointer.c -- demonstrates pointer declaration, */
- /* assignment, and use */
-
- #define WAIT printf("(press any key)"); getch(); \
- printf("\n\n")
-
- main()
- {
- int num, *address_var;
-
- num = 0;
- address_var = #
-
- printf("The address of the variable ");
- printf("\"num\" is: 0x%04X\n", &num );
- printf("The value in the pointer ");
- printf("\"address_var\" is: 0x%04X\n", address_var);
- printf("The value in the variable ");
- printf("\"num\" is: %d\n", num );
- WAIT;
- printf("Since \"address_var\" points to \"num\"\n");
- printf("the value in ");
- printf("\"*address_var\" is: %d\n", *address_var);
- WAIT;
- printf("To verify this, let's store 3 in\n");
- printf("\"*address_var\", then print out ");
- printf("\"num\" and \"*address_var\"\n");
- printf("again.\n");
- WAIT;
-
- printf("Doing: *address_var = 3;\n\n");
- *address_var = 3;
-
- printf("The address of the variable ");
- printf("\"num\" is: 0x%04X\n", &num);
- printf("The value in the pointer ");
- printf("\"address_var\" is: 0x%04X\n", address_var);
- printf("The value in the variable ");
- printf("\"num\" is: %d\n", num);
- WAIT;
- printf("Since \"address_var\" points to \"num\"\n");
- printf("the value in ");
- printf("\"*address_var\" is: %d\n", *address_var);
- WAIT;
-
- printf("Now we will add 15 to \"num\" and print\n");
- printf("\"num\" and \"*address_var\" again.\n");
- WAIT;
-
- printf("Doing: num += 15;\n\n");
- num += 15;
-
- printf("The address of the variable ");
- printf("\"num\" is: 0x%04X\n", &num);
- printf("The value in the pointer ");
- printf("\"address_var\" is: 0x%04X\n", address_var);
- printf("The value in the variable ");
- printf("\"num\" is: %d\n", num);
- WAIT;
- printf("Since \"address_var\" points to \"num\"\n");
- printf("the value in ");
- printf("\"*address_var\" is: %d\n", *address_var);
- WAIT;
-
- printf("Doing: return (*address_var);\n\n");
- return (*address_var);
- }
-
-
- PORTINFO.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\PORTINFO.C
-
- /* portinfo.c -- reads port values */
- /* program list -- portinfo.c (inp() not in core lib) */
-
- #include <conio.h>
- #include <stdio.h>
- main()
- {
- unsigned int portnum;
- int regvalue;
-
- printf("Enter number (in hex) of the port ");
- printf("you wish to read: ");
- while (scanf("%x", &portnum) == 1)
- {
- regvalue = inp(portnum);
- printf("\nValue returned for port %x is %d (decimal)"
- " %x (hex)\n", portnum, regvalue, regvalue);
- printf("Next port? (q to quit): ");
- }
- }
-
-
- POWER.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\POWER.C
-
- /* power.c -- attempting to raise to a power */
-
- main()
- {
- int number;
-
- number = 10**3; /* raise 10 to 3rd power? */
- printf("%d\n", number);
- }
-
-
- PREPOST.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\PREPOST.C
-
- /* prepost.c -- shows effect of pre- */
- /* and post-increments */
- /* and decrements */
-
- main()
- {
- int b = 100;
-
- printf("b is %d\n", b);
- printf("b++ is still %d\n", b++);
- printf("but after it's used, ");
- printf("b is incremented to %d\n\n, b);
-
- printf("++b, on the other hand, ");
- printf("is immediately %d\n", ++b);
- }
-
-
- PROTO.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP06\PROTO.C
-
- /* proto.c -- demonstrate function prototyping */
- /* and parameter checking */
-
- main()
- {
- float n = 9995.997;
- int i;
- int examine(int num); /* declare function */
- /* with prototype */
-
- printf("n in main() is %f\n", n);
- i = examine(n); /* pass float to function */
- printf("examine() returned n as %d\n", i);
- }
-
- int examine(num)
- {
- printf("examine() says n is %d\n", num);
- return(num);
- }
-
-
- QCHELLO.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP02\QCHELLO.C
-
- /* qchello.c -- a simple C program */
-
- main()
- {
- printf("Hello, and welcome to QuickC!\n");
- }
-
-
- RACE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\RACE.C
-
- /* race.c -- race of the patterned circles */
- /* Illustrates animation with _getimage() and */
- /* _putimage(), random number use with srand() and */
- /* rand(), and system clock use with time() and */
- /* ftime().
- /* Program list: race.c (for srand(), rand(), and */
- /* ftime()) */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- #include <graph.h>
- #include <time.h>
- #include <sys\types.h>
- #include <sys\timeb.h>
-
- #define END 25
- #define FIGNUM 3
- typedef char far *PTFRCHAR;
- PTFRCHAR Bufs[FIGNUM];
- unsigned char Masks[FIGNUM][8] = {
- {0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00},
- {0xF0,0xF0,0xF0,0xF0,0x0F,0x0F,0x0F,0x0F},
- {0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,0xAA}};
- short Xul[FIGNUM], Yul[FIGNUM]; /* figure locations */
- short Xsize, Ysize; /* figure size */
- struct videoconfig Vc;
- void Initialize(void);
- void Draw_n_store(void);
- void Move_figs(void);
- void Wait(double);
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- int mode = _MRES4COLOR;
-
- if (argc > 1)
- mode = atoi(argv[1]);
- if (_setvideomode(mode) == 0)
- {
- fprintf(stderr,"mode %d not supported\n",mode);
- exit(1);
- }
- Initialize();
- Draw_n_store();
- _settextcolor(2);
- _settextposition(1, 1);
- _outtext("Place your bets and type a key");
- _settextposition(25, 1);
- _outtext("Type a key again when done");
- getch();
- Move_figs();
- getch();
- _setvideomode(_DEFAULTMODE);
- }
-
- void Initialize()
- {
- int i;
- float ar; /* aspect ratio */
-
- _getvideoconfig(&Vc);
- ar = (float)(10 * Vc.numypixels) / (6.5 * Vc.numxpixels);
- /* set size, initial positions */
- Xsize = Vc.numxpixels / 30;
- Ysize = ar * Xsize;
- for(i = 0; i < FIGNUM; i++)
- {
- Xul[i] = 0;
- Yul[i] = (i + 1) * Vc.numypixels /
- (FIGNUM + 1);
- }
- _selectpalette(0);
- _setcolor(1);
- /* draw finish line */
- _moveto(END * Xsize, 0);
- _lineto(END * Xsize, Vc.numypixels - 1);
- }
-
- void Draw_n_store() /* draw images, save them */
- {
- int i;
-
- for (i = 0; i < FIGNUM; i++)
- {
- _setcolor(i + 1);
- _setfillmask(Masks[i]);
- _ellipse(_GFILLINTERIOR ,Xul[i], Yul[i],
- Xul[i] + Xsize, Yul[i] + Ysize);
- _ellipse(_GBORDER ,Xul[i], Yul[i],
- Xul[i] + Xsize, Yul[i] + Ysize);
- Bufs[i] = (PTFRCHAR) malloc((unsigned int)
- _imagesize(0,Yul[i], Xul[i] +
- Xsize, Yul[i] + Ysize));
- _getimage(Xul[i],Yul[i], Xul[i] + Xsize, Yul[i] +
- Ysize, Bufs[i]);
-
- }
- }
- void Move_figs()
- {
- int i, j;
- static int dx[FIGNUM] = {0, 0, 0}; /* displacements */
- time_t tval;
-
- time(&tval); /* use the current time value */
- srand(tval); /* to initialize rand() */
- while (dx[0] < END && dx[1] < END && dx[2] < END)
- {
- for (i = 0; i < FIGNUM; i++)
- {
- /* advance the figure one position if */
- /* rand() returns an even number */
- if (rand() % 2 == 0)
- {
- /* erase old image */
- _putimage(dx[i] * Xsize, Yul[i],
- Bufs[i], _GXOR);
- /* redraw in new position */
- _putimage((1 + dx[i]) * Xsize, Yul[i],
- Bufs[i], _GPSET);
- dx[i]++;
- }
- }
- Wait(0.15);
- }
- for (j = 0; j < 5; j++)
- {
- for(i = 0; i < FIGNUM; i++)
- {
- /* flash winning figure */
- if (dx[i] >= END)
- {
- Wait(0.2);
- _putimage(dx[i] * Xsize,Yul[i],
- Bufs[i], _GPRESET);
- Wait(0.2);
- _putimage(dx[i] * Xsize,Yul[i],
- Bufs[i], _GPSET);
- }
- }
- }
- }
-
- void Wait(pause) /* wait for pause seconds */
- double pause;
- {
- struct timeb start, end;
- long delay;
-
- delay = 1000 * pause; /* convert to milliseconds */
- ftime(&start);
- ftime(&end);
- while ((1000 * (end.time - start.time) +
- + end.millitm - start.millitm) < delay)
- ftime(&end);
- }
-
-
-
- READKEY.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP13\READKEY.C
-
- /* readkey.c -- contains the Readkey() function */
- #include <dos.h>
- KEYINTR 0x16 /* keyboard read interrupt */
- GETCHAR 0 /* read scancode function */
- struct SCANCODE {
- unsigned char ascii; /* ascii code */
- unsigned char scan; /* scan code */
- };
-
- struct SCANCODE Readkey()
- {
- union REGS reg;
- struct SCANCODE scancode;
-
- reg.h.ah = GETCHAR; /* specify function */
- int86(KEYINTR, ®, ®); /* note use of & oper.*/
- scancode.ascii = reg.h.al;
- scancode.scan = reg.h.ah;
- return (scancode);
- }
-
-
- RECALL.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\RECALL.C
-
- /* recall.c -- displays previously stored screen, */
- /* including attributes. Uses DMA. */
- /* Program list: recall.c, scrfun.c */
- /* User include files: scrn.h, grafchar.h */
- /* Note: activate Screen Swapping On in Debug menu */
-
- #include <stdio.h>
- #include <conio.h>
- #include "scrn.h"
- #include "grafchar.h"
-
- main(ac, ar)
- int ac;
- char *ar[];
- {
- unsigned char mode;
- unsigned short char_attr;
- FILE *save;
- unsigned int offset;
- char filename[81];
- VIDMEM screen;
-
- if (ac < 2)
- {
- fprintf(stderr, "Usage: %s filename\n", ar[0]);
- exit(1);
- }
-
- if ((save = fopen(ar[1],"rb")) == NULL)
- {
- fprintf(stderr, "Can't open %s\n", ar[1]);
- exit(1);
- }
-
- if ((mode = Getvmode()) == TEXTMONO)
- screen = MONMEM;
- else if (mode == TEXTC80 || mode == TEXTBW80)
- screen = CGAMEM;
- else
- exit(1);
-
- Clearscr();
- for (offset = 0; offset < CHARS; offset++)
- {
- fread(&char_attr, 2, 1, save);
- screen[offset] = char_attr;
- }
- fclose(save);
- Setcurs(23, 0, PAGE);
- getch(); /* anti scrolling for QC environment */
- }
-
-
- RECEIPTS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\RECEIPTS.C
-
- /* receipts.c -- calculates gross and net */
- /* receipts on sales */
-
- main()
- {
- int units = 38; /* number sold */
- float price = 149.99, /* price per item */
- rate = 0.06; /* sales tax rate */
-
- /* variables to hold calculated totals */
- float gross, tax, net;
-
- /* perform calculations */
- net = units * price;
- tax = net * rate;
- gross = net + tax;
-
- /* print results */
- printf("\tSales Report\n");
- printf("Net sales: \t%6.2f\n", net);
- printf("Tax:\t\t %5.2f\n", tax);
- printf("Gross sales:\t%6.2f\n", gross);
- }
-
-
- RECT.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\RECT.C
-
- /* rect.c -- illustrates logical coordinates, */
- /* the _rectangle() and _setlinestyle() */
- /* functions */
- /* If you load graphics.qlb, no program list is needed */
-
- #include <stdio.h>
- #include <graph.h>
- #include <conio.h>
- #define STYLES 5
- short Linestyles[STYLES] = {0xFFFF, 0x8888, 0x7777,
- 0x00FF, 0x8787};
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- struct videoconfig vc;
- int mode = _MRES4COLOR;
- int xcent, ycent;
- int xsize, ysize;
- int i;
-
- if (argc > 1)
- mode = atoi(argv[1]);
- if (_setvideomode(mode) == 0)
- {
- printf("Can't open that mode.\n");
- exit(1);
- }
- _getvideoconfig(&vc);
- xcent = vc.numxpixels / 2 - 1;
- ycent = vc.numypixels / 2 - 1;
- _setlogorg(xcent, ycent);
- xsize = 0.9 * xcent;
- ysize = 0.9 * ycent;
- _selectpalette(1);
- _setcolor(3);
- _rectangle(_GBORDER, -xsize, -ysize, xsize, ysize);
- xsize *= 0.9;
- ysize *= 0.9;
- _setcolor(1);
- _rectangle(_GFILLINTERIOR, -xsize, -ysize, xsize, ysize);
- for (i = 0; i < 16; i++)
- {
- _setcolor(((i % 2) == 0) ? 2 : 3);
- _setlinestyle(Linestyles[ i % 5 ]);
- xsize *= 0.9;
- ysize *= 0.9;
- _rectangle(_GBORDER, -xsize, -ysize, xsize, ysize);
- }
- getch(); /* Type a key to terminate. */
- _setvideomode(_DEFAULTMODE);
- }
-
-
- RECURSE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP06\RECURSE.C
-
- /* recurse.c -- demonstrates recursion */
-
- int level = 1; /* recursion level */
- main()
- {
- int num, result;
-
- printf("Factorial of what number? ");
- scanf("%d", &num);
- result = factorial(num);
- printf("Result is: %d\n", result);
- }
-
- factorial(number)
- {
- int result;
- printf("entering: ");
- printf("level %d. number = %d. &number = %d\n",
- level++, number, &number);
-
- if (number == 0)
- result = 1;
- else
- result = number * factorial(number - 1);
-
- printf("exiting : ");
- printf("level %d. number = %d. &number = %d. ",
- --level, number, &number);
- printf("result = %d\n", result);
-
- return(result);
- }
-
-
- REKEY.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP13\REKEY.C
-
- /* rekey.c -- transliterates typed input */
- /* This program illustrates getch() and putch(). */
-
- #include <stdio.h>
- #include <conio.h>
- #include <ctype.h>
- ESC '\033' /* the escape key */
- char Newchars[] = "qwertyuiopasdfghjklzxcvbnm";
- /* values to be assigned to the a,b,c keys, etc. */
- main()
- {
- char ch;
-
- printf("Type characters and see them transformed;\n");
- printf("Press the Esc key to terminate.\n");
- while ((ch = getch()) != ESC)
- if (islower(ch))
- putch(Newchars[ch - 'a']);
- else if (isupper(ch))
- {
- ch = tolower(ch);
- putch(toupper(Newchars[ch - 'a']));
- }
- else if (ch == '\r')
- {
- putch('\n');
- putch('\r');
- }
- else
- putch(ch);
- }
-
-
- RELATION.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\RELATION.C
-
- /* relation.c -- shows effect of */
- /* relational operators */
-
- main()
- {
- int a = 5, b = 3, c = 4;
- printf("a = %d\t b = %d\t c = %d\n", a, b, c);
-
- printf("Expression a > b has a value of %d\n",
- a > b);
- printf("Expression a == c has a value of %d\n",
- a == c);
- printf("Expression a > (b + c) has a value of %d\n",
- a > (b + c));
- printf("Expression a = b has a value of %d\n",
- a = b); /* what happened here? */
- }
-
-
- REMOIRE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\REMOIRE.C
-
- /* remoire.c -- adds palette remapping to moire.c */
- #include <conio.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <graph.h>
- #define ESC '\033'
- #define MAXCOLORS 64
- #define PALCOLORS 16
- long Ega_to_vga(int);
-
- main (argc, argv)
- int argc;
- char *argv[];
- {
- struct videoconfig vc;
- unsigned int col, row;
- long colors[MAXCOLORS];
- long palette[PALCOLORS];
- int index;
- int shift = 1;
- int firstcol, firstrow, lastrow, lastcol;
- int mode = _ERESCOLOR;
-
-
- if (argc > 1)
- mode = atoi(argv[1]);
-
- if (_setvideomode(mode) == 0)
- {
- printf("Can't do that mode.\n");
- exit(1);
- }
- /* Create array of all 64 color values. */
- for (index = 0; index < MAXCOLORS; index++)
- colors[index] = Ega_to_vga(index);
- /* Create array of 16 palette choices. */
- for (index = 0; index < PALCOLORS; index++)
- palette[index] = colors[index];
- _remapallpalette(palette);
- _getvideoconfig(&vc);
- firstcol = vc.numxpixels / 5;
- firstrow = vc.numypixels / 5;
- lastcol = 4 * vc.numxpixels / 5;
- lastrow = 4 * vc.numypixels / 5;
-
- for (col = firstcol; col <= lastcol; ++col)
- {
- for (row = firstrow; row <= lastrow; ++row)
- {
- _setcolor(((row * row + col * col) / 10)
- % vc.numcolors);
- _setpixel(col, row);
- }
- }
- _settextposition(1, 1);
- _outtext("Type a key to stop or start.");
- _settextposition(2, 1);
- _outtext("Type [Esc] while paused to quit.");
- do
- {
- while (!kbhit())
- {
- /* Set palette array to new color values. */
- for (index = 1; index < PALCOLORS; index++)
- palette[index] = (colors[(index + shift)
- % MAXCOLORS]);
- _remapallpalette(palette);
- shift++;
- }
- getch(); /* pause until key is typed */
- } while (getch() != ESC);
-
- _setvideomode(_DEFAULTMODE); /* reset orig. mode */
- }
-
- long Ega_to_vga(egacolor)
- int egacolor; /* ega color value */
- {
- static long vgavals[6] = {0x2A0000L, 0x002A00L, 0x00002AL,
- 0x150000L, 0x001500L, 0x000015L};
- long vgacolor = 0L; /* vga color value */
- int bit;
-
- for (bit = 0; bit < 6; bit++)
- vgacolor += ((egacolor >> bit) &1) * vgavals[bit];
- return (vgacolor);
- }
-
-
- REVERSE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP08\REVERSE.C
-
- /* reverse.c -- demonstrates an array of pointers */
- /* by reversing lines of text */
-
- <stdio.h> /* for NULL */
- <malloc.h> /* for size_t */
-
- #define MAXL 20
-
- main()
- {
- char *cptrs[MAXL]; /* array of pointers */
- char *cp;
- int count, i, j, ch;
- extern char *Getbyte();
-
-
- printf("Type in several lines of text, and I will\n");
- printf("print them back out in reverse order.\n");
- printf("(Any blank line ends input):\n");
-
- for (i = 0; i < MAXL; ++i)
- {
- cp = Getbyte();
- cptrs[i] = cp; /* assign address to pointer */
- count = 0;
- while ((ch = getchar()) != '\n') /* gather line */
- {
- *cp = ch;
- cp = Getbyte();
- ++count;
- }
- *cp = '\0';
- if (count == 0) /* all done if blank line */
- break;
- }
- printf("---------<reversed>---------\n");
- for (j = i-1; j >= 0; --j)
- {
- printf("%s\n", cptrs[j]);
- }
- }
-
- char *Getbyte(void)
- {
- char *cp;
-
- if ((cp = sbrk(1)) == (char *)-1)
- {
- printf("Panic: sbrk failed\n");
- exit(1);
- }
- return (cp);
- }
-
-
- REVERSE2.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP08\REVERSE2.C
-
- /* reverse2.c -- demonstrates a pointer to a pointer */
-
- <stdio.h> /* for NULL */
- <malloc.h> /* for size_t */
-
- #define MAXL 20
-
- main()
- {
- char *cptrs[MAXL];
- char **pp; /* pointer to pointer */
- char *cp;
- int count, i, ch;
- extern char *Getbyte();
-
- printf("Type in several lines of text, and I will\n");
- printf("print them back out in reverse order.\n");
- printf("(Any blank line ends input):\n");
-
- for (i = 0; i < MAXL; ++i)
- {
- cp = Getbyte();
- cptrs[i] = cp; /* assign address to pointer */
- count = 0;
- while ((ch = getchar()) != '\n') /* gather line */
- {
- *cp = ch;
- cp = Getbyte();
- ++count;
- }
- *cp = '\0';
- if (count == 0) /* all done if blank line */
- break;
- }
- printf("---------<reversed>---------\n");
- pp = &cptrs[i];
- while (pp >= cptrs)
- {
- printf("%s\n", *(pp--));
- }
- }
-
- char *Getbyte(void)
- {
- char *cp;
-
- if ((cp = sbrk(1)) == (char *)-1)
- {
- printf("Panic: sbrk failed\n");
- exit(1);
- }
- return (cp);
- }
-
-
- RIGHTSTR.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\RIGHTSTR.C
-
- /* rightstr.c -- a C version of BASIC's RIGHT$ */
-
- #include <stdio.h>
-
- char *Rightstr(char *str, int cnt)
- {
- static char *cp = NULL;
- char *malloc();
-
- if (cnt > strlen(str))
- cnt = strlen(str);
- if (cp != NULL)
- free(cp);
- if ((cp = malloc(cnt + 1)) == NULL)
- return (NULL);
- strcpy(cp, str + strlen(str) - cnt);
- return (cp);
- }
-
-
- RINGS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\RINGS.C
-
- /* rings.c -- shoots colored rings */
- /* This program illustrates _remapallpalette() and */
- /* how it can be used to produce the appearance of */
- /* motion. The program is intended for EGA modes 13, */
- /* 14, and 16. */
- /* Program list: rings.c */
- /* If you load graphics.qlb, no program list is needed*/
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- #include <graph.h>
- #define ESC '\033'
-
- long Colors[16] = {_BLACK, _BLUE, _GREEN, _CYAN,
- _RED, _MAGENTA, _BROWN, _WHITE,
- _GRAY, _LIGHTBLUE, _LIGHTGREEN,
- _LIGHTCYAN, _LIGHTRED, _LIGHTMAGENTA,
- _LIGHTYELLOW,_BRIGHTWHITE };
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- struct videoconfig vc;
- float aspect;
- short xmax, ymax;
- long int newpalette[16];
- long int temp;
- int index;
- int hot1 = 1; /* first colored ring */
- int hot2 = 8; /* second colored ring */
- int mode = _ERESCOLOR;
- int ch;
-
- if (argc > 1)
- mode = atoi(argv[1]);
- if (mode < 13)
- {
- fprintf(stderr,"Requires EGA or VGA mode\n");
- exit(1);
- }
- if (_setvideomode(mode) == 0)
- {
- fprintf(stderr,"% d mode unavailable\n", mode);
- exit(2);
- }
- _getvideoconfig(&vc);
- _setlogorg(vc.numxpixels / 2 - 1, vc.numypixels / 2 - 1);
- aspect = (10.0 * vc.numypixels) / (6.5 * vc.numxpixels);
- ymax = vc.numypixels / 2 - 2;
- xmax = ymax / aspect;
- for (index = 2; index < 16; index++)
- newpalette[index] = _LIGHTBLUE;
- newpalette[0] = _GRAY;
- newpalette[hot1] = _RED;
- newpalette[hot2] = _LIGHTRED;
- _remapallpalette(newpalette); /* set initial palette */
- _setcolor(1);
- _ellipse(_GFILLINTERIOR, -xmax, -ymax, xmax, ymax);
- /* draw concentric circles */
- for (index = 2; index < 16; index++)
- {
- xmax /= 1.4;
- ymax /= 1.4;
- _setcolor(index);
- _ellipse(_GFILLINTERIOR, -xmax, -ymax, xmax, ymax);
- }
- do
- {
- while (!kbhit())
- {
- temp = newpalette[15];
- for(index = 15; index > 1; index--)
- newpalette[index] = newpalette[index - 1];
- newpalette[1] = temp;
- _remapallpalette(newpalette);
- hot1 = hot1 % 15 + 1; /* index of colored ring */
- hot2 = hot2 % 15 + 1;
- }
- ch = getch();
- if (ch > '1' && ch < '8') /* reassign colors */
- {
- newpalette[hot1] = Colors[ ch - '0'];
- newpalette[hot2] = Colors[ ch - '0' + 8];
- }
- } while (ch != ESC);
- _clearscreen(_GCLEARSCREEN);
- _setvideomode(_DEFAULTMODE);
- }
-
-
- ROAMSCRN.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP13\ROAMSCRN.C
-
- /* roamscrn.c -- puts text on screen, positions */
- /* cursor with arrow keys, uses F1 */
- /* and F2 to control video inverse. */
- /* program list -- roamscreen.c, scrfun.lib */
- /* user include files -- keys.h, scrn.h */
- /* Note: Activate Screen Swapping On in Debug menu */
- #include <conio.h>
- #include "keys.h"
- #include "scrn.h"
- #define BELL '\a'
- #define ESC '\033'
- #define PAGE 0
-
- char *Heading =
- "Use standard keys to enter text. Use arrow keys to "
- "reposition cursor.\nUse F2 to turn on video inverse "
- "and F1 to turn it off.\nHit the ESC key to quit.\n";
-
- main()
- {
- int ch;
- unsigned char atr = NORMAL;
-
- Clearscr();
- Home();
- printf("%s", Heading);
- while ((ch = getch()) != ESC)
- {
- if (ch == '\r')
- {
- putch('\n');
- putch('\r');
- }
- else if (ch != 0)
- {
- Write_ch_atr(ch, atr, PAGE, 1);
- if (!Cursrt())
- putch(BELL);
- }
- else
- {
- ch = getch();
- switch (ch)
- {
- case F1 : atr = NORMAL; break;
- case F2 : atr = VIDREV; break;
- case UP : Rewrite(atr, PAGE);
- if (!Cursup())
- putch(BELL);
- break;
- case DN : Rewrite(atr, PAGE);
- if (!Cursdn())
- putch(BELL);
- break;
- case LT : Rewrite(atr, PAGE);
- if (!Curslt())
- putch(BELL);
- break;
- case RT : Rewrite(atr, PAGE);
- if (!Cursrt())
- putch(BELL);
- break;
- default : break;
- }
- }
- }
- }
-
-
- ROLO.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP11\ROLO.C
-
- /* rolo.c -- demonstrates pointers to structures */
-
- <stdio.h> /* for NULL and stdin */
- <string.h> /* for strdup() */
-
- #define MAXN 79
- #define MAXCARDS 3
-
- struct cardstruct { /* global pattern */
- char first[MAXN],
- last[MAXN],
- middle[MAXN];
- unsigned long street_no;
- char street[MAXN],
- city[MAXN],
- state[MAXN];
- unsigned long zip;
- unsigned int area;
- unsigned long phone;
- };
-
- struct cardstruct cards[MAXCARDS];
-
- main()
- {
- int i;
-
- for (i = 0; i < MAXCARDS; ++i)
- {
- printf("\n<card %d of %d>\n", i + 1, MAXCARDS);
- Input(&cards[i]);
- }
- for (i = 0; i < MAXCARDS; ++i)
- {
- printf("\n<%d> ", i + 1);
- Showcard(&cards[i]);
- }
- }
-
- Input(struct cardstruct *cardp)
- {
- char *Str_Input();
- long Lint_Input();
-
- strcpy(cardp->first,Str_Input("First Name"));
- strcpy(cardp->last,Str_Input("Last Name"));
- strcpy(cardp->middle,Str_Input("Middle Name"));
- cardp->street_no = Lint_Input("Street Number");
- strcpy(cardp->street,Str_Input("Street"));
- strcpy(cardp->city,Str_Input("City"));
- strcpy(cardp->state,Str_Input("State"));
- cardp->zip = Lint_Input("Zip Code");
- cardp->area = (int)Lint_Input("Area Code");
- cardp->phone = Lint_Input("Phone Number");
- }
-
- char *Str_Input(char *prompt)
- {
- char buf[MAXN + 1], *ptr;
-
- printf("%s: ", prompt);
- if (fgets(buf, MAXN, stdin) == NULL)
- exit(0);
- buf[strlen(buf) - 1] = '\0'; /* strip '\n' */
- if (strlen(buf) == 0)
- exit(0);
- if ((ptr = strdup(buf)) == NULL)
- exit(0);
- return (ptr);
- }
-
- long Lint_Input(char *prompt)
- {
- char buf[MAXN + 1];
- long num;
-
- printf("%s: ", prompt);
- if (fgets(buf, MAXN, stdin) == NULL)
- exit(0);
- if (sscanf(buf, "%ld", &num) != 1)
- exit(0);
- return (num);
- }
-
- Showcard(struct cardstruct *cardptr)
- {
- printf("\n\n");
- printf("%s %s %s\n", cardptr->first, cardptr->middle,
- cardptr->last);
- printf("%ld %s, %s, %s %ld\n", cardptr->street_no,
- cardptr->street, cardptr->city, cardptr->state,
- cardptr->zip);
- printf("(%d) %ld\n", cardptr->area, cardptr->phone);
- }
-
-
- ROLO2.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP11\ROLO2.C
-
- /* rolo2.c -- demonstrates a linked list */
-
- <stdio.h> /* for NULL and stdin */
- <string.h> /* for strdup() */
- <malloc.h> /* for malloc() */
-
- #define MAXN 79
-
- struct cardstruct { /* global pattern */
- char first[MAXN],
- last[MAXN],
- middle[MAXN];
- unsigned long street_no;
- char street[MAXN],
- city[MAXN],
- state[MAXN];
- unsigned long zip;
- unsigned int area;
- unsigned long phone;
- struct cardstruct *nextcard;
- };
-
- main()
- {
- int i;
- struct cardstruct card, *first, *current;
-
- first = (struct cardstruct *)malloc(sizeof(struct cardstruct));
- if(first == NULL)
- exit(1);
- if (Input(&card) != 0)
- exit(1);
- *first = card;
- current = first;
-
- while (Input(&card) == 0)
- {
- current->nextcard =
- (struct cardstruct *)malloc(sizeof(struct cardstruct));
- if(current->nextcard == NULL)
- exit(1);
- current = current->nextcard;
- *current = card;
- }
- current->nextcard = NULL;
-
- Dumplist(first);
- }
-
- Dumplist(struct cardstruct *head)
- {
- do
- {
- Showcard(head);
- } while ((head = head->nextcard) != NULL);
- }
-
- Showcard(struct cardstruct *cardptr)
- {
- printf("\n\n");
-
- printf("%s %s %s\n", cardptr->first, cardptr->middle,
- cardptr->last);
- printf("%ld %s, %s, %s %ld\n", cardptr->street_no,
- cardptr->street, cardptr->city, cardptr->state,
- cardptr->zip);
- printf("(%d) %ld\n", cardptr->area, cardptr->phone);
- }
-
- Input(struct cardstruct *cardp)
- {
- char *Str_Input();
- long Lint_Input();
-
- printf("\n<new card> (Empty first name Quits)\n");
- strcpy(cardp->first,Str_Input("First Name"));
- if (*(cardp->first) == '\0')
- return (1);
- strcpy(cardp->last,Str_Input("Last Name"));
- strcpy(cardp->middle,Str_Input("Middle Name"));
- cardp->street_no = Lint_Input("Street Number");
- strcpy(cardp->street,Str_Input("Street"));
- strcpy(cardp->city,Str_Input("City"));
- strcpy(cardp->state,Str_Input("State"));
- cardp->zip = Lint_Input("Zip Code");
- cardp->area = (int)Lint_Input("Area Code");
- cardp->phone = Lint_Input("Phone Number");
- return (0);
- }
-
- char *Str_Input(char *prompt)
- {
- char buf[MAXN + 1], *ptr;
-
- printf("%s: ", prompt);
- if (fgets(buf, MAXN, stdin) == NULL)
- exit(0);
- buf[strlen(buf) - 1] = '\0'; /* strip '\n' */
- if ((ptr = strdup(buf)) == NULL)
- exit(0);
- return (ptr);
- }
-
- long Lint_Input(char *prompt)
- {
- char buf[MAXN + 1];
- long num;
-
- printf("%s: ", prompt);
- if (fgets(buf, MAXN, stdin) == NULL)
- exit(0);
- if (sscanf(buf, "%ld", &num) != 1)
- num = 0;
- return (num);
- }
-
-
- SADD.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP07\SADD.C
-
- /* sadd.c -- a small adding machine that illustrates */
- /* the need for array bounds checking. */
-
- main()
- {
- int offset = 0, i, result = 0;
- int stack[3];
-
- while (scanf("%d", &stack[offset]) == 1)
- {
- ++offset;
- }
- for (i = 0; i < offset; ++i)
- {
- result += stack[i];
- }
- printf("-------------\n");
- printf("%d\n", result);
-
- }
-
-
- SADD2.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP07\SADD2.C
-
- /* sadd2.c -- a small adding machine that includes */
- /* array bounds checking. */
-
- #define MAXSTAK 3
-
- main()
- {
- int offset = 0, i, result = 0;
- int stack[MAXSTAK];
-
- while (scanf("%d", &stack[offset]) == 1)
- {
- if (++offset >= MAXSTAK)
- {
- printf("Stack Full\n");
- break;
- }
- }
- for (i = 0; i < offset; ++i)
- {
- result += stack[i];
- }
- printf("-------------\n");
- printf("%d\n", result);
-
- }
-
-
- SAVEGRAF.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\SAVEGRAF.C
-
- /* savegraf.c -- uses DMA to save screen of graphics */
- /* characters and attributes */
- /* Program list - savegraf.c, initstuf.c, drawchar.c, */
- /* savescrn.c, scrfun.c */
- /* User include files - scrn.h, keys.h, grafchar.h */
- /* Note: activate Screen Swapping On in Debug menu */
-
-
- #include "grafchar.h"
- unsigned char Grchr[NUMCHARS]; /* to store graphics set */
- void Init_stuff(void);
- void Draw_chars(void);
- void Save_screen(void); /* in savescrn.c */
-
- main()
- {
- int ch;
-
- Init_stuff(); /* initialize vital elements */
- Draw_chars(); /* map keys to graphics characters */
- Setcurs(BOTLINE + 1, 0, PAGE);
- printf("%-80s", "Save screen? <y/n> ");
- Setcurs(BOTLINE + 1, 20, PAGE);
- ch = getche();
- if (ch == 'y' || ch == 'Y')
- Save_screen();
- Setcurs(BOTLINE + 2, 0, PAGE);
- printf("%-80s\n", "BYE!");
- }
-
-
- SAVESCRN.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\SAVESCRN.C
-
- /* savescrn.c -- saves screen, including attribute */
- /* values, in a file */
- /* Uses direct memory access. */
-
- <stdio.h> /* for file-handling */
- #include "scrn.h"
- #include "grafchar.h"
- void Save_screen()
- {
- FILE *save;
- char filename[80];
- unsigned char mode;
- unsigned short char_attr; /* character,attribute */
- int offset;
- VIDMEM screen;
-
- if ((mode = Getvmode()) == TEXTMONO)
- screen = MONMEM;
- else if (mode == TEXTC80 || mode == TEXTBW80)
- screen = CGAMEM;
- else
- exit(1);
- Setcurs(BOTLINE + 1, 0, PAGE);
- printf("Please enter name for save file: ");
- scanf("%s", filename);
- if ((save = fopen(filename,"wb")) == NULL)
- {
- fprintf(stderr,"Can't open %s\n", filename);
- exit(1);
- }
- for (offset = 0; offset < CHARS; offset++)
- {
- char_attr = screen[offset];
- fwrite(&char_attr, 2, 1, save);
- }
- fclose(save);
- }
-
-
- SCANCODE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP13\SCANCODE.C
-
- /* scancode.c -- displays ASCII or scan code */
- /* This program illustrates using getch() to detect */
- /* special keys such as function keys. */
-
- #include <conio.h>
- ESC '\033' /* ESC key */
- main()
- {
- int ch;
-
- printf("Strike keys and see the codes!\n");
- printf("Press the Esc key to quit.\n");
-
- while ((ch = getch()) != ESC)
- {
- if (ch != 0)
- {
- if (ch <= 32) /* control characters */
- printf("^%c has ASCII code %d\n",
- ch + 64, ch);
- else
- printf("%c has ASCII code %d\n", ch, ch);
- }
- else /* ch IS 0 */
- {
- ch = getch(); /* get scan code */
- printf("Scan code is %d\n", ch);
- }
- }
- }
-
-
- SCANLINE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP09\SCANLINE.C
-
- /* scanline.c -- demonstrates how scanf() reads */
- /* the individual words of a line */
-
- #define INTRO \
- "Type in lines of text. They will be printed out\n\
- one word per line, thus demonstrating scanf().\n\
- (Type Ctrl-Z to Quit)\n"
-
- main()
- {
- char buf[512]; /* should be big enough */
-
- printf(INTRO);
-
- /*
- * scanf() returns the number of items
- * its control string matched.
- */
- while (scanf("%s", buf) == 1)
- {
- printf("%s\n", buf);
- }
-
- }
-
-
- SCAPE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\SCAPE.C
-
- /* scape.c -- uses nondefault EGA colors */
- /* If you load graphics.qlb, no program list is needed.*/
-
- #include <stdio.h>
- #include <graph.h>
- #include "egacolor.h"
- #include <stdlib.h>
- #include <conio.h>
- #define SKY (b | B | g)
- #define OCEAN b
- #define SAND (R | g | b)
- #define SUN (R | G | r | g)
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- struct videoconfig vc;
- int mode = _ERESCOLOR;
- short xmax, ymax, sunx, suny, sunsizex, sunsizey;
- float ar;
-
-
- if (argc > 1)
- mode = atoi(argv[1]);
- if (_setvideomode(mode) == 0)
- {
- fprintf(stderr,"mode %d not supported\n", mode);
- exit(1);
- }
- _getvideoconfig(&vc);
- xmax = vc.numxpixels - 1;
- ymax = vc.numypixels - 1;
- sunx = 0.7 * xmax;
- suny = 0.2 * ymax;
- ar = (float)(10 * vc.numypixels) / (6.5 * vc.numxpixels);
- sunsizex = xmax / 30;
- sunsizey = ar * sunsizex;
- _remappalette(1, SKY);
- _remappalette(2, OCEAN);
- _remappalette(3, SAND);
- _remappalette(4, SUN);
- _setcolor(1);
- _rectangle(_GFILLINTERIOR, 0, 0, xmax, 2 * ymax / 5);
- _setcolor(4);
- _ellipse(_GFILLINTERIOR, sunx - sunsizex, suny -
- sunsizey, sunx + sunsizex, suny + sunsizey);
- _setcolor(2);
- _rectangle(_GFILLINTERIOR, 0, 2 * ymax / 5, xmax,
- 2 * ymax / 3);
- _setcolor(3);
- _rectangle(_GFILLINTERIOR, 0, 2 * ymax / 3, xmax, ymax);
- getch();
- _setvideomode(_DEFAULTMODE);
- }
-
-
- SCORE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\SCORE.C
-
- /* score.c -- defines and prints */
- /* int and long vars */
-
- main()
- {
- /* declare some int variables and assign values */
- /* to them in the same statement */
-
- int home = 5, visitors = 2, inning =7, attendance = 31300;
- long total_attendance = 1135477; /* long int */
-
- /* print out the values */
-
- printf("The score after %d innings is \n", inning);
- printf("Home team %d, Visitors %d.\n\n", home, visitors);
- printf("The attendance today is %d.\n", attendance);
- printf("Attendance this year to date is %ld.",
- total_attendance);
- }
-
-
- SCRANGE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP09\SCRANGE.C
-
- /* scrange.c -- illustrates scanf()'s control */
- /* directives */
-
- main()
- {
- char buf[512], /* should be big enough */
- dummy[2]; /* for \n and \0 */
- int num;
-
- do
- {
- printf("Running:\n");
- printf("\tscanf(\"%%d\", &num);\n");
- printf("\tscanf(\"%%[^\\n]\", buf);\n");
- printf("\tscanf(\"%%[\\n]\", dummy);\n");
-
- printf("\nType enough to satisfy this:\n");
- printf("(Set num equal to zero to quit)\n");
-
- scanf("%d", &num);
- scanf("%[^\n]", buf);
- scanf("%[\n]", dummy);
-
- printf("\n\tnum = %d\n", num);
- printf("\tbuf[] = \"%s\"\n", buf);
- printf("\n\n");
-
- } while (num != 0) ;
-
- }
-
-
- SCRFUN.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\SCRFUN.C
-
- /* scrfun.c -- contains several video BIOS calls */
- /* Setcurs() sets the cursor position */
- /* Getcurs() gets the cursor postion */
- /* Setpage() sets the current video page */
- /* Setvmode() sets the video mode */
- /* Clearscr() clears the screen */
- /* Read_ch_atr() reads the character and */
- /* attribute at the cursor */
- /* Write_ch_atr() writes a character and */
- /* attribute at the cursor */
- /* Rewrite() rewrites a screen character */
- /* with a new attribute */
- /* Getvmode() gets the current video mode */
- /* Getpage() gets the current video page */
- /* */
- /* The following functions use Setcurs() to move the */
- /* one position at a time up to a limit. */
- /* Curslt_lim() moves cursor one column left */
- /* Cursrt_lim() moves cursor one column right */
- /* Cursup_lim() moves cursor one line up */
- /* Cursdn_lim() moves cursor one line down */
- /* */
- /* Programs using these functions should include the */
- /* scrn.h file */
-
- #include <dos.h>
- #include "scrn.h"
-
- /* sets cursor to row, column, and page */
- void Setcurs(row, col, page)
- unsigned char row, col, page;
- {
- union REGS reg;
-
- reg.h.ah = SETCURSOR;
- reg.h.dh = row;
- reg.h.dl = col;
- reg.h.bh = page;
- int86(VIDEO, ®, ®);
- }
-
- /* gets current cursor row, column for given page */
- void Getcurs(pr, pc, page)
- unsigned char *pr, *pc, page;
- {
- union REGS reg;
-
- reg.h.ah = GETCURSOR;
- reg.h.bh = page;
- int86(VIDEO, ®, ®);
- *pr = reg.h.dh; /* row number */
- *pc = reg.h.dl; /* column number */
- }
-
-
- /* sets page to given value */
- void Setpage(page)
- unsigned char page;
- {
- union REGS reg;
-
- reg.h.ah = SETPAGE;
- reg.h.al = page;
- int86(VIDEO, ®, ®);
- }
-
- /* sets video mode to given mode */
- void Setvmode(mode)
- unsigned char mode;
- {
- union REGS reg;
-
- reg.h.ah = SETMODE;
- reg.h.al = mode;
- int86(VIDEO, ®, ®);
- }
-
- /* clear the screen */
- void Clearscr()
- {
- union REGS reg;
-
- reg.h.ah = SCROLL;
- reg.h.al = 0;
- reg.h.ch = 0;
- reg.h.cl = 0;
- reg.h.dh = ROWS - 1;
- reg.h.dl = COLS - 1;
- reg.h.bh = NORMAL;
- int86(VIDEO, ®, ®);
- }
-
- /* reads the character and attribute at the cursor */
- /* position on a given page */
- void Read_ch_atr(pc, pa, page)
- unsigned char *pc, *pa;
- unsigned char page;
- {
- union REGS reg;
-
- reg.h.ah = READCHATR;
- reg.h.bh = page;
- int86(VIDEO, ®, ®);
- *pc = reg.h.al; /* character at cursor */
- *pa = reg.h.ah; /* attribute at cursor */
- }
-
- /* writes a given character and attribute at the */
- /* cursor on a given page for num times */
- void Write_ch_atr(ch, atr, page, num)
- unsigned char ch, atr, page;
- unsigned int num;
- {
- union REGS reg;
-
- reg.h.ah = WRITECHATR;
- reg.h.al = ch;
- reg.h.bl = atr;
- reg.h.bh = page;
- reg.x.cx = num;
- int86(VIDEO, ®, ®);
- }
-
- /* rewrites the character at the cursor using */
- /* attribute at */
- void Rewrite(at, page)
- unsigned char at, page;
- {
- unsigned char ch, atr;
-
- Read_ch_atr(&ch, &atr, page);
- Write_ch_atr(ch, at, page, 1);
- }
-
- /* obtains the current video mode */
- unsigned char Getvmode()
- {
- union REGS reg;
-
- reg.h.ah = GETMODE;
- int86(VIDEO, ®, ®);
- return reg.h.al;
- }
-
- /* obtains the current video page */
- unsigned char Getpage()
- {
- union REGS reg;
-
- reg.h.ah = GETMODE;
- int86(VIDEO, ®, ®);
- return reg.h.bh;
- }
-
- /* moves cursor one column left, but not past */
- /* the given limit */
- unsigned char Curslt_lim(limit)
- unsigned char limit;
- {
- unsigned char row, col, page;
- unsigned char status = 1;
-
- Getcurs(&row, &col, page = Getpage());
- if (col > limit)
- Setcurs(row, col - 1, page);
- else
- status = 0;
- return status;
- }
-
- /* moves cursor one column right, but not past */
- /* the given limit */
- unsigned char Cursrt_lim(limit)
- unsigned char limit;
- {
- unsigned char row, col, page;
- unsigned char status = 1;
-
- Getcurs(&row, &col, page = Getpage());
- if (col < limit)
- Setcurs(row, col + 1, page);
- else
- status = 0;
- return status;
- }
-
- /* move cursor one row down, but not past */
- /* the given limit */
- unsigned char Cursup_lim(limit)
- unsigned char limit;
- {
- unsigned char row, col, page;
- unsigned char status = 1;
-
- Getcurs(&row, &col, page = Getpage());
- if (row > limit)
- Setcurs(row - 1, col, page);
- else
- status = 0;
- return status;
- }
-
- /* move cursor one row down, but not past */
- /* the given limit */
- unsigned char Cursdn_lim(limit)
- unsigned char limit;
- {
- unsigned char row, col, page;
- unsigned char status = 1;
-
- Getcurs(&row, &col, page = Getpage());
- if (row < limit)
- Setcurs(row + 1, col, page);
- else
- status = 0;
- return status;
- }
-
-
- SCRFUN.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP13\SCRFUN.C
-
- /* scrfun.c -- contains several video BIOS calls */
- /* Setcurs() sets the cursor position */
- /* Getcurs() gets the cursor postion */
- /* Setpage() sets the current video page */
- /* Setvmode() sets the video mode */
- /* Clearscr() clears the screen */
- /* Read_ch_atr() reads the character and */
- /* attribute at the cursor */
- /* Write_ch_atr() writes a character and */
- /* attribute at the cursor */
- /* Rewrite() rewrites a screen character */
- /* with a new attribute */
- /* Getvmode() gets the current video mode */
- /* Getpage() gets the current video page */
- /* */
- /* The following functions use Setcurs() to move the */
- /* one position at a time up to a limit. */
- /* Curslt_lim() moves cursor one column left */
- /* Cursrt_lim() moves cursor one column right */
- /* Cursup_lim() moves cursor one line up */
- /* Cursdn_lim() moves cursor one line down */
- /* */
- /* Programs using these functions should include the */
- /* scrn.h file */
-
- #include <dos.h>
- #include "scrn.h"
-
- /* sets cursor to row, column, and page */
- void Setcurs(row, col, page)
- unsigned char row, col, page;
- {
- union REGS reg;
-
- reg.h.ah = SETCURSOR;
- reg.h.dh = row;
- reg.h.dl = col;
- reg.h.bh = page;
- int86(VIDEO, ®, ®);
- }
-
- /* gets current cursor row, column for given page */
- void Getcurs(pr, pc, page)
- unsigned char *pr, *pc, page;
- {
- union REGS reg;
-
- reg.h.ah = GETCURSOR;
- reg.h.bh = page;
- int86(VIDEO, ®, ®);
- *pr = reg.h.dh; /* row number */
- *pc = reg.h.dl; /* column number */
- }
-
-
- /* sets page to given value */
- void Setpage(page)
- unsigned char page;
- {
- union REGS reg;
-
- reg.h.ah = SETPAGE;
- reg.h.al = page;
- int86(VIDEO, ®, ®);
- }
-
- /* sets video mode to given mode */
- void Setvmode(mode)
- unsigned char mode;
- {
- union REGS reg;
-
- reg.h.ah = SETMODE;
- reg.h.al = mode;
- int86(VIDEO, ®, ®);
- }
-
- /* clear the screen */
- void Clearscr()
- {
- union REGS reg;
-
- reg.h.ah = SCROLL;
- reg.h.al = 0;
- reg.h.ch = 0;
- reg.h.cl = 0;
- reg.h.dh = ROWS - 1;
- reg.h.dl = COLS - 1;
- reg.h.bh = NORMAL;
- int86(VIDEO, ®, ®);
- }
-
- /* reads the character and attribute at the cursor */
- /* position on a given page */
- void Read_ch_atr(pc, pa, page)
- unsigned char *pc, *pa;
- unsigned char page;
- {
- union REGS reg;
-
- reg.h.ah = READCHATR;
- reg.h.bh = page;
- int86(VIDEO, ®, ®);
- *pc = reg.h.al; /* character at cursor */
- *pa = reg.h.ah; /* attribute at cursor */
- }
-
- /* writes a given character and attribute at the */
- /* cursor on a given page for num times */
- void Write_ch_atr(ch, atr, page, num)
- unsigned char ch, atr, page;
- unsigned int num;
- {
- union REGS reg;
-
- reg.h.ah = WRITECHATR;
- reg.h.al = ch;
- reg.h.bl = atr;
- reg.h.bh = page;
- reg.x.cx = num;
- int86(VIDEO, ®, ®);
- }
-
- /* rewrites the character at the cursor using */
- /* attribute at */
- void Rewrite(at, page)
- unsigned char at, page;
- {
- unsigned char ch, atr;
-
- Read_ch_atr(&ch, &atr, page);
- Write_ch_atr(ch, at, page, 1);
- }
-
- /* obtains the current video mode */
- unsigned char Getvmode()
- {
- union REGS reg;
-
- reg.h.ah = GETMODE;
- int86(VIDEO, ®, ®);
- return reg.h.al;
- }
-
- /* obtains the current video page */
- unsigned char Getpage()
- {
- union REGS reg;
-
- reg.h.ah = GETMODE;
- int86(VIDEO, ®, ®);
- return reg.h.bh;
- }
-
- /* moves cursor one column left, but not past */
- /* the given limit */
- unsigned char Curslt_lim(limit)
- unsigned char limit;
- {
- unsigned char row, col, page;
- unsigned char status = 1;
-
- Getcurs(&row, &col, page = Getpage());
- if (col > limit)
- Setcurs(row, col - 1, page);
- else
- status = 0;
- return status;
- }
-
- /* moves cursor one column right, but not past */
- /* the given limit */
- unsigned char Cursrt_lim(limit)
- unsigned char limit;
- {
- unsigned char row, col, page;
- unsigned char status = 1;
-
- Getcurs(&row, &col, page = Getpage());
- if (col < limit)
- Setcurs(row, col + 1, page);
- else
- status = 0;
- return status;
- }
-
- /* move cursor one row down, but not past */
- /* the given limit */
- unsigned char Cursup_lim(limit)
- unsigned char limit;
- {
- unsigned char row, col, page;
- unsigned char status = 1;
-
- Getcurs(&row, &col, page = Getpage());
- if (row > limit)
- Setcurs(row - 1, col, page);
- else
- status = 0;
- return status;
- }
-
- /* move cursor one row down, but not past */
- /* the given limit */
- unsigned char Cursdn_lim(limit)
- unsigned char limit;
- {
- unsigned char row, col, page;
- unsigned char status = 1;
-
- Getcurs(&row, &col, page = Getpage());
- if (row < limit)
- Setcurs(row + 1, col, page);
- else
- status = 0;
- return status;
- }
-
-
- SCRINV.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP08\SCRINV.C
-
- /* scrinv.c -- using a far pointer to access text */
- /* screen memory */
-
- #define ROWS 25
- #define COLS 80
-
- main()
- {
- int far *screenp;
- int temp, i;
-
- do
- {
- /* use 0xB800000 for EGA or VGA */
- screenp = (int far *)0xB0000000;
-
- for (i = 0; i < ((ROWS*COLS)/2); ++i)
- {
- temp = screenp[i];
- screenp[i] = screenp[(ROWS*COLS)-i-1];
- screenp[(ROWS*COLS)-i-1] = temp;
- }
- } while (getch() != 'Q');
-
- }
-
-
- SCRMENU.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP11\SCRMENU.C
-
- /* scrmenu.c -- uses bit fields to modify your text */
- /* screen's attributes */
-
- char *Choice_Words[] = {
- "Quit",
- "Foreground",
- "Intensity",
- "Background",
- "Blinking"
- };
- enum Choices {
- Quit,
- Foreground,
- Intensity,
- Background,
- Blinking
- };
-
- /* use 0xB800000 for EGA or VGA */
- #define SCR_START (0xB0000000)
- #define SCR_SIZE (25 * 80)
-
- main()
- {
- enum Choices choice;
-
- printf("Select from the following by number:\n");
-
- for (choice = Quit; choice <= Blinking; ++choice)
- {
- printf("%d. %s\n", choice, Choice_Words[choice]);
- }
-
- printf("\nWhich: ");
- do
- {
- choice = getch();
- choice -= '0';
- if (choice < Foreground || choice > Blinking)
- continue;
- Redraw(choice);
- } while (choice != Quit);
-
- }
-
- Redraw(enum Choices field)
- {
- struct screen_char {
- unsigned int character :8,
- foreground :3,
- intensity :1,
- background :3,
- blink :1;
- } scrchar, far *sp, far *ep;
-
- sp = (struct screen_char far *)SCR_START;
- ep = sp + SCR_SIZE;
-
- while (sp < ep)
- {
- scrchar = *sp;
- switch (field)
- {
- case Foreground:
- scrchar.foreground = (scrchar.foreground)? 0 : 7;
- break;
- case Intensity:
- scrchar.intensity = (scrchar.intensity)? 0 : 1;
- break;
- case Background:
- scrchar.background = (scrchar.background)? 0 : 7;
- break;
- case Blinking:
- scrchar.blink = (scrchar.blink)? 0 : 1;
- break;
- }
- *(sp++) = scrchar;
- }
- }
-
-
- SCRREST.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP10\SCRREST.C
-
- /* scrrest.c -- demonstrates read() by restoring */
- /* text screen from any file. */
-
- <stdio.h> /* for stderr */
- <fcntl.h> /* for O_RDONLY | O_BINARY */
-
- #define SCRCHARS (25 * 80)
- int Buf[SCRCHARS];
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- int *cp, *ep;
- int far *sp;
- int fd_in, bytes;
-
- if (argc != 2)
- {
- fprintf(stderr, "usage: scrrest file.scr\n");
- exit(0);
- }
- if ((fd_in = open(argv[1], O_RDONLY | O_BINARY)) < 0)
- {
- fprintf(stderr, "\"%s\": Can't open to read.\n", argv[1]);
- exit(1);
- }
- /* Read it. */
- bytes = read(fd_in, Buf, SCRCHARS * 2);
- if (bytes < 0)
- {
- fprintf(stderr, "\"%s\": Error Reading.\n", argv[1]);
- exit(1);
- }
- if (bytes == 0)
- {
- fprintf(stderr, "\"%s\": Empty File.\n", argv[1]);
- exit(1);
- }
- /* Copy the buffer to screen memory. */
- ep = &Buf[bytes / 2];
- cp = Buf;
-
- /* use 0xB800000 for EGA or VGA */
- sp = (int far *)(0xB0000000);
- for (; cp < ep; ++cp, ++sp)
- *sp = *cp;
- }
-
-
- SCRSAVE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP10\SCRSAVE.C
-
- /* scrsave.c -- demonstrates write() by saving the */
- /* text screen to a file. */
-
- <stdio.h> /* for stderr */
- <fcntl.h> /* for O_CREAT | O_BINARY */
- <sys\types.h> /* for stat.h */
- <sys\stat.h> /* for S_IREAD | S_IWRITE */
-
- #define SCRCHARS (25 * 80)
- int Buf[SCRCHARS];
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- int *cp, *ep, fname[16];
- int far *sp;
- int fd_out, bytes;
-
- if (argc != 2)
- {
- fprintf(stderr, "usage: scrsave file\n");
- exit(0);
- }
- if (strlen(argv[1]) > 8)
- {
- fprintf(stderr, "\"%s\": File name too long.\n", argv[1]);
- exit(1);
- }
- strcpy(fname, argv[1]);
- strcat(fname, ".SCR");
- if (access(fname, 0) == 0)
- {
- fprintf(stderr, "\"%s\": Won't overwrite.\n", fname);
- exit(1);
- }
- if ((fd_out = open(fname, O_WRONLY|O_CREAT|O_BINARY,
- S_IREAD|S_IWRITE)) < 0)
- {
- fprintf(stderr, "\"%s\": Can't create.\n", fname);
- exit(1);
- }
- /* Copy the screen into a near buffer. */
- ep = &Buf[SCRCHARS - 1];
- cp = Buf;
- /* use 0xB800000 for EGA or VGA */
- sp = (int far *)(0xB0000000);
- for (; cp < ep; ++cp, ++sp)
- *cp = *sp;
- /* Write it. */
- bytes = write(fd_out, Buf, SCRCHARS * 2);
- if (bytes != SCRCHARS * 2)
- {
- fprintf(stderr, "\"%s\": Error writing.\n", fname);
- exit(1);
- }
- }
-
-
- SETCURS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP13\SETCURS.C
-
- /* setcurs.c -- moves cursor, checks out Setcurs() */
- #include <dos.h>
- #include <stdio.h>
- #define VIDEO 0x10
- #define SETCURSOR 2
- void Setcurs(unsigned char, unsigned char,
- unsigned char);
- main()
- {
- int row, col;
-
- printf("Enter row and column: (q to quit)\n");
- while (scanf("%d %d", &row, &col) == 2)
- {
- Setcurs(row, col, 0);
- printf("Enter row and column: (q to quit)");
- }
- }
-
- /* Setcurs() -- sets cursor to row, column, and page */
- void Setcurs(row, col, page)
- unsigned char row, col, page;
- {
- union REGS reg;
-
- reg.h.ah = SETCURSOR;
- reg.h.dh = row;
- reg.h.dl = col;
- reg.h.bh = page;
- int86(VIDEO, ®, ®);
- }
-
-
- SHIFTADD.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\SHIFTADD.C
-
- /* shiftadd.c -- shift and add numbers */
-
- main()
- {
- int x = 0x12;
- int y;
-
- y = x << 8 + 2;
- printf("y is 0x%x\n", y);
- }
-
-
-
- SHORTIF.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP05\SHORTIF.C
-
- /* shortif.c -- shows 'shorthand' IF / ELSE */
- /* -- gets absolute value of number */
-
- main()
- {
- int num, pos, abs;
- printf("Enter a whole number: ");
- scanf("%d", &num);
-
- pos = (num >= 0); /* is number positive? */
-
- abs = (pos) ? num : -num; /* assigns negative of */
- /* number if number is negative */
- if (pos)
- printf ("The number is positive.\n");
- else
- printf("The number is negative.\n");
- printf("Absolute value of number is: %d\n", abs);
- }
-
-
- SHOW2.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP09\SHOW2.C
-
- /* show2.c -- shows how to use main()'s envp */
-
- <stdio.h> /* for NULL */
-
- main(argc, argv, envp)
- int argc;
- char *argv[], *envp[];
- {
- int i;
-
- printf("argc = %d\n", argc);
- printf("\n");
-
- for (i = 0; i < argc; ++i)
- {
- printf("argv[%d] -> \"%s\"\n", i, argv[i]);
- }
- printf("argv[%d] -> NULL\n", i);
- printf("\n");
-
- for (i= 0; envp[i] != NULL; ++i)
- {
- printf("envp[%d] -> \"%s\"\n", i, envp[i]);
- }
- printf("envp[%d] -> NULL\n", i);
-
- }
-
-
- SHOWARGS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP09\SHOWARGS.C
-
- /* showargs.c -- shows how to access the arguments */
- /* passed to main() */
-
- <stdio.h> /* for NULL */
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- int i;
-
- printf("argc = %d\n", argc);
- printf("\n");
-
- for (i = 0; i < argc; ++i)
- {
- printf("argv[%d] -> \"%s\"\n", i, argv[i]);
- }
- printf("argv[%d] -> NULL\n", i);
- printf("\n");
-
- }
-
-
- SHOWCODE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP13\SHOWCODE.C
-
- /* showcode.c -- shows ASCII and scan codes for */
- /* keystrokes */
- /* Note: Set Screen Swapping On in the Debug menu. */
- #include <stdio.h>
- #include <dos.h>
- KEYINTR 0x16 /* keyboard read interrupt */
- GETCHAR 0 /* read scancode function */
- ESC '\033' /* escape key */
- struct SCANCODE {
- unsigned char ascii; /* ascii code */
- unsigned char scan; /* scan code */
- };
- struct SCANCODE Readkey();
-
- main()
- {
- struct SCANCODE keys;
-
- printf("Press keys to see their scancodes. ");
- printf("Press the Esc key to quit.\n");
- do {
- keys = Readkey();
- if (keys.ascii > 0 && keys.ascii < 040)
- printf("^%c: ascii = %3d, scan = %3d\n",
- keys.ascii + 0100, keys.ascii,
- keys.scan);
- else if (keys.ascii >= 40)
- printf(" %c: ascii = %3d, scan = %3d\n",
- keys.ascii, keys.ascii, keys.scan);
- else
- printf(" : ascii = %3d, scan = %3d\n",
- keys.ascii, keys.scan);
- } while (keys.ascii != ESC);
- }
-
- struct SCANCODE Readkey()
- {
- union REGS reg;
- struct SCANCODE scancode;
-
- reg.h.ah = GETCHAR;
- int86(KEYINTR, ®, ®);
- scancode.ascii = reg.h.al;
- scancode.scan = reg.h.ah;
- return (scancode);
- }
-
-
- SPECS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\SPECS.C
-
- /* specs.c -- shows printf() format */
- /* specifiers for numbers */
-
- main()
- {
- int i = 122; /* ASCII code for 'z' */
- long l = 93000000; /* distance to Sun (miles) */
- float f = 192450.88; /* someone's bottom line */
- double d = 2.0e+030; /* mass of Sun (kg.) */
-
- printf("%d\n", i); /* integer as decimal */
- printf("%x\n", i); /* integer as hex */
- printf("%ld\n", l); /* long */
- printf("%f\n", f); /* float as decimal */
- printf("%e\n", f); /* float as exponential */
- printf("%f\n", d); /* double as decimal */
- printf("%d\n", d); /* double as exponential */
- }
-
-
- SQUARE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP08\SQUARE.C
-
- /* square.c -- a quiz to demonstrate passing */
- /* pointers and addresses in functions */
-
- main()
- {
- int val, count, guess;
-
- for (count = 1; count < 255; ++count)
- {
- val = count;
- printf("\nWhat is the square of %d?\n", val);
- if (scanf("%d", &guess) != 1)
- return(0); /* non-number exits */
-
- if(Square(&val) != 0) /* pass val's address */
- {
- printf("Range Error\n");
- exit(1);
- }
- if (val != guess)
- printf("Wrong. It is %d.\n", val);
- else
- printf("Right!\n");
- printf("Continue? ");
- if (getche() != 'y')
- break;
- }
- }
-
- int Square(int *where)
- {
- if (*where > 181 || *where < -181)
- return (-1);
- *where = (*where) * (*where);
- return (0);
- }
-
-
- SQUARE2.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP08\SQUARE2.C
-
- /* LISTING 8-2 */
-
- /* square.c -- A quiz to demonstrate passing */
- /* pointers and addresses in functions. */
-
- #include <stdio.h>
-
- main()
- {
- int val, count, guess;
-
- for (count = 1; count < 255; ++count)
- {
- val = count;
- printf("\nWhat is the square of %d?\n", val);
- if (scanf(" %d", &guess) != 1)
- return(0); /* non-number exits */
-
- if(Square(&val) != 0) /* pass val's address */
- {
- printf("Range Error\n");
- exit(1);
- }
-
- if (val != guess)
- printf("Wrong. It is %d.\n", val);
- else
- printf("Right!\n");
-
-
- printf("Continue? ");
- if (getche() != 'y')
- break;
- }
- return (0);
- }
-
- int Square(int *where)
- {
- if (*where > 181 || *where < -181)
- return (-1);
- *where = (*where) * (*where);
- return (0);
- }
-
-
- STATIC.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP06\STATIC.C
-
- /* static.c -- demonstrates a static variable */
- /* that holds count of lines, */
- /* words, and characters */
-
- main()
- {
- void countline();
- printf("Type some lines of text.\n");
- printf("Start a line with a . to quit.\n\n");
-
- while (getche() != '.')
- countline(); /* accumulate word and */
- /* line counts */
- }
-
- void countline()
- {
- static int words = 0; /* static variables */
- static int chars = 0;
- char ch;
- ++chars; /* count char typed when */
- /* function was called */
-
- while ((ch = getche()) != '\r')
- {
- ++chars;
- if (ch == ' ')
- ++words;
- }
- ++words; /* count last word */
-
- printf("\nWords so far %d. Chars. so far %d\n", words, chars);
- }
-
-
- STRINGS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\STRINGS.C
-
- /* strings.c -- shows two ways to print */
- /* a string with printf() */
-
- main()
- {
- printf("This uses a string literal by itself\n");
- printf("%s", "This plugs the literal into %s\n");
- }
-
-
- STRINGS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP10\STRINGS.C
-
- /* strings.c -- opens a file and searches it for */
- /* possible strings */
-
- <stdio.h> /* for FILE, BUFSIZ & EOF */
- <ctype.h> /* for isprint() */
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- FILE *fp;
- char buf[BUFSIZ];
- int ch, count;
-
- if (argc != 2)
- {
- fprintf(stderr, "usage: strings file\n");
- exit(1);
- }
- if ((fp = fopen(argv[1], "rb")) == NULL)
- {
- fprintf(stderr, "Can't open %s\n", argv[1]);
- exit(1);
- }
-
- count = 0;
- while ((ch = fgetc(fp)) != EOF)
- {
- if (! isprint(ch) || count >= (BUFSIZ - 1))
- {
- if (count > 5)
- {
- buf[count] = 0;
- puts(buf);
- }
- count = 0;
- continue;
- }
- buf[count++] = ch;
- }
- }
-
-
- STRIO.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP13\STRIO.C
-
- /* strio.c -- uses cgets() and cputs() */
- /* program list -- strio.c (cgets() not in core library) */
- #include <conio.h>
- #define MAXSIZE 6
- main()
- {
- char store[MAXSIZE + 2];
-
- store[0] = MAXSIZE; /* put limit in first element */
- cputs("What's your name?\n\r");
- cgets(store);
- cputs("\n\rI'll remember you, ");
- cputs(store + 2);
- cputs("!\n\r");
- }
-
-
- STRPOOL.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP09\STRPOOL.C
-
- /* strpool.c -- dumps the string pool to show how */
- /* quoted strings are stored */
-
- #define PHRASE \
- "This is one long sentence that the compiler \
- combines into a single string."
-
- char Start[] = "start";
- char Long_phrase[] = PHRASE;
- char Short_phrase[] = "This is a short phrase";
- char Cent_string[] = "\x9b";
-
- main()
- {
- static char local_phrase[] = "This is local";
- char *cp;
-
- printf("Dump of the string pool:\n");
- printf("-----------------------\n");
-
- printf("\""); /* print leading quote */
-
- /*
- * Note that the address of a string can be
- * assigned to a pointer: cp = Start
- */
- for (cp = Start; *cp != '^'; ++cp)
- {
- if (*cp == '\0') /* print '\0' as a quote */
- printf("\"\n\"");
- else if (*cp == '\n' ) /* print '\n' as '\' 'n' */
- printf("\\n");
- else
- printf("%c", *cp);
- }
- printf("^"); /* marks end */
- }
-
-
- SUMNUMS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\SUMNUMS.C
-
- /* sumnums.c -- type mismatch in function arguments */
- /* No function prototyping */
-
- int sums();
-
- main()
- {
- float a = 10.0;
- float b = 20.0;
- int c;
-
- c = sums(a, b);
- printf("sum of %.1f and %.1f is %d\n", a, b, c); ;
- }
-
- int sums(x, y)
- int x, y;
- {
- return (x + y);
- }
-
-
-
- SUMNUMS2.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\SUMNUMS2.C
-
- /* sumnums2.c -- type mismatch in function arguments */
- /* Function prototyping */
-
- int sums(int, int);
- main()
- {
- float a = 10.0;
- float b = 20.0;
- int c;
-
- c = sums(a, b);
- printf("sum of %.1f and %.1f is %d\n", a, b, c);
- }
- int sums(x, y)
- int x, y;
- {
- return ( x + y);
- }
-
-
-
- SWITCH.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP05\SWITCH.C
-
- /* switch.c -- demonstrates switch statement */
- /* prints values according */
- /* to user's choice */
-
- <math.h> /* for sqrt() */
- #define TRUE 1
- main()
- {
- char choice; /* routine wanted by user */
- int number; /* number entered by user */
-
- while (TRUE) /* endless loop */
- {
- printf("\nSelect value wanted:\n");
- printf("o = octal h = hex s = square\n");
- printf("r = square root q = quit: ");
- choice = getche(); printf("\n");
-
- if (choice == 'q')
- break; /* exits WHILE loop; ends program */
-
- /* rest of program executed if base <> 'q' */
- printf("Enter a whole number: ");
- scanf("%d", &number);
-
- switch (choice) /* print according to */
- /* choice requested */
- {
- case 'o': /* print octal */
- printf("Result: %o\n", number);
- break; /* break here in each case */
- /* exits the switch statement */
-
- case 'h': /* print hex */
- printf("Result: %x\n", number);
- break;
-
- case 's': /* square */
- printf("Result: %d\n", number * number);
- break;
-
- case 'r': /* square root */
- printf("Result: %f\n", sqrt(number) );
- break;
-
- default:
- printf("Choice must be o, h, s, r, or q\n");
- }
- }
- }
-
-
- TABLE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP04\TABLE.C
-
-
- /* TABLE.C -- prints square root, square, and cube */
- /* for the numbers 1 thru 9 */
-
- <math.h> /* include math functions so we */
- /* can do square root */
-
- main()
- {
- int i;
- printf("i\t sqrt(i)\tsquare(i)\tcube(i)\n\n");
- for (i = 1; i < 10; i++)
- /* beginning of body of loop */
- {
- printf("%d\t", i);
- printf("%f\t", sqrt(i));
- printf("%d\t\t", i * i);
- printf("%d\n", i * i * i);
- }
- /* end of body of loop */
- }
-
-
-
- TABS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\TABS.C
-
- /* tabs.c -- shows formatting with the \t */
- /* tab escape sequence */
-
- main()
- {
- int q1 = 338, q2 = 57, q3 = 1048, q4 = 778,
- /* quantity in bin */
- t1 = 6, t2 = 8, t3 = 12, t4 = 16;
- /* threads per inch */
-
- float s1 = 0.250, s2 = 0.500, s3 = 0.750, s4 = 1.0;
- /* size in inches */
-
- /* print table header */
- printf("number\t\t size\t\t threads\n");
- printf("in bin\t\t (inches)\t per inch\n\n");
-
- /* print lines of table */
- printf("%d\t\t %f\t %d\n", q1, s1, t1);
- printf("%d\t\t %f\t %d\n", q2, s2, t2);
- printf("%d\t\t %f\t %d\n", q3, s3, t3);
- printf("%d\t\t %f\t %d\n", q4, s4, t4);
- }
-
-
- TEST.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\TEST.C
-
- /* test.c -- test the routines in basic.lib */
- /* Program list: test.c and basic.lib */
-
- #include <stdio.h>
-
- main()
- {
- static char string[] = "This is a test.";
- char *cp, *Leftstr(), *Midstr(), *Rightstr();
-
- printf("Testing: \"%s\"\n", string);
-
- if ((cp = Leftstr(string, 4)) == NULL)
- {
- printf("Error in Leftstr()\n");
- exit(1);
- }
- printf("Leftstr() returned: \"%s\"\n", cp);
-
- if ((cp = Midstr(string, 4, 5)) == NULL)
- {
- printf("Error in Midstr()\n");
- exit(1);
- }
- printf("Midstr() returned: \"%s\"\n", cp);
-
- if ((cp = Rightstr(string, 5)) == NULL)
- {
- printf("Error in Rightstr()\n");
- exit(1);
- }
- printf("Rightstr() returned: \"%s\"\n", cp);
- }
-
-
- TESTER.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP16\TESTER.C
-
- /* tester.c -- demonstrates the assert() macro */
- /* Program list: tester.c (to link math functions) */
-
- #include <assert.h>
- #include <stdio.h>
- #include <math.h>
- main()
- {
- float s1 = 3.0;
- float s2 = 4.0;
- float sumsq;
- float hypot;
-
- sumsq = s1*s1 - s2*s2;
- assert(sumsq >= 0);
- hypot = sqrt(sumsq);
- printf("hypotenuse is %.2f\n", hypot);
- }
-
-
- TEXED.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP12\TEXED.C
-
- /* texed.c -- main entry point to the editor; the */
- /* menu and signal handlers are here */
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- char ch;
-
- while (1)
- {
- printf("\nTexEd Main Menu\n");
- printf("Select from:\n");
- printf("0) Quit\n\n");
- printf("1) Load File\n");
- printf("2) Save File\n");
- printf("3) Edit File\n");
- printf("Which: ");
- do
- {
- ch = getch();
- ch -= '0';
- } while (ch < 0 || ch > 3);
- printf("%d\n\n", (int)ch);
- switch(ch)
- {
- case 0: exit(0);
- case 1: Load_file(); break;
- case 2: Save_file(); break;
- case 3: Edit_file(); break;
- }
- }
- }
-
-
- TIMER.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP04\TIMER.C
-
-
- /* TIMER.C -- uses do loop to */
- /* check elapsed time */
-
- #include <time.h>
-
- main()
- {
- long start, end, /* starting and ending times */
- /* measured in seconds since */
- /* Jan. 1, 1970 */
- ltime; /* used to get val from time function */
- int seconds; /* elapsed time to be set */
-
- printf("QuickC Egg Timer\n");
- printf("Enter time to set in seconds: ");
- scanf("%d", &seconds);
- start = time(<ime); /* get system elapsed seconds */
- /* since 1-1-70 */
- end = start + seconds; /* calculate alarm time */
-
- do
- ; /* null statement for loop body */
- while (time(<ime) < end); /* wait for alarm time */
-
- printf("Time's Up!\a\a\a\n");
- }
-
-
-
- TIMER2.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP06\TIMER2.C
-
- /* timer2.c -- interval timer */
- /* calls delay(), uses beep() */
-
- main()
- {
- /* function declarations */
- void beep (times);
- void delay (seconds);
-
- /* variable declarations */
- int seconds, interval, tick;
-
- printf("Set for how many seconds? ");
- scanf("%d", &seconds);
- printf("Interval to show in seconds? ");
- scanf("%d", &interval);
- printf("Press a key to start timing\n");
- getch();
-
- tick = 0; /* run "clock" for */
- while (tick < seconds) /* time specified */
- {
- delay(interval); /* wait interval seconds */
- tick += interval;
- printf("%d\n", tick);
- beep(1);
- }
- beep(3);
- }
-
- void delay(seconds)
- /* wait for number of seconds specified */
- /* see TIMER.C in chapter 4 for details */
- /* on the library function time(). */
-
- int seconds; /* parameter declaration */
- {
- /* variable declarations */
- long start, end, /* starting and ending times */
- /* measured in seconds since */
- /* Jan. 1, 1970 */
- ltime; /* used to get val from time function */
-
- start = time(<ime); /* get system elapsed seconds */
- /* since 1-1-70 */
- end = start + seconds; /* calculate alarm time */
-
- do
- ; /* null statement for loop body */
- while (time(<ime) < end); /* wait for end of time */
- }
-
- void beep(times)
- /* parameter declaration */
- int times;
- {
- /* variable declaration */
- int count;
-
-
- /* check that parameter is between 1 and 4 */
- if ((times < 1) || (times > 4))
- {
- printf("Error in beep(): %d beeps specified.\n",
- times);
- printf("Specify one to four beeps");
- }
- else /* sound the beeps */
- for (count = 1; count <= times; count++)
- printf("\a"); /* "alert" escape sequence */
- }
-
-
- TINY.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\TINY.C
-
- /* tiny.c -- the smallest possible C */
- /* program with comments */
-
- main() /* function name and argument list */
- {
- /* function definition in braces */
- }
-
-
- TODAY.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP11\TODAY.C
-
- /* today.c -- demonstrates using enum */
-
- main()
- {
- enum week_days {
- monday = 1, /* start with 1 */
- tuesday,
- wednesday,
- thursday,
- friday,
- saturday,
- sunday
- } pay_day;
-
- static char *day_names[] = {
- "",
- "monday",
- "tuesday",
- "wednesday",
- "thursday",
- "friday",
- "saturday",
- "sunday"
- };
-
- printf("What day do you want to be paid on?\n");
-
- for (pay_day = monday; pay_day <= sunday; ++pay_day)
- {
- printf("%d. %s\n", pay_day, day_names[pay_day]);
- }
-
- printf("Which (%d-%d): ", monday, sunday);
-
- do
- {
- pay_day = getch();
- pay_day -= '0';
- } while (pay_day < monday || pay_day > sunday);
-
- printf("%d\n\n", pay_day);
-
- printf("You selected %s\n", day_names[pay_day]);
-
- }
-
-
- TOTAL.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP08\TOTAL.C
-
- /* total.c -- how to build an array on the fly */
-
- <stdio.h> /* for NULL */
- <malloc.h> /* for size_t */
-
- main()
- {
- int *iptr, count = 0, i, total;
- size_t bytes = sizeof(int);
-
- /* Start the array with room for one value. */
- if ((iptr = malloc(bytes)) == NULL)
- {
- printf("Oops, malloc failed\n");
- exit(1);
- }
-
- printf("Enter as many integer values as you want.\n");
- printf("I will build an array on the fly with them.\n");
- printf("(Any non-number means you are done.)\n");
-
- while (scanf("%d", &iptr[count]) == 1)
- {
- ++count;
- /* Enlarge the array. */
- if ((iptr = realloc(iptr,bytes*(count+1))) == NULL)
- {
- printf("Oops, realloc failed\n");
- exit(1);
- }
- }
- total = 0;
- printf("You entered:\n");
- for (i = 0; i < count; i++)
- {
- printf("iptr[%d] = %d\n", i, iptr[i]);
- total += iptr[i];
- }
- printf("\nTotal: %d\n", total);
- return (0);
- }
-
-
- TOTAL2.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP08\TOTAL2.C
-
- /* total2.c -- how to build an array on the fly */
- /* using sbrk() */
-
- <stdio.h> /* for NULL */
- <malloc.h> /* for size_t */
-
- main()
- {
- int *iptr, count = 0, i, total;
- size_t bytes = sizeof(int);
-
- /* Start the array with room for one value. */
- iptr = sbrk(0);
- if (sbrk(bytes) == (int *)-1)
- {
- printf("Oops, sbrk failed\n");
- exit(1);
- }
-
- printf("Enter as many integer values as you want.\n");
- printf("I will build an array on the fly with them.\n");
- printf("(Any non-number means you are done.)\n");
-
- while (scanf("%d", &iptr[count]) == 1)
- {
- ++count;
- /* Enlarge the array. */
- if (sbrk(bytes) == (int *)-1)
- {
- printf("Oops, sbrk failed\n");
- exit(1);
- }
- }
- total = 0;
- for (i = 0; i < count; i++)
- total += iptr[i];
- /* just print the total this time */
- printf( "%d\n", total);
- }
-
-
- TRUTH.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\TRUTH.C
-
- /* truth.c -- shows logical operators */
-
- main()
- {
- printf("1 AND 1 is %d\n", 1 && 1);
- printf("1 AND 0 is %d\n", 1 && 0);
- printf("0 AND 0 is %d\n", 0 && 0);
- printf("1 OR 1 is %d\n", 1 || 1);
- printf("1 OR 0 is %d\n", 1 || 0);
- printf("0 OR 0 is %d\n", 0 || 0);
- }
-
-
- TTT.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP07\TTT.C
-
- /* ttt.c -- a tic-tac-toe game demonstrates */
- /* passing two-dimensional arrays */
- /* to functions */
-
- main()
- {
- static char board[3][3] = {
- { '-', '-', '-' },
- { '-', '-', '-' },
- { '-', '-', '-' },
- };
- int row, col, ch;
- extern char Check_winner();
- extern void Make_move(), Draw_field();
-
- printf("You are X and make the first move.\n");
- while (1)
- {
- printf("Specify coordinate for your X.\n");
- printf("(eg, as a2, or Q to quit)\n");
-
- /* Print the square. */
- Draw_field(board);
-
- /* Input the user's coordinates. */
- if ((row = getch()) == 'Q')
- exit(0);
- row -= 'a';
- col = getch() - '1';
-
- /* Check for a legal move. */
- if (row < 0 || row > 2 || col < 0 || col > 2)
- {
- printf("Bad Square Specification\n\n");
- continue;
- }
- if (board[row][col] != '-')
- {
- printf("Sorry, Square Occupied\n\n");
- continue;
- }
-
- /* Make the move. */
- board[row][col] = 'X';
- if ((ch = Check_winner(board)) != '-' || ch == 't')
- break;
- Make_move(board);
- if ((ch = Check_winner(board)) != '-' || ch == 't')
- break;
- }
- Draw_field(board);
- if (ch == 't')
- printf("It's a tie!\n");
- else if (ch == 'X')
- printf("You win!\n");
- else
- printf("I win!\n");
- }
-
- char Check_winner(char field[][3])
- {
- int row, col;
-
- for (row = col = 0; row < 3; ++row, ++col)
- {
- if (field[row][0] != '-' /* horizontal */
- && field[row][0] == field[row][1]
- && field[row][1] == field[row][2] )
- {
- return(field[row][0]);
- }
- if (field[0][col] != '-' /* vertical */
- && field[0][col] == field[1][col]
- && field[1][col] == field[2][col] )
- {
- return(field[0][col]);
- }
- }
- if (field[0][0] != '-' /* right diagonal */
- && field[0][0] == field[1][1]
- && field[1][1] == field[2][2] )
- {
- return(field[0][0]);
- }
- if (field[0][2] != '-' /* left diagonal */
- && field[0][2] == field[1][1]
- && field[1][1] == field[2][0] )
- {
- return(field[0][2]);
- }
-
- for (row = 0; row < 3; ++row) /* any moves left */
- {
- for (col = 0; col < 3; ++col)
- {
- if (field[row][col] == '-')
- {
- return('-');
- }
- }
- }
- return ('t');
- }
-
- void Make_move(char field[3][3])
- {
- int row, col;
-
- for (row = 2; row >= 0; --row)
- {
- for (col = 2; col >= 0; --col)
- {
- if (field[row][col] == '-')
- {
- field[row][col] = 'O';
- return;
- }
- }
- }
- }
-
- void Draw_field(char field[][3])
- {
- int row, col;
-
- printf("\n 1 2 3\n\n");
- for (row = 0; row < 3; ++row)
- {
- printf("%c ", 'a'+row);
- for (col = 0; col < 3; ++col)
- {
- printf(" %c ", field[row][col] );
- }
- printf("\n");
- }
- printf("\n");
- }
-
-
- UDEMO.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP11\UDEMO.C
-
- /* udemo.c -- demonstrates a union at work */
-
- #include <stdio.h>
-
- char *Strings[6] = {
- "Quit",
- "line of text",
- "floating point double value",
- "long integer value",
- "floating point value",
- "integer value"
- };
-
- struct Unitstruct {
- union {
- char wtype[BUFSIZ];
- double dtype;
- long ltype;
- float ftype;
- int itype;
- } manyu;
- int type_in_union;
- };
-
- main()
- {
- struct Unitstruct one_of_many;
-
- while ((one_of_many.type_in_union = Menu()) != 0)
- {
- Inputval(&one_of_many);
- Printval(&one_of_many);
- }
- }
-
- Inputval(struct Unitstruct *one_of_many)
- {
- printf("\nEnter a %s: ", Strings[one_of_many->type_in_union]);
- switch(one_of_many->type_in_union)
- {
- case 1:
- fgets(one_of_many->manyu.wtype, BUFSIZ, stdin);
- break;
- case 2:
- scanf("%lf", &(one_of_many->manyu.dtype));
- while (getchar() != '\n');
- break;
- case 3:
- scanf("%ld", &(one_of_many->manyu.ltype));
- while (getchar() != '\n');
- break;
- case 4:
- scanf("%f", &(one_of_many->manyu.ftype));
- while (getchar() != '\n');
- break;
- case 5:
- scanf("%i", &(one_of_many->manyu.itype));
- while (getchar() != '\n');
- break;
- }
- }
-
- Printval(struct Unitstruct *one_of_many)
- {
- printf("The %s you entered\nwas: ", Strings[one_of_many->type_in_union]);
- switch (one_of_many->type_in_union)
- {
- case 1:
- fputs(one_of_many->manyu.wtype, stdout);
- break;
- case 2:
- printf("%lf", one_of_many->manyu.dtype);
- break;
- case 3:
- printf("%ld", one_of_many->manyu.ltype);
- break;
- case 4:
- printf("%f", one_of_many->manyu.ftype);
- break;
- case 5:
- printf("%i", one_of_many->manyu.itype);
- break;
- }
- printf("\n\n");
- }
-
- Menu()
- {
- int i;
- char ch;
-
- for (i = 0; i < 6; ++i)
- {
- printf("%d) %s\n", i, Strings[i]);
- }
- printf("Which: ");
- do
- {
- ch = getch();
- } while (ch < '0' || ch > '5');
- printf("%c\n", ch);
- return (ch - '0');
- }
-
-
- UNDOVER.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP07\UNDOVER.C
-
- /* undover.c -- illustrates the effect of underinitializing and */
- /* overinitializing arrays. */
-
- int Primes[6] = { 1, 2, 3, 5, 7, 11 };
- #define NUMP (sizeof(Primes)/sizeof(int))
-
- main()
- {
- int i;
-
- printf("The first %d primes are: ", NUMP);
- for (i = 0; i < NUMP; ++i)
- {
- printf("%d ", Primes[i]);
- }
- printf("\n");
- }
-
-
- UPITY.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP10\UPITY.C
-
- /* upity.c -- makes an uppercase copy of a file using */
- /* fread() and fwrite() */
-
- <string.h> /* for strrchr() */
- <stdio.h> /* for NULL */
- <malloc.h> /* for malloc() */
- <ctype.h> /* for isupper() */
-
- #define HUNK 512
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- char *cp, newname[128], *np;
- FILE *fp;
- int hunks = 0, bytes = 0, totbytes = 0;
- int i;
- if (argc != 2)
- {
- printf("usage: upity file\n");
- exit(1);
- }
-
- if ((fp = fopen(argv[1], "rb")) == NULL)
- {
- printf("\"%s\": Can't open.\n", argv[1]);
- exit(1);
- }
- if ((cp = malloc(HUNK)) == NULL)
- {
- printf("Malloc Failed.\n");
- exit(1);
- }
-
- while ((bytes = fread(cp + (HUNK * hunks), 1, HUNK, fp)) == HUNK)
- {
- totbytes += bytes;
- ++hunks;
- if ((cp = realloc(cp, HUNK + (HUNK * hunks))) == NULL)
- {
- printf("Realloc Failed.\n");
- exit(1);
- }
- }
- if (bytes < 0)
- {
- printf("\"%s\": Error Reading.\n", argv[1]);
- exit(1);
- }
- totbytes += bytes;
-
- for (i = 0; i < totbytes; ++i)
- if (islower(cp[i]))
- cp[i] = toupper(cp[i]);
-
- (void)fclose(fp);
-
- if ((np = strrchr(argv[1], '.')) != NULL)
- *np = '\0';
- strcpy(newname, argv[1]);
- strcat(newname, ".up");
- if ((fp = fopen(newname, "wb")) == NULL)
- {
- printf("\"%s\": Can't open.\n", argv[1]);
- exit(1);
- }
-
- if (fwrite(cp, 1, totbytes, fp) != totbytes)
- {
- printf("\"%s\": Error writing.\n", argv[1]);
- exit(1);
- }
-
- }
-
-
- VARADDRS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\VARADDRS.C
-
- /* varaddrs.c -- use & operator to get */
- /* addresses of variables */
-
- main()
- {
- char c1, c2;
- int i;
- long l;
- float f;
- double d;
-
- printf("Address of c1 %d\n", &c1);
- printf("Address of c2 %d\n", &c2);
- printf("Address of i %d\n", &i);
- printf("Address of l %d\n", &l);
- printf("Address of f %d\n", &f);
- printf("Address of d %d\n", &d);
- }
-
-
- VARSIZE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP03\VARSIZE.C
-
- /* varsize.c -- shows amount of memory */
- /* by various types */
-
- main()
- {
- printf("Size of a char is %d\n", sizeof(char));
- printf("Size of an int is %d\n", sizeof(int));
- printf("Size of a long is %d\n", sizeof(long));
- printf("Size of a float is %d\n", sizeof(float));
- printf("Size of a double is %d\n", sizeof(double));
- }
-
-
- VGAMAP.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP15\VGAMAP.C
-
- /* vgamap.c -- remaps the vga mode 19 palette */
- /* Program list: vgamap.c (for rand()) */
- #include <stdio.h>
- #include <graph.h>
- #include <conio.h>
- #define ESC '\033'
- #define PALSIZE 256
- #define ROWS 16
- #define COLS 16
- #define MIDBLUE 0x190000L
- long newpal[PALSIZE]; /* array of color values */
-
- main()
- {
- struct videoconfig vc;
- int mode = _MRES256COLOR;
- short xmax, ymax;
- short xcs[ROWS][COLS];
- short ycs[ROWS][COLS];
- short row, col;
- long colorval; /* VGA color value */
- long index; /* looping index */
- short palval; /* palette value */
- int c_base; /* color base -- blue, green, or red */
- int ch;
-
- if (_setvideomode(mode) == 0)
- {
- fprintf(stderr, "%d mode not supported\n", mode);
- exit(1);
- }
- _getvideoconfig(&vc);
- xmax = vc.numxpixels - 1;
- ymax = vc.numypixels - 1;
- for (col = 0; col < COLS; col++)
- for (row = 0; row < ROWS; row++)
- {
- xcs[row][col] = col * xmax / COLS + 5;
- ycs[row][col] = row * ymax / ROWS + 5;
- }
- _setcolor(1);
- _rectangle(_GBORDER, 0, 0, xmax, ymax);
- for (col = 1; col < COLS ; col++)
- {
- _moveto(col * (xmax + 1) / COLS, 0);
- _lineto(col * (xmax + 1) / COLS, ymax);
- }
- for (row = 1; row < ROWS; row++)
- {
- _moveto(0, row * (ymax + 1) / ROWS);
- _lineto(xmax, row * (ymax + 1) / ROWS);
- }
-
- for (col = 0; col < COLS; col++)
- for (row = 0; row < ROWS; row++)
- {
- _setcolor(row * ROWS + col);
- _floodfill(xcs[row][col], ycs[row][col],1);
- }
- getch();
-
- /* initialize newpal[] to 64 shades of blue, 64
- shades of green, 64 shades of red, and 64 shades
- of magenta */
- for (index = 0; index < 64; index++)
- {
- newpal[index] = index << 16;
- newpal[index + 64] = index << 8;
- newpal[index + 128] = index;
- newpal[index + 192] = index | MIDBLUE;
- }
- _remapallpalette(newpal);
- getch();
-
- /* set squares and colors randomly -- ESC
- terminates loop, and other keystrokes toggle
- it on and off */
- do
- {
- while (!kbhit())
- {
- palval = rand() % PALSIZE;
- colorval = 0L;
- for (c_base = 0; c_base < 3; c_base++)
- colorval += ((long) rand() % 64) <<
- (c_base * 8);
- _remappalette (palval, colorval);
- }
- ch = getch();
- if (ch != ESC)
- ch = getch();
- } while (ch != ESC);
- _setvideomode(_DEFAULTMODE);
- }
-
-
- VIEW.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP10\VIEW.C
-
- /* view.c -- demonstrates lseek() by displaying */
- /* a file and moving around in it */
-
- <fcntl.h> /* for open() */
- <stdio.h> /* for SEEK_CUR, etc. */
-
- #define HUNK 512
- #define MOVE 512L
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- char ch, buf[HUNK];
- long position = 0L;
- int bytes, eofflag = 0, fd_in;
-
- if (argc != 2)
- {
- fprintf(stderr, "Usage: view file\n");
- exit(0);
- }
-
- if ((fd_in = open(argv[1], O_RDONLY)) < 0)
- {
- fprintf(stderr, "\"%s\": Can't open.\n", argv[1]);
- exit(1);
- }
-
- for (;;)
- {
- bytes = read(fd_in, buf, HUNK);
- if (bytes == 0)
- {
- if (! eofflag)
- {
- fprintf(stderr, "\n<<at end of file>>\n");
- ++eofflag;
- }
- else
- exit(0);
- }
- else if (bytes < 0)
- {
- fprintf(stderr, "\"%s\": Error Reading.\n", argv[1]);
- exit(1);
- }
- else
- {
- eofflag = 0;
- position = lseek(fd_in, 0L, SEEK_CUR);
- if (position == -1L)
- {
- fprintf(stderr, "\"%s\": Error Seeking.\n", argv[1]);
- exit(1);
- }
- Print(buf, bytes);
- do
- {
- ch = getch();
- if (ch == 'q' || ch == 'Q')
- exit(0);
- } while (ch != '+' && ch != '-');
-
- if (ch == '-')
- {
- position = lseek(fd_in, -2 * MOVE, SEEK_CUR);
- if (position == -1L)
- {
- fprintf(stderr, "\"%s\": Error Seeking.\n", argv[1]);
- exit(1);
- }
- }
- }
- }
- }
-
- Print(char *buf, int cnt)
- {
- int i;
-
- for (i = 0; i < cnt; ++i, ++buf)
- {
- if (*buf < ' ' && *buf != '\n' && *buf != '\t')
- printf("^%c", *buf + '@');
- else
- putchar(*buf);
- }
- }
-
-
- WHATCHAR.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP09\WHATCHAR.C
-
- /* whatchar.c -- demonstrates the character */
- /* classification routines in ctype.h */
-
- <stdio.h> /* for NULL and BUFSIZ */
- <ctype.h> /* for iscntl(), et al */
- #define MAXL 20
-
- main()
- {
- char buf[BUFSIZ];
- int i;
-
- printf("Enter a line of text (20 chars max):\n");
- if (gets(buf) == NULL)
- exit(1);
-
- for (i = 0; i < MAXL; ++i)
- {
- if (buf[i] == '\0')
- break;
- printf("'%c' ->", buf[i]);
- if (isalpha(buf[i])) printf(" isalpha");
- if (isascii(buf[i])) printf(" isascii");
- if (iscntrl(buf[i])) printf(" iscntrl");
- if (isgraph(buf[i])) printf(" isgraph");
- if (isprint(buf[i])) printf(" isprint");
- if (isdigit(buf[i])) printf(" isdigit");
- if (isupper(buf[i])) printf(" isupper");
- if (islower(buf[i])) printf(" islower");
- if (ispunct(buf[i])) printf(" ispunct");
- if (isspace(buf[i])) printf(" isspace");
- if (isalnum(buf[i])) printf(" isalnum");
- if (isxdigit(buf[i])) printf(" isxdigit");
- printf("\n");
- }
- }
-
-
- WHILE.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP04\WHILE.C
-
-
- /* WHILE.C -- a simple while loop */
-
- main()
- {
- int count = 1;
-
- while (count < 11) /* loop condition */
- /* body of loop */
- {
- printf("%d\n", count);
- count++ ;
- }
- printf("Done!\n");
- }
-
-
-
- WRITECHR.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\WRITECHR.C
-
- /* writechr.c -- writes char and attribute repeatedly */
- /* using DMA */
- /* write character ch with attribute attr num times */
- /* starting at location pstart -- uses array notation */
-
- typedef unsigned int (far * VIDMEM);
-
- void Write_chars(pstart, ch, attr, num)
- VIDMEM pstart;
- unsigned short ch, attr, num;
- {
- register count;
- unsigned short pair;
-
- pair = (attr << 8) | (ch & 0x00FF) ;
- for (count = 0; count < num; count++)
- pstart[count] = pair;
- }
-
-
- WRITESTR.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP14\WRITESTR.C
-
- /* writestr.c -- writes string and attribute using DMA */
- /* write the string str with attribute attr at */
- /* location pstart -- uses pointer notation. */
-
- typedef unsigned int (far * VIDMEM);
-
- void Write_str(pstart, attr, str)
- VIDMEM pstart;
- unsigned short attr;
- char *str;
- {
- while (*str != '\0')
- *pstart++ = (attr << 8) | (*str++ & 0x00FF);
- }
-
-
- XMAS.C
- CD-ROM Disc Path: \SAMPCODE\QC_PROG\CHAP07\XMAS.C
-
- /* xmas.c -- fills an array with values, then passes */
- /* each of those values to a function. */
-
- main()
- {
- int i, j, widths[20];
- void Center_out();
-
- for (i = 0, j = 1; i < 18; ++i, j += 2)
- {
- widths[i] = j;
- }
- widths[i++] = 3;
- widths[i] = 3;
-
- for (i = 0; i < 20; i++)
- {
- Center_out('X', widths[i]);
- }
-
- }
-
- void Center_out(char character, int width)
- {
- int i;
-
- for (i = 0; i < ((80 - width) / 2); ++i)
- {
- putch(' ');
- }
- for (i = 0; i < width; ++i)
- {
- putch(character);
- }
- putch('\r');
- putch('\n');
- }
- Misc. `C' Sample Code from Microsoft
-
-
- ABS.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\ABS.C
-
- /* ABS.C: Demonstrate macros. */
-
- #include <stdio.h>
- #define ABS(value) ( (value) >= 0 ? (value) : -(value) )
-
- main()
- {
- int val = -20;
- printf( "result = %d\n", ABS(val) );
- }
-
-
- ALARM.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\ALARM.C
-
- /* ALARM.C illustrates inline assembly and functions or keywords
- * related to Terminate-and-Stay-Resident programs. Functions include:
- * _dos_setvect _dos_getvect _dos_keep
- * _chain_intr _enable _disable
- *
- * Keywords:
- * interrupt _asm
- * Directive:
- * #pragma
- * Pragma:
- * check_stack check_pointer
- * Global variables:
- * _psp _amblksiz
- *
- * WARNING: You must run ALARM from the DOS command line. The QC
- * environment does not permit TSRs to be installed from inside it, since
- * this would cause subsequent memory problems.
- *
- * See HARDERR.C for another example of inline assembler. See MOVEMEM.C
- * for another pragma example.
- */
-
- #include <dos.h>
- #include <malloc.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
-
- /* Stack and pointer checking off */
- #pragma check_stack( off )
- #pragma check_pointer( off )
-
- /* Inline assembler macro to sound a bell. Note that comments in macros must
- * be in the C format, not the assembler format.
- */
- #define BEEP() _asm { \
- _asm push bx /* Save register */ \
- _asm sub bx, bx /* Page 0 */ \
- _asm mov ax, 0E07h /* TTY bell */ \
- _asm int 10h /* BIOS 10 */ \
- _asm pop bx /* Restore */ \
- }
-
- #define TICKPERMIN 1092L
- #define MINPERHOUR 60L
- enum BOOLEAN { FALSE, TRUE };
-
- /* Prototypes for interrupt functions */
- void (interrupt far *oldtimer)( void );
- void (interrupt far *oldvideo)( void );
- void interrupt far newtimer( void );
- void interrupt far newvideo( unsigned _es, unsigned _ds, unsigned _di,
- unsigned _si, unsigned _bp, unsigned _sp,
- unsigned _bx, unsigned _dx, unsigned _cx,
- unsigned _ax, unsigned _ip, unsigned _cs,
- unsigned _flags );
-
- /* Variables that will be accessed inside TSR must be global. */
- int ftimesup = FALSE, fintimer = FALSE, finvideo = FALSE;
- long goaltick;
- long far *pcurtick = (long far *)0x0000046cL;
-
- /* Huge pointers force compiler to do segment arithmetic for us. */
- char huge *tsrstack;
- char huge *appstack;
- char huge *tsrbottom;
-
- main( int argc, char **argv )
- {
- long minute, hour;
- unsigned tsrsize;
-
- /* Initialize stack and bottom of program. */
- _asm mov WORD PTR tsrstack[0], sp
- _asm mov WORD PTR tsrstack[2], ss
- FP_SEG( tsrbottom ) = _psp;
- FP_OFF( tsrbottom ) = 0;
-
- /* Use 16 paragraph heap (controlled through global in malloc.h). */
- _amblksiz = 256;
-
- /* Program size is:
- * top of stack
- * - bottom of program (converted to paragraphs)
- * + paragraphs in the heap plus
- * + one extra paragraph just to be safe
- */
- tsrsize = ((tsrstack - tsrbottom) >> 4) + (_amblksiz >> 4) + 1;
-
- /* If command-line, convert time to ticks past midnight. Time must
- * include 0 in first place (0930, not 930). Time must be later than
- * current time.
- */
- if( argc < 2 )
- {
- puts( " Syntax: ALARM <hhmm> " );
- puts( " where <hhmm> is time (in military format) to ring alarm"
- exit( 1 );
- }
-
- minute = atol( argv[1] + 2 );
- argv[1][2] = 0;
- hour = atol( argv[1] );
- goaltick = (hour * MINPERHOUR * TICKPERMIN) + (minute * TICKPERMIN);
- if( *pcurtick > goaltick )
- {
- puts( "It's past that time now" );
- exit( 1 );
- }
-
- /* Replace existing timer and video routines with ours. */
- oldtimer = _dos_getvect( 0x1c );
- _dos_setvect( 0x1c, newtimer );
- oldvideo = _dos_getvect( 0x10 );
- _dos_setvect( 0x10, newvideo );
-
- /* Free the PSP segment and terminate with program resident. */
- _dos_freemem( _psp );
- _dos_keep( 0, tsrsize );
- }
-
- /* newtimer - Our timer interrupt compares current time to goal. If earlier
- * it just continues. If later, it beeps and sets a flag to quit checking.
- */
- void interrupt far newtimer()
- {
- if( ftimesup )
- _chain_intr( oldtimer );
- else
- {
- /* First execute the original timer interrupt. */
- (*oldtimer)();
- if( *pcurtick > goaltick )
- {
- /* If time is up, set flag so we'll never return. */
- ftimesup = TRUE;
-
- /* Save current stack of application, and set old stack of TSR.
- * This is for safety since we don't know the state of the
- * application stack, but we do know the state of our own stack.
- * Turn off interrupts during the stack switch.
- */
- _disable();
- _asm \
- {
- mov WORD PTR appstack[0], sp ; Save current stack
- mov WORD PTR appstack[2], ss
- mov sp, WORD PTR tsrstack[0] ; Load new stack
- mov ss, WORD PTR tsrstack[2]
- }
- _enable();
-
- /* Make sure we're not in video interrupt, then BEEP. This check
- * prevents the rare but potentially dangerous case of
- * calling INT 10 to beep while INT 10 is already running.
- */
- while( finvideo )
- ;
- BEEP();
- BEEP();
- BEEP();
-
- /* Restore application stack. */
- _disable();
- _asm \
- {
- mov sp, WORD PTR appstack[0]
- mov ss, WORD PTR appstack[2]
- }
- _enable();
- }
- }
- }
-
- /* newvideo - This routine protects against reentering INT 10 while it is
- * already executing. This could be disastrous if the interrupt routine was
- * interrupted while it was accessing a hardware register.
- */
- void interrupt far newvideo( unsigned _es, unsigned _ds, unsigned _di,
- unsigned _si, unsigned _bp, unsigned _sp,
- unsigned _bx, unsigned _dx, unsigned _cx,
- unsigned _ax, unsigned _ip, unsigned _cs,
- unsigned _flags )
- {
- static unsigned save_bp;
-
- /* If not already in (most of the time), chain to original. */
- if( !finvideo )
- _chain_intr( oldvideo );
- else
- {
-
- /* Set the inside flag, then make sure all the real registers
- * that might be passed to an interrupt 10h match the parameter
- * registers. Some of the real registers may be modified by the
- * preceding code. Note that BP must be saved in a static (nonstack)
- * variable so that it can be retrieved without modifying the stack.
- */
- finvideo = TRUE;
- _asm \
- {
- mov ax, _ax
- mov bx, _bx
- mov cx, _cx
- mov dx, _dx
- mov es, _es
- mov di, _di
- mov save_bp, bp
- mov bp, _bp
- }
-
- /* Call the original interrupt. */
- (*oldvideo)();
-
- /* Make sure that any values returned in real registers by the
- * interrupt are updated in the parameter registers. Reset the flag.
- */
- _asm \
- {
- mov bp, save_bp
- mov _bp, bp
- mov _di, di
- mov _es, es
- mov _dx, dx
- mov _cx, cx
- mov _bx, bx
- mov _ax, ax
- }
- finvideo = FALSE;
- }
- }
-
-
- ANIMATE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\ANIMATE.C
-
- /* ANIMATE.C illustrates animation functions including:
- * _imagesize _getimage _putimage
- */
-
- #include <conio.h>
- #include <stddef.h>
- #include <stdlib.h>
- #include <malloc.h>
- #include <graph.h>
-
- short action[5] = { _GPSET, _GPRESET, _GXOR, _GOR, _GAND };
- char *descrip[5] = { "PSET ", "PRESET", "XOR ", "OR ", "AND " };
-
- main()
- {
- char far *buffer;
- short i, x, y = 30;
- size_t imsize;
- short mode = _VRES16COLOR;
-
- while( !_setvideomode( mode ) ) /* Find best graphics mode */
- mode--;
- if (mode == _TEXTMONO )
- exit( 1 ); /* No graphics available */
- _setcolor( 3 );
- for ( i = 0; i < 5; i++ )
- {
- x = 50; y += 40;
- _settextposition( 1, 1 ); /* Display action type */
- _outtext( descrip[i] );
- /* Draw and measure ellipse */
- _ellipse( _GFILLINTERIOR, x - 15, y - 15, x + 15, y + 15 );
- imsize = (size_t)_imagesize( x - 16, y - 16, x + 16, y + 16 );
- buffer = (char far *)_fmalloc( imsize );
- if ( buffer == (char far *)NULL )
- exit( 1 );
- /* Get master copy of ellipse */
- _getimage( x - 16, y - 16, x + 16, y + 16, buffer );
- while( x < 260 ) /* Copy row of ellipses */
- { /* with specified action */
- x += 5;
- _putimage( x - 16, y - 16, buffer, action[i] );
- }
- _ffree( (char far *)buffer ); /* Free memory */
- getch();
- }
- exit( !_setvideomode( _DEFAULTMODE ) );
- }
-
-
- ARGS.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\ARGS.C
-
- /* ARGS.C illustrates the following variables used for accessing
- * command-line arguments and environment variables:
- * argc argv envp
- *
- * Also illustrates getting a process ID with:
- * getpid
- */
-
- #include <stdio.h>
- #include <process.h>
-
- main( int argc, /* Number of strings in array argv */
- char *argv[], /* Array of command-line argument strings */
- char **envp ) /* Array of environment variable strings */
- {
- int count;
-
- /* Display each command-line argument. */
- printf( "\nCommand-line arguments:\n" );
- for( count = 0; count < argc; count++ )
- printf( " argv[%d] %s\n", count, argv[count] );
-
- /* Display each environment variable. */
- printf( "\nEnvironment variables:\n" );
- while( *envp != NULL )
- printf( " %s\n", *(envp++) );
-
- /* If run from DOS, shows different ID for DOS than for DOS shell.
- * If execed or spawned, shows ID of parent.
- */
- printf( "\nProcess id of parent: %d", getpid() );
- exit( 0 );
- }
-
-
- ARGV.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\ARGV.C
-
- /* ARGV.C: Demonstrate accessing command-line arguments.
- */
-
- #include <stdio.h>
-
- void show_args( char *argument );
-
- int main( int argc, char *argv[] )
- {
- int count;
- for( count=0; count < argc; count++ )
- show_args( argv[count] );
- return 0;
- }
-
- void show_args( char *argument )
- {
- printf( "%s\n", argument );
- }
-
-
- ARGV1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\ARGV1.C
-
- /* ARGV1.C: Demonstrate null pointers. */
-
- #include <stdio.h>
-
- void show_args( char *argument );
-
- int main( int argc, char **argv )
- {
- while( *argv )
- show_args( *(argv++) );
- return 0;
- }
-
- void show_args( char *argument )
- {
- printf( "%s\n", argument );
- }
-
-
- ARRAY.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\ARRAY.C
-
- /* ARRAY.C: Demonstrate arrays. */
-
- #include <stdio.h>
-
- main()
- {
- int j, k;
- static int i_array[2][3] = { { 12, 2, 444 }, { 6, 55, 777 } };
- static char c_array[] = "Hello";
-
- printf( "--- Values -------- --- Addresses -------\n\n" );
-
- for( j = 0; j < 2; j = j + 1 )
- {
- for( k = 0; k < 3; k = k + 1 )
- {
- printf( "i_array[%d][%d] = %d", j, k, i_array[j][k] );
- printf( "\t&i_array[%d][%d] = %u\n", j, k, &i_array[j][k] );
- }
- printf( "\n" );
- }
-
- for( j = 0; j < 6; j = j + 1 )
- {
- printf( "c_array[%d] = %x %c", j, c_array[j], c_array[j] );
- printf( "\t&c_array[%d] = %u\n", j, &c_array[j] );
- }
- }
-
-
- ASSERT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\ASSERT.C
-
- /* ASSERT.C illustrates function:
- * assert
- */
-
- #include <stdio.h>
- #include <conio.h>
- #include <string.h>
- #include <assert.h>
-
- #define MAXSTR 120
-
- void chkstr( char *string ); /* Prototype */
-
- main()
- {
- char string1[MAXSTR], string2[MAXSTR];
-
- /* Do various processes on strings and check the results. If
- * none cause errors, force on error with empty string.
- */
- printf( "Enter a string: " );
- gets( string1 );
- chkstr( string1 );
-
- printf( "Enter another string: " );
- gets( string2 );
- chkstr( string2 );
-
- strcat( string1, string2 );
- chkstr( string1 );
- printf( "string1 + string2 = %s\n", string1 );
-
- chkstr( "" );
- printf( "You'll never get here\n" );
- }
-
- void chkstr( char *string )
- {
- assert( string != NULL ); /* Cannot be NULL */
- assert( *string != '\0' ); /* Cannot be empty */
- assert( strlen( string ) < MAXSTR ); /* Length must be positive */
- }
-
-
- ATEXIT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\ATEXIT.C
-
- /* ATEXIT.C illustrates:
- * atexit onexit
- */
-
- #include <stdlib.h>
- #include <stdio.h>
- ANSI /* Comment out to try onexit */
-
- /* Prototypes */
- void fn1( void ), fn2( void ), fn3( void ), fn4( void );
-
- main()
- {
-
- /* atexit is ANSI standard. It returns 0 for success, nonzero
- * for fail.
- */
- #ifdef ANSI
- atexit( fn1 );
- atexit( fn2 );
- atexit( fn3 );
- atexit( fn4 );
-
- /* onexit is Microsoft extension. It returns pointer to function
- * for success, NULL for fail.
- */
- #else
- onexit( fn1 );
- onexit( fn2 );
- onexit( fn3 );
- onexit( fn4 );
- #endif
-
- printf( "This is executed first.\n" );
- }
-
- void fn1()
- {
- printf( "next.\n" );
- }
-
- void fn2()
- {
- printf( "executed " );
- }
-
- void fn3()
- {
- printf( "is " );
- }
-
- void fn4()
- {
- printf( "This " );
- }
-
-
- ATONUM.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\ATONUM.C
-
- /* ATONUM.C illustrates string to number conversion functions including:
- * atof atoi atol gcvt
- *
- * It also illustrates:
- * cgets cputs
- */
-
- #include <stdlib.h>
- #include <string.h>
- #include <conio.h>
-
- #define MAXSTR 100
-
- char cnumbuf[MAXSTR] = { MAXSTR + 2, 0 };
- numbuf cnumbuf + 2 /* Actual buffer starts at byte 3 */
- char tmpbuf[MAXSTR];
-
- /* Numeric input and output without printf. */
- main()
- {
- int integer;
- long longint;
- float real;
-
- /* Using cgets (rather than gets) allows use of DOS editing keys
- * (or of editing keys from DOS command line editors).
- */
- cputs( "Enter an integer: " );
- cgets( cnumbuf );
- cputs( "\n\r" ); /* cputs doesn't translate \n */
- integer = atoi( numbuf );
- strcpy( tmpbuf, numbuf );
- strcat( tmpbuf, " + " );
-
- cputs( "Enter a long integer: " );
- cgets( cnumbuf );
- cputs( "\n\r" );
- longint = atol( numbuf );
- strcat( tmpbuf, numbuf );
- strcat( tmpbuf, " + " );
-
- cputs( "Enter a floating point number: " );
- cgets( cnumbuf );
- cputs( "\n\r" );
- real = atof( numbuf );
- strcat( tmpbuf, numbuf );
- strcat( tmpbuf, " = " );
-
- gcvt( integer + longint + real, 4, numbuf );
- strcat( tmpbuf, numbuf );
- strcat( tmpbuf, "\n\r" );
-
- cputs( tmpbuf );
- }
-
-
- BADSEMI.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\BADSEMI.C
-
- /* BADSEMI.C: Misplaced semicolon. */
-
- #include <stdio.h>
-
- main()
- {
- int count;
- for( count = 0; count < 500; count++ ); /* Error! */
- {
- printf( "count = %d\n", count );
- printf( "And the beat goes on...\n" );
- }
- }
-
-
- BADSEMI1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\BADSEMI1.C
-
- /* BADSEMI1.C: Misplaced semicolon. */
-
- #include <stdio.h>
-
- main()
- {
- int count;
- for( count = 0; count < 500; count++ )
- ; /* Null statement */
- {
- printf( "count = %d\n", count );
- printf( "And the beat goes on...\n" );
- }
- }
-
-
- BEEP.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\UTILITY\BEEP.C
-
- /* BEEP.C illustrates timing and port input and output functions
- * including:
- * inp outp clock
- * Also keyword:
- * enum
- *
- * In addition to the delay use shown here, clock can be used as a
- * timer as shown in SIEVE.C.
- */
-
- #include <time.h>
- #include <conio.h>
-
- void beep( unsigned duration, unsigned frequency );
- void delay( clock_t wait );
-
-
- enum notes
- { /* Enumeration of notes and frequencies */
- C0 = 262, D0 = 296, E0 = 330, F0 = 349, G0 = 392, A0 = 440, B0 = 494,
- C1 = 523, D1 = 587, E1 = 659, F1 = 698, G1 = 784, A1 = 880, B1 = 988,
- EIGHTH = 125, QUARTER = 250, HALF = 500, WHOLE = 1000, END = 0
- } song[] =
- { /* Array initialized to notes of song */
- C1, HALF, G0, HALF, A0, HALF, E0, HALF, F0, HALF, E0, QUARTER,
- D0, QUARTER, C0, WHOLE, END
- };
-
- int main ()
- {
- int note = 0;
-
- while( song[note] )
- beep( song[note++], song[note++] );
- }
-
- /* beep - sounds the speaker for a time specified in microseconds by
- * duration at a pitch specified in hertz by frequency.
- */
- void beep( unsigned duration, unsigned frequency )
- {
- int control;
-
- /* If frequency is 0, beep doesn't try to make a sound. It
- * just sleeps for the duration.
- */
- if (frequency)
- {
- /* 75 is the shortest reliable duration of a sound. */
- if( duration < 75 )
- duration = 75;
-
- /* Prepare timer by sending 10111100 to port 43. */
- outp( 0x43, 0xb6 );
-
- /* Divide input frequency by timer ticks per second and
- * write (byte by byte) to timer.
- */
- frequency = (unsigned)(1193180L / frequency);
- outp( 0x42, (char)frequency );
- outp( 0x42, (char)(frequency >> 8) );
-
- /* Save speaker control byte. */
- control = inp( 0x61 );
-
- /* Turn on the speaker (with bits 0 and 1). */
- outp( 0x61, control | 0x3 );
- }
-
- delay( (clock_t)duration );
-
- /* Turn speaker back on if necessary. */
- if( frequency )
- outp( 0x61, control );
- }
-
- /* delay - Pauses for a specified number of microseconds. */
- void delay( clock_t wait )
- {
- clock_t goal;
-
- goal = wait + clock();
- while( goal > clock() )
- ;
- }
-
-
- BESSEL.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\BESSEL.C
-
- /* BESSEL.C illustrates Bessel functions including:
- * j0 j1 jn y0 y1 yn
- */
-
- #include <math.h>
- #include <stdio.h>
-
- main()
- {
- double x = 2.387;
- int n = 3, c;
-
- printf( "Bessel functions for x = %f:\n", x );
- printf( " Kind\t\tOrder\t\Function\tResult\n\n" );
- printf( " First\t\t0\tj0( x )\t\t%f\n", j0( x ) );
- printf( " First\t\t1\tj1( x )\t\t%f\n", j1( x ) );
- for( c = 2; c < 10; c++ )
- printf( " First\t\t%d\tjn( n, x )\t%f\n", c, jn( c, x ) );
-
- printf( " Second\t0\ty0( x )\t\t%f\n", y0( x ) );
- printf( " Second\t1\ty1( x )\t\t%f\n", y1( x ) );
- for( c = 2; c < 10; c++ )
- printf( " Second\t%d\tyn( n, x )\t%f\n", c, yn( c, x ) );
- }
-
-
- BINTEXT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\BINTEXT.C
-
- /* BINTEXT.C illustrates changing between binary and text modes for
- * stream I/O using function:
- * setmode
- * and global variable:
- * _fmode
- */
-
- #include <stdio.h>
- #include <fcntl.h>
- #include <io.h>
- #include <string.h>
- <stdlib.h> /* For _fmode and exit */
-
- main()
- {
- FILE *htmp;
- char name[13];
-
- /* Set default mode to binary and open file. */
- _fmode = O_BINARY;
- if( (htmp = fopen( tmpnam( name ), "w+" )) == NULL )
- exit( 1 );
- fprintf( htmp, "\nThis\nis\nsome\nbinary\ntext.\n\n" );
-
- /* Flush buffer and change mode to text. */
- fflush( htmp );
- setmode( fileno( htmp ), O_TEXT );
- fprintf( htmp, "\nThis\nis\nsome\ntext\ntext.\n\n" );
- fclose( htmp );
-
- system( strcat( "TYPE ", name ) );
- remove( name );
- exit( 0 );
- }
-
-
- BREAKER.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\BREAKER.C
-
- /* BREAKER.C: Demonstrate break statement. */
-
- #include <stdio.h>
- #include <conio.h>
-
- main()
- {
- char ch;
- printf( "Press any key. Press TAB to quit.\n" );
- while( 1 )
- {
- ch = getche();
- if( ch == '\t' )
- {
- printf( "\a\nYou pressed TAB.\n" );
- break;
- }
- }
- }
-
-
- BREAKER1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\BREAKER1.C
-
- /* BREAKER1.C: Break only exits one loop. */
-
- #include <stdio.h>
- #include <conio.h>
-
- main()
- {
- char ch;
- printf( "Press any key. Press RETURN to quit.\n" );
- do
- {
- while( ( ch = getche() ) != '\r' )
- {
- if( ch == '\t' )
- {
- printf( "\a\nYou pressed TAB.\n" );
- break;
- }
- }
- } while( ch != '\r' );
- printf( "\nBye bye." );
- }
-
-
- BUFTEST.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\BUFTEST.C
-
- /* BUFTEST.C illustrates buffer control for stream I/O using functions:
- * setbuf setvbuf
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #define BUF2SIZ 2048
-
- long countln( FILE *stream ); /* Prototype */
- char buf1[BUFSIZ], buf2[BUF2SIZ]; /* File buffers */
-
- main( int argc, char *argv[] )
- {
- time_t start;
- FILE *stream;
- int c;
-
- /* Use our buffer with the default size. This gives us the option
- * of examining and/or modifying the buffer during I/0 (though the
- * example doesn't illustrate this).
- */
- if( (stream = fopen( argv[1], "rt" )) == NULL )
- exit( 1 );
- setbuf( stream, buf1 );
- start = clock();
- c = countln( stream );
- printf( "Time: %5.2f\tBuffering: Normal\tBuffer size: %d\n",
- ((float)clock() - start) / CLK_TCK, BUFSIZ );
-
- /* Use a larger buffer. */
- if( (stream = fopen( argv[1], "rt" )) == NULL )
- exit( 1 );
- setvbuf( stream, buf2, _IOFBF, sizeof( buf2 ) );
- start = clock();
- c = countln( stream );
- printf( "Time: %5.2f\tBuffering: Normal\tBuffer size: %d\n",
- ((float)clock() - start) / CLK_TCK, BUF2SIZ );
-
- /* Try it with no buffering. */
- if( (stream = fopen( argv[1], "rt" )) == NULL )
- exit( 1 );
- setvbuf( stream, NULL, _IONBF, 0 );
- start = clock();
- c = countln( stream );
- printf( "Time: %5.2f\tBuffering: Normal\tBuffer size: %d\n",
- ((float)clock() - start) / CLK_TCK, 0 );
-
- printf( "File %s has %d lines", argv[1], c );
- exit( 0 );
- }
-
- /* Count lines in text files and close file. */
- long countln( FILE *stream )
- {
- char linebuf[120];
- long c = 0;
-
- while( !feof( stream ) )
- {
- fgets( linebuf, 121, stream );
- ++c;
- }
- fclose( stream );
- return c;
- }
-
-
- CABS.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\MATH\CABS.C
-
- /* CABS.C illustrates functions:
- * cabs hypot
- */
-
- #include <math.h>
- #include <stdio.h>
-
- main()
- {
- static struct complex ne = { 3.0, 4.0 }, se = { -3.0, -4.0 },
- sw = { -3.0, -4.0 }, nw = { -3.0, 4.0 };
-
- printf( "Absolute %4.1lf + %4.1lfi:\t\t%4.1f\n",
- ne.x, ne.y, cabs( ne ) );
- printf( "Absolute %4.1lf + %4.1lfi:\t\t%4.1f\n",
- sw.x, sw.y, cabs( sw ) );
-
- printf( "Hypotenuse of %4.1lf and %4.1lf:\t%4.1f\n",
- se.x, se.y, hypot( se.x, se.y ) );
- printf( "Hypotenuse of %4.1lf and %4.1lf:\t%4.1f\n",
- nw.x, nw.y, hypot( nw.x, nw.y ) );
- }
-
-
-
- CASE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\CASE.C
-
- /* CASE.C illustrates case conversion and other conversions.
- * Functions illustrated include:
- * strupr toupper _toupper
- * strlwr tolower _tolower
- * strrev toascii
- */
-
- #include <string.h>
- #include <stdio.h>
- #include <ctype.h>
-
- char mstring[] = "Dog Saw Dad Live On";
- char *ustring, *tstring, *estring;
- char *p;
-
- main()
- {
- printf( "Original:\t%s\n", mstring );
-
- /* Upper and lower case. */
- ustring = strupr( strdup( mstring ) );
- printf( "Upper case:\t%s\n", ustring );
-
- printf( "Lower case:\t%s\n", strlwr( ustring ) );
-
- /* Reverse case of each character. */
- tstring = strdup( mstring );
- for( p = tstring; *p; p++ )
- {
- if( isupper( *p ) )
- *p = tolower( *p );
- else
- *p = toupper( *p );
-
- /* This alternate code (commented out) shows how to use _tolower
- * and _toupper for the same purpose.
- if( isupper( *p ) )
- *p = _tolower( *p );
- else if( islower( *p ) )
- *p = _toupper( *p );
- */
- }
- printf( "Toggle case:\t%s\n", tstring );
-
- /* Encode and decode string. The decoding technique will convert
- * WordStar-style strings, which have some high bits set.
- */
- estring = strdup( mstring );
- for( p = estring; *p; p++ )
- *p = *p | 0x80;
- printf( "Encoded:\t%s\n", estring );
-
- for( p = estring; *p; p++ )
- *p = toascii( *p );
- printf( "Decoded:\t%s\n", estring );
-
- printf( "Reversed:\t%s\n", strrev( ustring ) );
- }
-
-
- CGA.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\CGA.C
-
- /* CGA.C: Demonstrates CGA colors */
- #include <stdio.h>
- #include <graph.h>
- #include <conio.h>
-
- long bkcolor[8] =
- {_BLACK, _BLUE, _GREEN, _CYAN,
- _RED, _MAGENTA, _BROWN, _WHITE};
-
- char *bkcolor_name [] =
- {"_BLACK", "_BLUE", "_GREEN", "_CYAN",
- "_RED", "_MAGENTA", "_BROWN", "_WHITE"};
-
- main()
- {
- int i, j, k;
- _setvideomode( _MRES4COLOR );
- for( i=0; i<= 3; i++ )
- {
- _selectpalette( i );
- for( k=0; k <= 7; k++ )
- {
- _setbkcolor( bkcolor[k] );
- for( j=0; j<=3; j++ )
- {
- _settextposition( 1, 1 );
- printf( "background color: %8s\n", bkcolor_name[k] );
- printf( "palette: %d\ncolor: %d\n", i, j );
- _setcolor( j );
- _rectangle( _GFILLINTERIOR, 160, 100, 320, 200 );
- getch();
- }
- }
- }
- _setvideomode( _DEFAULTMODE );
- }
-
-
- CGAPAL.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\CGAPAL.C
-
- /* CGAPAL.C illustrates CGA palettes using:
- * _selectpalette
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- #include <graph.h>
-
- long bkcolor[8] = { _BLACK, _BLUE, _GREEN, _CYAN,
- _RED, _MAGENTA, _BROWN, _WHITE };
- char *bkname [] = { "BLACK", "BLUE", "GREEN", "CYAN",
- "RED", "MAGENTA", "BROWN", "WHITE" };
- main()
- {
- int i, j, k;
-
- if ( !_setvideomode( _MRES4COLOR ) )
- exit( 1 );
- for( i = 0; i < 4; i++ )
- {
- _selectpalette( i );
- for( k = 0; k < 8; k++ )
- {
- _setbkcolor( bkcolor[k] );
- for( j = 0; j < 4; j++ )
- {
- _settextposition( 1, 1 );
- printf( "Background color: %8s\n", bkname[k] );
- printf( "Palette: %d\nColor: %d\n", i, j );
- _setcolor( j );
- _rectangle( _GFILLINTERIOR, 160, 100, 320, 200 );
- getch();
- }
- }
- }
- exit( !_setvideomode( _DEFAULTMODE ) );
- }
-
-
- CHMOD1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\CHMOD1.C
-
- /* CHMOD1.C illustrates reading and changing file attribute and time using:
- * access chmod utime
- *
- * See CHMOD2.C for a more powerful variation of this program using
- * _dos functions.
- */
-
- #include <io.h>
- #include <sys\types.h>
- #include <sys\stat.h>
- #include <sys\utime.h>
- #include <stdio.h>
- #include <conio.h>
- #include <stdlib.h>
-
- enum FILEATTRIB { EXIST, WRITE = 2, READ = 4, READWRITE = 6 };
-
- /* Exist macro uses access */
- #define EXIST( name ) !access( name, EXIST )
-
- main( int argc, char *argv[] )
- {
- if( !EXIST( argv[1] ) )
- {
- printf( "Syntax: CHMOD1 <filename>" );
- exit( 1 );
- }
-
- if( !access( argv[1], WRITE ) )
- {
- printf( "File %s is read/write. Change to read only? ", argv[1] );
-
- /* Note: Use stdlib.h for function definition of toupper rather
- * than macro version in ctype.h. Macro side effects would cause
- * macro version to read two keys.
- */
- if( toupper( getch() ) == 'Y' )
- chmod( argv[1], S_IREAD );
- }
- else
- {
- printf( "File %s is read only. Change to read/write? ", argv[1] );
- if( toupper( getch() ) == 'Y' )
- chmod( argv[1], S_IREAD | S_IWRITE );
- }
-
- printf( "\nUpdate file time to current time? " );
- if( toupper( getch() ) == 'Y' )
- utime( argv[1], NULL );
- exit( 0 );
- }
-
-
- CHMOD2.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\CHMOD2.C
-
- /* CHMOD2.C illustrates reading and changing file attributes and file
- * time using:
- * _dos_getftime _dos_setftime
- * _dos_getfileattr _dos_setfileattr
- *
- * See CHMOD1.C for a simpler variation of this program using the utime,
- * access, and chmod functions.
- */
-
- #include <dos.h>
- #include <fcntl.h>
- #include <stdio.h>
- #include <conio.h>
- #include <stdlib.h>
- #include <sys\types.h>
- #include <sys\stat.h>
-
- char *datestr( unsigned d, char *buf ); /* Prototypes */
- char *timestr( unsigned t, char *buf );
-
- main( int argc, char *argv[] )
- {
- unsigned fdate, ftime, fattr;
- struct dosdate_t ddate;
- struct dostime_t dtime;
- int hsource;
- char timebuf[10], datebuf[10], *pkind;
-
- /* Open to get file handle and test for errors (such as nonexistence). */
- if( _dos_open( argv[1], O_RDONLY, &hsource ) )
- {
- printf( "Can't open file\n" );
- exit( 1 );
- }
-
- /* Get time, date, and attribute of file. */
- _dos_getftime( hsource, &fdate, &ftime );
- _dos_getfileattr( argv[1], &fattr );
-
- /* Convert information into formatted strings. */
- datestr( fdate, datebuf );
- timestr( ftime, timebuf );
-
- if( fattr & _A_SUBDIR )
- pkind = "Directory";
- else if( fattr & _A_VOLID )
- pkind = "Label";
- else
- pkind = "File";
-
- printf( "%-12s %-8s %-9s %-9s %s %s %s\n",
- "FILE", "TIME", "DATE", "KIND", "RDO", "HID", "SYS" );
- printf( "%-12s %8s %8s %-9s %c %c %c\n",
- argv[1], timebuf, datebuf, pkind,
- (fattr & _A_RDONLY) ? 'Y' : 'N',
- (fattr & _A_HIDDEN) ? 'Y' : 'N',
- (fattr & _A_SYSTEM) ? 'Y' : 'N' );
-
- /* Update file time or attribute. */
- printf( "Change: (T)ime (R)ead only (H)idden (S)ystem\n" );
- switch( toupper( getch() ) ) /* Use stdlib.h, not ctype.h */
- {
- case 'T': /* Set to current time */
- _dos_gettime( &dtime );
- _dos_getdate( &ddate );
- ftime = (dtime.hour << 11) | (dtime.minute << 5);
- fdate = ((ddate.year - 1980) << 9) | (ddate.month << 5) |
- ddate.day;
- _dos_setftime( hsource, fdate, ftime );
- break;
- case 'R': /* Toggle read only */
- _dos_setfileattr( argv[1], fattr ^ _A_RDONLY );
- break;
- case 'H': /* Toggle hidden */
- _dos_setfileattr( argv[1], fattr ^ _A_HIDDEN );
- break;
- case 'S': /* Toggle system */
- _dos_setfileattr( argv[1], fattr ^ _A_SYSTEM );
- break;
- }
- _dos_close( hsource );
- exit( 1 );
- }
-
- /* Take unsigned time in the format: fedcba9876543210
- * s=2 sec incr, m=0-59, h=23 hhhhhmmmmmmsssss
- * Change to a 9-byte string (ignore seconds): hh:mm ?m
- */
- char *timestr( unsigned t, char *buf )
- {
- int h = (t >> 11) & 0x1f, m = (t >> 5) & 0x3f;
-
- sprintf( buf, "%2.2d:%02.2d %cm", h % 12, m, h > 11 ? 'p' : 'a' );
- return buf;
- }
-
- /* Take unsigned date in the format: fedcba9876543210
- * d=1-31, m=1-12, y=0-119 (1980-2099) yyyyyyymmmmddddd
- * Change to a 9-byte string: mm/dd/yy
- */
- char *datestr( unsigned d, char *buf )
- {
- sprintf( buf, "%2.2d/%02.2d/%02.2d",
- (d >> 5) & 0x0f, d & 0x1f, (d >> 9) + 80 );
- return buf;
- }
-
-
- CMPSTR.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\CMPSTR.C
-
- /* CMPSTR.C illustrates string and memory comparison functions including:
- * memcmp memicmp
- * strncmp strnicmp
- * strcmp stricmp strcmpi
- */
-
- #include <memory.h>
- #include <string.h>
- #include <stdio.h>
-
- char string1[] = "The quick brown dog jumps over the lazy fox";
- char string2[] = "The QUICK brown fox jumps over the lazy dog";
-
- main()
- {
- char tmp[20];
- int result;
-
- printf( "Compare strings:\n\t\t%s\n\t\t%s\n\n", string1, string2 );
-
- printf( "Function:\tmemcmp\n" );
- result = memcmp( string1, string2 , 42 );
- if( result > 0 )
- strcpy( tmp, "greater than" );
- else if( result < 0 )
- strcpy( tmp, "less than" );
- else
- strcpy( tmp, "equal to" );
- printf( "Result:\t\tString 1 is %s than string 2\n\n", tmp );
-
- printf( "Function:\tmemicmp\n" );
- result = memicmp( string1, string2, 42 );
- if( result > 0 )
- strcpy( tmp, "greater than" );
- else if( result < 0 )
- strcpy( tmp, "less than" );
- else
- strcpy( tmp, "equal to" );
- printf( "Result:\t\tString 1 is %s than string 2\n\n", tmp );
-
- printf( "Function:\tstrncmp\n" );
- result = strncmp( string1, string2 , 42 );
- if( result > 0 )
- strcpy( tmp, "greater than" );
- else if( result < 0 )
- strcpy( tmp, "less than" );
- else
- strcpy( tmp, "equal to" );
- printf( "Result:\t\tString 1 is %s than string 2\n\n", tmp );
-
- printf( "Function:\tstrnicmp\n" );
- result = strnicmp( string1, string2, 42 );
- if( result > 0 )
- strcpy( tmp, "greater than" );
- else if( result < 0 )
- strcpy( tmp, "less than" );
- else
- strcpy( tmp, "equal to" );
- printf( "Result:\t\tString 1 is %s than string 2\n\n", tmp );
-
- printf( "Function:\tstrcmp\n" );
- result = strcmp( string1, string2 );
- if( result > 0 )
- strcpy( tmp, "greater than" );
- else if( result < 0 )
- strcpy( tmp, "less than" );
- else
- strcpy( tmp, "equal to" );
- printf( "Result:\t\tString 1 is %s than string 2\n\n", tmp );
-
- printf( "Function:\tstricmp or strcmpi\n" );
- result = stricmp( string1, string2 );
- /* strcmpi (commented out) is the same as stricmp.
- result = strcmpi( string1, string2 );
- */
- if( result > 0 )
- strcpy( tmp, "greater than" );
- else if( result < 0 )
- strcpy( tmp, "less than" );
- else
- strcpy( tmp, "equal to" );
- printf( "Result:\t\tString 1 is %s than string 2\n", tmp );
- }
-
-
- COLOR.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\COLOR.C
-
- /* COLOR.C: Sets a medium resolution mode with maximum color choices */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <graph.h>
- #include <conio.h>
- struct videoconfig vc;
-
- main()
- {
- if( _setvideomode( _MRES256COLOR ) )
- ;
- else if( _setvideomode( _MRES16COLOR ) )
- ;
- else if( _setvideomode( _MRES4COLOR ) )
- ;
- else {
- printf( "Error: No color graphics capability\n" );
- exit( 0 );
- }
-
- _getvideoconfig( &vc );
-
- printf( "%d available colors\n", vc.numcolors );
- printf( "%d horizontal pixels\n", vc.numxpixels );
- printf( "%d vertical pixels\n", vc.numypixels );
-
- getch();
- _clearscreen( _GCLEARSCREEN );
- _setvideomode( _DEFAULTMODE );
- }
-
-
- COLTEXT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\COLTEXT.C
-
- /* COLTEXT.C: Displays text in color */
- #include <stdio.h>
- #include <conio.h>
- #include <graph.h>
-
- char buffer [80];
-
- main()
- {
- int blink,fgd;
- long bgd;
-
- _clearscreen( _GCLEARSCREEN );
- printf( "Text color attributes:\n" );
-
- for( blink=0; blink<=16; blink+=16 )
- {
- for( bgd=0; bgd<8; bgd++ )
- {
- _setbkcolor( bgd );
- _settextposition( bgd + ((blink / 16) * 9) + 3, 1 );
- _settextcolor( 7 );
- sprintf( buffer, "Bgd: %d Fgd:", bgd );
- _outtext( buffer );
-
- for( fgd=0; fgd<16; fgd++ )
- {
- _settextcolor( fgd+blink );
- sprintf( buffer, " %2d ", fgd+blink );
- _outtext( buffer );
- }
- }
- }
- getch();
- _setvideomode( _DEFAULTMODE );
- }
-
-
- COM.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\COM.C
-
- /* COM.C illustrates serial port access using function:
- * _bios_serialcom
- */
-
- #include <bios.h>
- #include <stdio.h>
-
- main()
- {
- unsigned status, port;
-
- for( port = 0; port < 3; port++ )
- {
- status = _bios_serialcom( _COM_STATUS, port, 0 );
-
- /* Report status of each serial port and test whether there is a
- * modem for each. If data-set-ready and clear-to-send, modem exists.
- */
- printf( "COM%c status: %.4X\tModem: %s\n",
- (char)port + '1', status,
- (status & 0x0030) ? "YES" : "NO" );
- }
- }
-
-
- COMMA.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\COMMA.C
-
- /* COMMA.C: Demonstrate comma operator. */
-
- #include <stdio.h>
-
- main()
- {
- int val = 5, val1 = 666, temp;
- temp = val, val = val1, val1 = temp;
- printf( "val = %d val1 = %d\n", val, val1 );
- }
-
-
- CONT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\CONT.C
-
- /* CONT.C: Demonstrate continue statement. */
-
- #include <stdio.h>
-
- main()
- {
- int count;
- for( count = 0; count < 10; count++ )
- {
- if( count > 3 )
- continue;
- printf( "count = %d\n", count );
- }
- printf( "Done!\n" );
- }
-
-
- CONT1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\CONT1.C
-
- /* CONT1.C: Demonstrate alternative to continue. */
-
- #include <stdio.h>
-
- main()
- {
- int count;
- for( count = 0; count < 10; count++ )
- {
- if( count < 4 )
- printf( "count = %d\n", count );
- }
- printf( "Done!\n" );
- }
-
-
- CONVERT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\CONVERT.C
-
- /* CONVERT.C: Demonstrate type conversions. */
-
- #include <stdio.h>
-
- main()
- {
- char c_val = 10;
- int i_val = 20;
- long l_val = 64000;
- float f_val = 3.1;
- int result;
-
- result = c_val + i_val + l_val + f_val; /* Error! */
-
- printf( "%d\n", result );
- }
-
-
- COPROC.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\MATH\COPROC.C
-
- /* COPROC.C illustrates use of the status and control words of a floating
- * point coprocessor (or emulator). Functions illustrated include:
- * _clear87 _status87 _control87
- */
-
- #include <stdio.h>
- #include <conio.h>
- #include <float.h>
- #include <stdlib.h>
- #include <string.h>
-
- double dx = 1e-40, dy;
- float fx, fy;
- unsigned status, control;
- char tmpstr[20];
- char *binstr( int num, char *buffer );
-
- main()
- {
- printf( "Status Word Key:\n" );
- printf( "B\tBusy flag\n0-3\tCondition codes\nS\tStack top pointer\n" );
- printf( "E\tError summary\nF\tStack flag\nP\tPrecision exception\n" );
- printf( "U\tUnderflow exception\nO\tOverflow exception\n" );
- printf( "Z\tZero divide exception\nD\tDenormalized exception\n" );
- printf( "I\tInvalid operation exception\n\n" );
-
- binstr( _clear87(), tmpstr );
- printf( "B3SSS210EFPUOZDI Function\tCondition\n\n" );
- printf( "%16s _clear87\tAfter clearing\n", tmpstr );
-
- /* Storing double to float that hasn't enough precision for it
- * causes underflow and precision exceptions.
- */
- fx = dx;
- binstr( _status87(), tmpstr );
- printf( "%16s _status87\tAfter moving double to float\n", tmpstr );
-
- /* Storing float with lost precision back to double adds denormalized
- * exception (previous exceptions remain).
- */
- dy = fx;
- binstr( _clear87(), tmpstr );
- printf( "%16s _clear87\tAfter moving float to double\n", tmpstr );
-
- /* Using clear87() erases previous exceptions. */
- fy = dy;
- binstr( _status87(), tmpstr );
- printf( "%16s _status87\tAfter moving double to float\n\n", tmpstr );
-
- getch();
- printf( "Control Word Key:\n" );
- printf( "i\tInfinity control\nr\tRounding control\n" );
- printf( "p\tPrecision control\ne\tInterrupt enable mask\n" );
- printf( "U\tUnderflow mask\nO\tOverflow mask\n" );
- printf( "Z\tZero divide mask\nD\tDenormalized mask\n" );
- printf( "I\tInvalid operation mask\n\n" );
- printf( "???irrppe?PUOZDI Result\n" );
- fy = .1;
-
- /* Show current control word. */
- binstr( _control87( 0, 0 ), tmpstr );
- printf( "%16s %.1f * %.1f = %.15e with initial precision\n",
- tmpstr, fy, fy, fy * fy );
-
- /* Set precision to 24 bits. */
- binstr( _control87( PC_24, MCW_PC ), tmpstr );
- printf( "%16s %.1f * %.1f = %.15e with 24 bit precision\n",
- tmpstr, fy, fy, fy * fy );
-
- /* Restore default. */
- binstr( _control87( CW_DEFAULT, 0xffff ), tmpstr );
- printf( "%16s %.1f * %.1f = %.15e with default precision\n",
- tmpstr, fy, fy, fy * fy );
- }
-
- /* Convert integer to string of 16 binary characters. */
- char *binstr( int num, char *buffer )
- {
- char tmp[17];
- int len;
-
- memset( buffer, '0', 16 );
- len = strlen( itoa( num, tmp, 2 ) );
- strcpy( buffer + 16 - len, tmp );
- return buffer;
- }
-
-
- COPY2.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\COPY2.C
-
- /* COPY2.C illustrates DOS file I/O and DOS memory allocation functions
- * including:
- * _dos_open _dos_close _dos_creatnew _dos_creat
- * _dos_read _dos_write _dos_allocmem _dos_free
- *
- * See COPY1.C for another version of the copyfile function.
- */
-
- #include <dos.h>
- #include <fcntl.h>
- #include <conio.h>
- #include <stdio.h>
-
- int copyfile( char *source, char *destin ); /* Prototype */
-
- main( int argc, char *argv[] )
- {
- if( argc == 3 )
- if( copyfile( argv[1], argv[2] ) )
- printf( "Copy failed\n" );
- else
- printf( "Copy successful\n" );
- else
- printf( " SYNTAX: COPY2 <source> <target>\n" );
- }
-
- /* Function to copy one file to another (both specified by path).
- * Dynamically allocates memory for the file buffer. Prompts before
- * overwriting existing file. Returns 0 if successful, or an error
- * number if unsuccessful. This function uses dos functions only; no
- * standard C library functions are used.
- */
- #define EXIST 80
- enum ATTRIB { NORMAL, RDONLY, HIDDEN, SYSTEM = 4 };
- int copyfile( char *source, char *target )
- {
- char far *buf = NULL;
- static char prompt[] = "Target exists. Overwrite? ", newline[] = "\n\r";
- int hsource, htarget, ch;
- unsigned ret, segbuf, count;
-
- /* Attempt to dynamically allocate all of memory (0xffff paragraphs).
- * This will fail, but will return the amount actually available
- * in segbuf. Then allocate this amount.
- */
- _dos_allocmem( 0xffff, &segbuf );
- count = segbuf;
- if( ret = _dos_allocmem( count, &segbuf ) )
- return ret;
- FP_SEG( buf ) = segbuf;
-
- /* Open source file and create target, overwriting if necessary. */
- if( ret = _dos_open( source, O_RDONLY, &hsource ) )
- return ret;
- ret = _dos_creatnew( target, NORMAL, &htarget );
- if( ret == EXIST )
- {
- /* Use _dos_write to display prompts. Use bdos to call
- * function 1 to get and echo keystroke.
- */
- _dos_write( 1, prompt, sizeof( prompt ) - 1, &ch );
- ch = bdos( 1, 0, 0 ) & 0x00ff;
- if( (ch == 'y') || (ch == 'Y') )
- ret = _dos_creat( target, NORMAL, &htarget );
- _dos_write( 1, newline, sizeof( newline ) - 1, &ch );
- }
- if( ret )
- return ret;
-
- /* Read and write until there is nothing left. */
- while( count )
- {
- /* Read and write input. */
- if( (ret = _dos_read( hsource, buf, count, &count )) )
- return ret;
- if( (ret = _dos_write( htarget, buf, count, &count )) )
- return ret;
- }
-
- /* Close files and free memory. */
- _dos_close( hsource );
- _dos_close( htarget );
- _dos_freemem( segbuf );
- return 0;
- }
-
-
-
- CPYSTR.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\CPYSTR.C
-
- /* CPYSTR.C illustrate memory and string copy and move functions including:
- * memccpy memcpy memmove
- * strncpy strcpy strdup strlen
- */
-
- #include <memory.h>
- #include <string.h>
- #include <stdio.h>
- #include <conio.h>
- #include <dos.h>
-
- char string1[60] = "The quick brown dog jumps over the lazy fox";
- char string2[60] = "The quick brown fox jumps over the lazy dog";
- /* 1 2 3 4 5 *
- * 12345678901234567890123456789012345678901234567890 */
- main()
- {
- char buffer[61];
- char *pdest, *newstring;
- int pos;
-
- printf( "Function:\tmemccpy 60 characters or to character 's'\n" );
- printf( "Source:\t\t%s\n", string1 );
- pdest = memccpy( buffer, string1, 's', 60 );
- *pdest = '\0';
- printf( "Result:\t\t%s\n", buffer );
- printf( "Length:\t\t%d characters\n\n", strlen( buffer ) );
-
- pos = pdest - buffer;
- printf( "Function:\tstrcpy\n" );
- printf( "Source:\t\t%s\n", string2 + pos );
- pdest = strcpy( buffer + pos, string2 + pos );
- printf( "Result:\t\t%s\n", buffer );
- printf( "Length:\t\t%d characters\n\n", strlen( buffer ) );
-
- printf( "Function:\tmemcpy 20 characters\n" );
- printf( "Source:\t\t%s\n", string2 );
- memcpy( buffer, string2, 20 );
- printf( "Result:\t\t%s\n", buffer );
- printf( "Length:\t\t%d characters\n\n", strlen( buffer ) );
-
- printf( "Function:\tstrncpy 30 characters\n" );
- printf( "Source:\t\t%s\n", string1 + 20 );
- pdest = strncpy( buffer + 20, string1 + 20, 30 );
- printf( "Result:\t\t%s\n", buffer );
- printf( "Length:\t\t%d characters\n\n", strlen( buffer ) );
-
- getch();
-
- printf( "Function:\tstrdup\n" );
- printf( "Source:\t\t%s\n", buffer );
- newstring = strdup( buffer );
- printf( "Result:\t\t%s\n", newstring );
- printf( "Length:\t\t%d characters\n\n", strlen( newstring ) );
-
- /* Illustrate overlapping copy: memmove handles it correctly;
- * memcpy does not.
- */
- printf( "Function:\tmemcpy with overlap\n" );
- printf( "Source:\t\t%s\n", string1 + 4 );
- printf( "Destination:\t%s\n", string1 + 10 );
- memcpy( string1 + 10, string1 + 4, 40 );
- printf( "Result:\t\t%s\n", string1 );
- printf( "Length:\t\t%d characters\n\n", strlen( string1 ) );
-
- printf( "Function:\tmemmove with overlap\n" );
- printf( "Source:\t\t%s\n", string2 + 4 );
- printf( "Destination:\t%s\n", string2 + 10 );
- memmove( string2 + 10, string2 + 4, 40 );
- printf( "Result:\t\t%s\n", string2 );
- printf( "Length:\t\t%d characters\n\n", strlen( string2 ) );
- }
-
-
- DECRMENT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\DECRMENT.C
-
- /* DECRMENT.C: Demonstrate prefix and postfix operators.
- */
-
- #include <stdio.h>
- main()
- {
- int val, sample = 3, proton = 3;
- val = sample--;
- printf( "val = %d sample = %d\n", val, sample );
- val = --proton;
- printf( "val = %d proton = %d\n", val, proton );
- }
-
-
- DIRECT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\DIRECT.C
-
- /* DIRECT.C illustrates directory functions and miscellaneous file
- * and other functions including:
- * getcwd mkdir chdir rmdir
- * system mktemp remove unlink
- * stat
- *
- * See NULLFILE.C for an example of fstat, which is similar to stat.
- */
-
- #include <direct.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <conio.h>
- #include <io.h>
- #include <time.h>
- #include <sys/types.h>
- #include <sys/stat.h>
-
- main()
- {
- char cwd[_MAX_DIR];
- static char tmpdir[] = "DRXXXXXX";
- struct stat filestat;
-
- /* Get the current working directory. */
- getcwd( cwd, _MAX_DIR );
-
- /* Try to make temporary name for directory. */
- if( mktemp( tmpdir ) == NULL )
- {
- perror( "Can't make temporary directory" );
- exit( 1 );
- }
-
- /* Try to create a new directory, and if successful, change to it. */
- if( !mkdir( tmpdir ) )
- {
- chdir( tmpdir );
-
- /* Create and display a file to prove it. */
- system( "echo This is a test. > TEST.TXT" );
- system( "type test.txt" );
-
- /* Display some file statistics. */
- if( !stat( "TEST.TXT", &filestat ) )
- {
- printf( "File: TEST.TXT\n" );
- printf( "Drive %c:\n", filestat.st_dev + 'A' );
- printf( "Directory: %s\\%s\n", cwd + 2, tmpdir );
- printf( "Size: %ld\n", filestat.st_size );
- printf( "Created: %s", ctime( &filestat.st_atime ) );
- }
- getch();
-
- /* Delete file, go back to original directory, and remove
- * directory. Note that under DOS, remove is equivalent to unlink,
- * so this line could be used instead.
- unlink( "TEST.TXT" );
- */
- remove( "TEST.TXT" );
- chdir( cwd );
- rmdir( tmpdir );
- }
- }
-
-
- DISK.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\DISK.C
-
- /* DISK.C illustrates low-level disk access using functions:
- * _bios_disk _dos_getdiskfree
- */
-
- #include <stdio.h>
- #include <conio.h>
- #include <bios.h>
- #include <dos.h>
- #include <stdlib.h>
-
- char far diskbuf[512];
-
- main( int argc, char *argv[] )
- {
- unsigned status = 0, i;
- struct diskinfo_t di;
- struct diskfree_t df;
- unsigned char far *p, linebuf[17];
-
- if( argc != 5 )
- {
- printf( " SYNTAX: DISK <driveletter> <head> <track> <sector>" );
- exit( 1 );
- }
-
- if( (di.drive = toupper( argv[1][0] ) - 'A' ) > 1 )
- {
- printf( "Must be floppy drive" );
- exit( 1 );
- }
- di.head = atoi( argv[2] );
- di.track = atoi( argv[3] );
- di.sector = atoi( argv[4] );
- di.nsectors = 1;
- di.buffer = diskbuf;
-
- /* Get information about disk size. */
- if( _dos_getdiskfree( di.drive + 1, &df ) )
- exit( 1 );
-
- /* Try reading disk three times before giving up. */
- for( i = 0; i < 3; i++ )
- {
- status = _bios_disk( _DISK_READ, &di ) >> 8;
- if( !status )
- break;
- }
-
- /* Display one sector. */
- if( status )
- printf( "Error: 0x%.2x\n", status );
- else
- {
- for( p = diskbuf, i = 0; p < (diskbuf + df.bytes_per_sector); p++ )
- {
- linebuf[i++] = (*p > 32) ? *p : '.';
- printf( "%.2x ", *p );
- if( i == 16 )
- {
- linebuf[i] = '\0';
- printf( " %16s\n", linebuf );
- i = 0;
- }
- }
- }
- exit( 1 );
- }
-
-
- DO.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\DO.C
-
- /* DO.C: Demonstrate do loop. */
-
- #include <stdio.h>
-
- main()
- {
- int test = 10;
- do
- {
- printf( "test = %d\n", test );
- test -= 2;
- } while( test > 0 );
- }
-
-
- DOSMEM.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\MEMORY\DOSMEM.C
-
- /* DOSMEM.C illustrates functions:
- * _dos_allocmem _dos_setblock _dos_freemem
- *
- * See COPY2.C for another example of _dos_allocmem and _dos_freemem.
- */
-
- #include <dos.h>
- #include <stdio.h>
- #include <stdlib.h>
-
- main()
- {
- char far *buf = NULL, far *p;
- unsigned segbuf, maxbuf, size = 512;
-
- /* Allocate 512-byte buffer. Convert the size to paragraphs).
- * Assign the segment to the buffer. Fill with A's.
- */
- if( _dos_allocmem( size >> 4, &segbuf ) )
- exit( 1 );
- FP_SEG( buf ) = segbuf;
- for( p = buf; p < (buf + size); p++ )
- *p = 'A';
-
- /* Double the allocation. Fill the second half with B's. */
- size *= 2;
- if( _dos_setblock( size >> 4, segbuf, &maxbuf ) )
- exit( 1 );
- FP_SEG( buf ) = segbuf;
- for( p = buf + (size / 2); p < (buf + size); p++ )
- *p = 'B';
- *(--p) = '\0';
-
- printf( "Memory available: %u paragraphs\n", maxbuf );
- printf( "Buffer at %Fp contains:\n%Fs", (int far *)buf, buf );
-
- /* Free memory */
- exit( !_dos_freemem( segbuf ) );
- }
-
-
- EGA.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\EGA.C
-
- /* EGA.C: Demonstrates EGA palettes */
- #include <stdio.h>
- #include <conio.h>
- #include <graph.h>
-
- main()
- {
- _setvideomode( _ERESCOLOR );
- _setcolor( 4 );
- _rectangle( _GFILLINTERIOR, 50, 50, 200, 200 );
-
- _settextposition( 1, 1 );
- printf( "Normal palette\n" );
- printf( "Press a key" );
- getch();
-
- _remappalette( 4, _BLUE );
-
- _settextposition( 1, 1 );
- printf( "Remapped palette\n" );
- printf( "Press a key" );
- getch();
-
- _remappalette( 4, _RED );
-
- _settextposition( 1, 1 );
- printf( "Restored palette\n" );
- printf( "Press a key to clear the screen" );
- getch();
-
- _clearscreen( _GCLEARSCREEN );
- _setvideomode( _DEFAULTMODE );
- }
-
-
- ELSE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\ELSE.C
-
- /* ELSE.C: Demonstrate else clause. */
-
- #include <stdio.h>
- #include <conio.h>
- #define B_KEY 'b'
-
- main()
- {
- char ch;
- printf( "Press the b key to hear a bell.\n" );
- ch = getch();
- if( ch == B_KEY )
- printf( "Beep!\a\n" );
- else
- printf( "Bye bye.\n" );
- }
-
-
- ELSE1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\ELSE1.C
-
- /* ELSE1.C: Demonstrate else-if construct. */
-
- #include <stdio.h>
- #include <conio.h>
- #define B_KEY 'b'
- #define ENTER_KEY '\r'
-
- main()
- {
- char ch;
- printf( "Press the b key to hear a bell.\n" );
- ch = getch();
- if( ch == B_KEY )
- printf( "Beep!\a\n" );
- else
- if( ch == ENTER_KEY )
- printf( "What a boring selection...\n" );
- else
- printf( "Bye bye.\n" );
- }
-
-
- EMPLOY1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\EMPLOY1.C
-
- /* EMPLOY1.C: Demonstrate structure pointers. */
-
- #include <stdio.h>
-
-
- struct employee
- {
- char name[10];
- int months;
- float wage;
- };
-
- void display( struct employee *e_ptr );
-
- main()
- {
- static struct employee jones =
- {
- "Jones, J",
- 77,
- 13.68
- };
-
- display( &jones );
- }
-
- void display( struct employee *e_ptr )
- {
- printf( "Name: %s\n", e_ptr->name );
- printf( "Months of service: %d\n", e_ptr->months );
- printf( "Hourly wage: %6.2f\n", e_ptr->wage );
- }
-
-
- EMPLOYEE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\EMPLOYEE.C
-
- /* EMPLOYEE.C: Demonstrate structures. */
-
- #include <stdio.h>
- #include <string.h>
-
- struct employee
- {
- char name[10];
- int months;
- float wage;
- };
-
- void display( struct employee show );
-
- main()
- {
- struct employee jones;
-
- strcpy( jones.name, "Jones, J" );
- jones.months = 77;
- jones.wage = 13.68;
-
- display( jones );
- }
-
- void display( struct employee show )
- {
- printf( "Name: %s\n", show.name );
- printf( "Months of service: %d\n", show.months );
- printf( "Hourly wage: %6.2f\n", show.wage );
- }
-
-
- ENVIRON1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\ENVIRON1.C
-
- /* ENVIRON.C illustrates environment variable functions including:
- * getenv putenv _searchenv
- */
-
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
-
- main()
- {
- char *pathvar, pathbuf[128], filebuf[128];
-
- /* Get the PATH environment variable and save a copy of it. */
- pathvar = getenv( "PATH" );
- strcpy( pathbuf, pathvar );
- printf( "Old PATH: %s\n", pathvar ? pathvar : "variable not set");
-
- /* Add a new directory to the path. */
- strcat( pathbuf, ";\\QC;" );
- if( putenv( pathbuf ) == -1 )
- {
- printf( "Failed\n");
- return 1;
- }
- else
- printf( "New PATH: %s\n", pathbuf );
-
- /* Search for file in the new path. */
- _searchenv( "QC.INI", "PATH", filebuf );
- if( *filebuf )
- printf( "QC.INI found at %s\n", filebuf );
- else
- printf( "QC.INI not found\n" );
-
- /* Restore original path. */
- if( putenv( pathvar ) == -1 )
- printf( "Failed\n");
- else
- printf( "Old PATH: %s\n", pathvar );
- return 0;
- }
-
-
- ERROR.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\ERROR.C
-
- /* ERROR.C illustrates stream file error handling. Functions illustrated
- * include:
- * ferror clearerr exit _exit
- * perror strerror _strerror
- *
- * The _exit routine is not specifically illustrated, but it is the same
- * as exit except that file buffers are not flushed and atexit and onexit
- * are not called.
- */
-
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <errno.h>
- enum BOOL { FALSE, TRUE };
-
- FILE *stream;
- char string[] = "This should never be written";
- void errortest( FILE *stream, char *msg, int fterm );
-
- main( int argc, char *argv[] )
- {
- /* Open file and test to see if open caused error. If so, terminate. */
- stream = fopen( argv[1], "r" );
- errortest( stream, "Can't open file", TRUE );
-
- /* Try to write to a read-only file, then test to see if write
- * caused error. If so, clear error, but don't terminate.
- */
- fprintf( stream, "%s\n", string );
- errortest( stream, "Can't write file", FALSE );
- exit( 0 );
- }
-
- /* Error test routine takes a stream, a message, and a flag telling whether
- * to terminate if there is an error.
- */
- void errortest( FILE *stream, char *msg, int fterm )
- {
- /* If stream doesn't exist (failed fopen) or if there is an error
- * on the stream, handle error.
- */
- if( (stream == NULL) || (ferror( stream )) )
- {
- perror( msg );
- /* _strerror and strerror can be used to get the same result
- * as perror, as illustrated by these lines (commented out).
- printf( "%s: %s\n", msg, strerror( errno ) );
- printf( _strerror( msg ) );
- */
-
- /* Terminate or clear error, depending on terminate flag. */
- if( fterm )
- exit( errno );
- else
- clearerr( stream );
- }
- }
-
-
- EXEC.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\EXEC.C
-
- /* EXEC.C illustrates the different versions of exec including:
- * execl execle execlp execlpe
- * execv execve execvp execvpe
- *
- * Although EXEC.C can exec any program, you can verify how different
- * versions handle arguments and environment by compiling and
- * specifying the sample program ARGS.C. See SPAWN.C for examples
- * of the similar spawn functions.
- */
-
- #include <stdio.h>
- #include <conio.h>
- #include <process.h>
-
- char *my_env[] = /* Environment for exec?e */
- {
- "THIS=environment will be",
- "PASSED=to child by the",
- "SPAWN=functions",
- NULL
- };
-
- main()
- {
- char *args[4], prog[80];
- int ch;
-
- printf( "Enter name of program to exec: " );
- gets( prog );
- printf( " 1. execl 2. execle 3. execlp 4. execlpe\n" );
- printf( " 5. execv 6. execve 7. execvp 8. execvpe\n" );
- printf( "Type a number from 1 to 8 (or 0 to quit): " );
- ch = getche();
- if( (ch < '1') || (ch > '8') )
- exit( 1 );
- printf( "\n\n" );
-
- /* Arguments for execv? */
- args[0] = prog; /* First argument ignored under most */
- args[1] = "exec??"; /* recent versions of DOS */
- args[2] = "two";
- args[3] = NULL;
-
- switch( ch )
- {
- case '1':
- execl( prog, prog, "execl", "two", NULL );
- break;
- case '2':
- execle( prog, prog, "execle", "two", NULL, my_env );
- break;
- case '3':
- execlp( prog, prog, "execlp", "two", NULL );
- break;
- case '4':
- execlpe( prog, prog, "execlpe", "two", NULL, my_env );
- break;
- case '5':
- execv( prog, args );
- break;
- case '6':
- execve( prog, args, my_env );
- break;
- case '7':
- execvp( prog, args );
- break;
- case '8':
- execvpe( prog, args, my_env );
- break;
- default:
- break;
- }
-
- /* This point is only reached if exec fails. */
- printf( "\nProcess was not execed." );
- exit( 0 );
- }
-
-
- EXTDIR.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\EXTDIR.C
-
- /* EXTDIR.C illustrates wild card handling using functions:
- * _dos_findfirst _dos_findnext sprintf
- */
-
- #include <stdlib.h>
- #include <stdio.h>
- #include <conio.h>
- #include <ctype.h>
- #include <dos.h>
- #include <io.h>
- #include <sys\types.h>
- #include <sys\utime.h>
- #include <sys\stat.h>
-
- long fileinfo( struct find_t *find ); /* Prototypes */
- char *timestr( unsigned d, char *buf );
- char *datestr( unsigned d, char *buf );
-
- main( int argc, char *argv[] )
- {
- struct find_t find;
- long size;
-
- /* Find first matching file, then find additional matches. */
- if( !_dos_findfirst( argv[1], 0xffff, &find ) )
- {
- printf( "%-12s %-8s %-8s %-8s %-9s %s %s %s %s\n",
- "FILE", "SIZE", "TIME", "DATE", "KIND",
- "RDO", "HID", "SYS", "ARC" );
- size = fileinfo( &find );
- }
- else
- {
- printf( " SYNTAX: TOUCH <wildfilespec>" );
- exit( 1 );
- }
- while( !_dos_findnext( &find ) )
- size += fileinfo( &find );
- printf( "%-12s %8ld\n\n", "Total", size );
- exit( 0 );
- }
-
- long fileinfo( struct find_t *pfind )
- {
- char timebuf[10], datebuf[10], *pkind;
-
- datestr( pfind->wr_date, datebuf );
- timestr( pfind->wr_time, timebuf );
-
- if( pfind->attrib & _A_SUBDIR )
- pkind = "Directory";
- else if( pfind->attrib & _A_VOLID )
- pkind = "Label";
- else
- pkind = "File";
-
- printf( "%-12s %8ld %8s %8s %-9s %c %c %c %c\n",
- pfind->name, pfind->size, timebuf, datebuf, pkind,
- (pfind->attrib & _A_RDONLY) ? 'Y' : 'N',
- (pfind->attrib & _A_HIDDEN) ? 'Y' : 'N',
- (pfind->attrib & _A_SYSTEM) ? 'Y' : 'N',
- (pfind->attrib & _A_ARCH) ? 'Y' : 'N' );
- return pfind->size;
- }
-
- /* Take unsigned time in the format: fedcba9876543210
- * s=2 sec incr, m=0-59, h=23 hhhhhmmmmmmsssss
- * Change to a 9-byte string (ignore seconds): hh:mm ?m
- */
- char *timestr( unsigned t, char *buf )
- {
- int h = (t >> 11) & 0x1f, m = (t >> 5) & 0x3f;
-
- sprintf( buf, "%2.2d:%02.2d %cm", h % 12, m, h > 11 ? 'p' : 'a' );
- return buf;
- }
-
- /* Take unsigned date in the format: fedcba9876543210
- * d=1-31, m=1-12, y=0-119 (1980-2099) yyyyyyymmmmddddd
- * Change to a 9-byte string: mm/dd/yy
- */
- char *datestr( unsigned d, char *buf )
- {
- sprintf( buf, "%2.2d/%02.2d/%02.2d",
- (d >> 5) & 0x0f, d & 0x1f, (d >> 9) + 80 );
- return buf;
- }
-
-
- EXTERR.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\EXTERR.C
-
- /* EXTERR.C illustrates function:
- * dosexterr
- */
-
- #include <dos.h>
- #include <fcntl.h>
- #include <stdio.h>
- #include <stdlib.h>
-
- void errorinfo( void ); /* Prototype */
-
- main( int argc, char *argv[] )
- {
- int hsource;
-
- /* Open to get file handle and test for errors. Try specifying
- * invalid files to show different errors.
- */
- if( _dos_open( argv[1], O_RDWR, &hsource ) )
- errorinfo();
- printf( "No error\n" );
- _dos_close( hsource );
- exit( 0 );
- }
-
- void errorinfo()
- {
- struct DOSERROR err;
- static char *eclass[] =
- {
- "", "Out of Resource", "Temporary Situation", "Authorization",
- "Internal", "Hardware Failure", "System Failure", "Application Error"
- "Not Found", "Bad Format", "Locked", "Media", "Already Exists",
- "Unknown"
- };
- static char *eaction[] =
- {
- "", "Retry", "Delay Retry", "User", "Abort", "Immediate Exit",
- "Ignore", "Retry After User Intervention"
- };
- static char *elocus[] =
- {
- "", "Unknown", "Block Device", "Net", "Serial Device", "Memory"
- };
-
-
- /* Get error information and display class, action, and locus. */
- dosexterr( &err );
- printf( "Class:\t%s\nAction:\t%s\nLocus:\t%s\nAction\t",
- eclass[err.class], eaction[err.action], elocus[err.locus] );
-
- /* Errors that could be caused by sample _dos_open. You can expand
- * this list to handle others.
- */
- switch( err.exterror )
- {
- case 2:
- printf( "File not found\n" );
- break;
- case 3:
- printf( "Path not found\n" );
- break;
- case 5:
- printf( "Access denied\n" );
- break;
- }
- exit( err.exterror );
- }
-
-
- FACTOR.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\FACTOR.C
-
- /* FACTOR.C: Demonstrate functions.
- * NOTE: a value > 16 will overflow a long integer.
- */
-
- #include <stdio.h>
-
- long factor( int param );
-
- main()
- {
- int num;
- long result;
- /* Display a prompt */
- printf( "Type a number: " );
- /* Input a numeric value, assign to num */
- scanf( "%d", &num );
- result = factor( num );
- printf( "Factorial of %d is %ld\n", num, result );
- }
-
- long factor( int param )
- {
- long value = 1;
- while( param > 1 )
- {
- value = value * param;
- param = param - 1;
- }
- return value;
- }
-
-
- FCVT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\FCVT.C
-
- /* FCVT.C illustrates floating point to string conversion functions:
- * gcvt ecvt fcvt
- *
- * See MKFPSTR.C for an example of using the data returned by fcvt
- * to build a formatted string. See ATONUM.C for an example of using
- * the string returned by gcvt.
- */
-
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
-
- main()
- {
- int decimal, sign;
- char *pnumstr;
- int precision = 7;
- char numbuf[50];
- double number1, number2;
-
- printf( "Enter two floating point numbers: " );
- scanf( "%lf %lf", &number1, &number2 );
-
- /* With gcvt, precision specifies total number of digits.
- * The decimal place and sign are inserted in the string.
- */
- gcvt( number1 + number2, precision, numbuf );
- printf( "\nString produced by gcvt: %s\n", numbuf );
- printf( "Total digits: %d\n", precision );
-
- /* With ecvt, precision specifies total number of digits.
- * The decimal place and sign are provided for use in formatting.
- */
- pnumstr = ecvt( number1 + number2, precision, &decimal, &sign );
- printf( "\nString produced by ecvt: %s\nSign: %s\n",
- pnumstr, sign ? "-" : "+" );
- printf( "Digits left of decimal: %d\nTotal digits: %d\n",
- decimal, precision );
-
- /* With fcvt, precision specifies digits after decimal place.
- * The decimal place and sign are provided for use in formatting.
- */
- pnumstr = fcvt( number1 + number2, precision, &decimal, &sign );
- printf( "\nString produced by fcvt: %s\nSign: %s\n",
- pnumstr, sign ? "-" : "+" );
- printf( "Digits left of decimal: %d\nDigits after decimal: %d\n",
- decimal, precision );
- }
-
-
- FIGURE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\FIGURE.C
-
- /* FIGURE.C illustrates graphics drawing functions including:
- * _setpixel _lineto _moveto _rectangle _ellipse
- * _arc _pie
- *
- * Window versions of graphics drawing functions (such as _rectangle_w,
- * _ellipse_wxy, and _lineto_w) are illustrated in WINDOW.C and GEDIT.C.
- */
-
- #include <conio.h>
- #include <stdlib.h>
- #include <graph.h>
-
- main()
- {
- short x, y;
- short mode = _VRES16COLOR;
-
- while( !_setvideomode( mode ) ) /* Find best graphics mode */
- mode--;
- if( mode == _TEXTMONO )
- exit( 1 ); /* No graphics available */
-
- for( x = 10, y = 50; y < 90; x += 2, y += 3 )/* Draw pixels */
- _setpixel( x, y );
- getch();
-
- for( x = 60, y = 50; y < 90; y += 3 ) /* Draw lines */
- {
- _moveto( x, y );
- _lineto( x + 20, y );
- }
- getch();
-
- x = 110; y = 70; /* Draw rectangles */
- _rectangle( _GBORDER, x - 20, y - 20, x, y );
- _rectangle( _GFILLINTERIOR, x + 20, y + 20, x, y );
- getch();
-
- x = 160; /* Draw ellipses */
- _ellipse( _GBORDER, x - 20, y - 20, x, y );
- _ellipse( _GFILLINTERIOR, x + 20, y + 20, x, y );
- getch();
-
- x = 210; /* Draw arcs */
- _arc( x - 20, y - 20, x, y, x, y - 10, x - 10, y );
- _arc( x + 20, y + 20, x, y, x + 10, y + 20, x + 20, y + 10 );
- getch();
-
- x = 260; /* Draw pies */
- _pie( _GBORDER, x - 20, y - 20, x, y, x, y - 10, x - 10, y );
- _pie( _GFILLINTERIOR, x + 20, y + 20, x, y,
- x + 10, y + 20, x + 20, y + 10 );
- getch();
-
- exit( !_setvideomode( _DEFAULTMODE ) );
- }
-
-
- FILEONE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\FILEONE.C
-
- /* FILEONE.C: Visibility in multiple source files.
- */
-
- int chico = 20, harpo = 30;
- extern void yonder( void );
-
- main()
- {
- yonder();
- }
-
-
- FILETWO.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\FILETWO.C
-
- /* FILETWO.C: Visibility in multiple source files.
- */
-
- #include <stdio.h>
-
- void yonder( void )
- {
- extern int chico, harpo;
- printf( "chico = %d, harpo = %d\n", chico, harpo );
- }
-
-
- FILL.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\FILL.C
-
- /* FILL.C illustrates color, filling, and linestyle functions including:
- * _setlinestyle _setfillmask _setcolor
- * _getlinestyle _floodfill
- *
- * The _getfillmask function is not shown, but its use is similar to
- * _getlinestyle.
- */
-
- #include <conio.h>
- #include <graph.h>
- #include <time.h>
- #include <stdlib.h>
-
- main()
- {
- short x, y, xinc, yinc, xwid, ywid;
- unsigned char fill[8];
- struct videoconfig vc;
- unsigned seed = (unsigned)time( 0L ); /* Different seed each time */
- short i, color, mode = _VRES16COLOR;
-
- while( !_setvideomode( mode ) ) /* Find best graphics mode */
- mode--;
- if (mode == _TEXTMONO )
- exit( 1 ); /* No graphics available */
- _getvideoconfig( &vc );
-
- xinc = vc.numxpixels / 8; /* Size variables to mode */
- yinc = vc.numxpixels / 8;
- xwid = (xinc / 2) - 4;
- ywid = (yinc / 2) - 4;
-
- /* Draw circles and lines with different patterns. */
- for( x = xinc; x <= (vc.numxpixels - xinc); x += xinc )
- {
- for( y = yinc; y <= (vc.numypixels - yinc); y += yinc )
- {
- /* Vary random seed, randomize fill and color. */
- srand( seed = (seed + 431) * 5 );
- for( i = 0; i < 8; i++ )
- fill[i] = rand();
- _setfillmask( fill );
- color = (rand() % vc.numcolors) + 1;
- _setcolor( color );
-
- /* Draw ellipse and fill with random color. */
- _ellipse( _GBORDER, x - xwid, y - ywid, x + xwid, y + ywid );
- _setcolor( (rand() % vc.numcolors) + 1 );
- _floodfill( x, y, color );
-
- /* Draw vertical and horizontal lines. Vertical line style
- * is opposite of (not) horizontal style. Since lines are
- * overdrawn with several linestyles, this has the effect of
- * combining colors and styles.
- */
- _setlinestyle( rand() );
- _moveto( 0, y + ywid + 4 );
- _lineto( vc.numxpixels - 1, y + ywid + 4 );
- _setlinestyle( ~_getlinestyle() );
- _moveto( x + xwid + 4, 0 );
- _lineto( x + xwid + 4, vc.numypixels - 1 );
- }
- }
- getch();
- exit( !_setvideomode( _DEFAULTMODE ) );
- }
-
-
- FINDSTR.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\FINDSTR.C
-
- /* FINDSTR.C illustrates memory and string search functions including:
- * memchr strchr strrchr strstr
- */
-
- #include <memory.h>
- #include <string.h>
- #include <stdio.h>
-
- int ch = 'r';
- char str[] = "lazy";
- char string[] = "The quick brown dog jumps over the lazy fox";
- char fmt1[] = " 1 2 3 4 5";
- char fmt2[] = "12345678901234567890123456789012345678901234567890";
-
- main()
- {
- char *pdest;
- int result;
-
- printf( "String to be searched:\n\t\t%s\n", string );
- printf( "\t\t%s\n\t\t%s\n\n", fmt1, fmt2 );
-
- printf( "Function:\tmemchr\n" );
- printf( "Search char:\t%c\n", ch );
- pdest = memchr( string, ch, sizeof( string ) );
- result = pdest - string + 1;
- if( pdest != NULL )
- printf( "Result:\t\t%c found at position %d\n\n", ch, result );
- else
- printf( "Result:\t\t%c not found\n" );
-
- printf( "Function:\tstrchr\n" );
- printf( "Search char:\t%c\n", ch );
- pdest = strchr( string, ch );
- result = pdest - string + 1;
- if( pdest != NULL )
- printf( "Result:\t\t%c found at position %d\n\n", ch, result );
- else
- printf( "Result:\t\t%c not found\n" );
-
- printf( "Function:\tstrrchr\n" );
- printf( "Search char:\t%c\n", ch );
- pdest = strrchr( string, ch );
- result = pdest - string + 1;
- if( pdest != NULL )
- printf( "Result:\t\t%c found at position %d\n\n", ch, result );
- else
- printf( "Result:\t\t%c not found\n" );
-
- printf( "Function:\tstrstr\n" );
- printf( "Search string:\t%s\n", str );
- pdest = strstr( string, str );
- result = pdest - string + 1;
- if( pdest != NULL )
- printf( "Result:\t\t%s found at position %d\n\n", str, result );
- else
- printf( "Result:\t\t%c not found\n" );
- }
-
-
- FOR1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\FOR1.C
-
- /* FOR1.C: Demonstrate multiple expressions. */
-
- #include <stdio.h>
-
- main()
- {
- int a, b;
- for( a = 256, b = 1; b < 512; a /= 2, b *= 2 )
- printf( "a = %d b = %d\n", a, b );
- }
-
-
- FOR2.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\FOR2.C
-
- /* FOR2.C: Demonstrate variations on for loop. */
-
- #include <stdio.h>
- #include <conio.h>
-
- main()
- {
- for( printf( "Type something\n" ); getche() != '\r'; )
- ; /* Null statement */
- }
-
-
- FOR3.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\FOR3.C
-
- /* FOR3.C: Demonstrate similarity of for and while.
- */
-
- #include <stdio.h>
-
- main()
- {
- int count;
-
- for( count = 0; count < 10; count++ )
- printf( "count = %d\n", count );
-
- count = 0;
- while( count < 10 )
- {
- printf( "count = %d\n", count );
- count++;
- }
-
- }
-
-
- FOR4.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\FOR4.C
-
- /* FOR.C: Demonstrate for loop. */
-
- #include <stdio.h>
-
- main()
- {
- int test;
- for( test = 10; test > 0; test -= 2 )
- printf( "test = %d\n", test );
- }
-
-
- FREECT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\FREECT.C
-
- /* FREECT.C illustrates the following heap functions:
- * _freect _memavl
- */
-
- #include <malloc.h>
- #include <stdio.h>
-
- main()
- {
- char near *bufs[64];
- unsigned request, avail, i;
-
- printf( "Near heap bytes free: %u\n\n", _memavl() );
- printf( "How many 1K buffers do you want from the near heap? " );
- scanf( "%d", &request );
- if( request > 64 )
- {
- printf( "There are only 64K in a segment.\n" );
- request = 64;
- }
-
- avail = _freect( 1024 );
- request = (avail > request) ? request : avail;
- printf( "You can have %d buffers\n", request );
-
- printf( "They are available at:\n");
- for( i = 0; i < request; i++ )
- {
- bufs[i] = (char near *)_nmalloc( 1024 );
- printf( "%2d %Fp ", i + 1, (char far *)bufs[i] );
- if( (i % 5) == 4 )
- printf( "\n" );
- }
- printf( "\n\nNear heap bytes free: %u\n\n", _memavl() );
- printf( "Freeing buffers . . ." );
- for( i = request; i; i-- )
- _nfree( bufs[i] );
- printf( "\n\nNear heap bytes free: %u", _memavl() );
- }
-
-
- FSAMPLER.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\FSAMPLER.C
-
- /* SAMPLER.C: Display sample text in various fonts.
- */
-
- #include <stdio.h>
- #include <conio.h>
- #include <stdlib.h>
- #include <graph.h>
- #include <string.h>
-
- #define NFONTS 6
-
- main()
-
- {
- static unsigned char *text[2*NFONTS] =
- {
- "COURIER", "courier",
- "HELV", "helv",
- "TMS RMN", "tms rmn",
- "MODERN", "modern",
- "SCRIPT", "script",
- "ROMAN", "roman"
- };
- static unsigned char *face[NFONTS] =
- {
- "t'courier'",
- "t'helv'",
- "t'tms rmn'"
- "t'modern'"
- "t'script'"
- "t'roman'"
- };
- static unsigned char list[20];
- struct videoconfig vc;
- int mode = _VRES16COLOR;
- register i;
-
- /* Read header info from all .FON files in
- * current directory */
-
- if(_registerfonts( "*.FON" )<0 )
- {
- _outtext("Error: can't register fonts");
- exit( 0 );
- }
-
- /* Set highest available video mode */
-
- while( !_setvideomode( mode ) )
- mode--;
- if( mode == _TEXTMONO )
- exit ( 0 );
-
- /* Copy video configuration into structure vc */
-
- _getvideoconfig( &vc );
-
- /* Display six lines of sample text */
-
- for( i = 0; i<NFONTS; i++ )
- {
- strcpy( list, face[i] );
- strcat( list, "h30w24b" );
-
- if( !_setfont( list ) )
- {
- _setcolor( i + 1 );
- _moveto( 0, (i * vc.numypixels) / NFONTS );
- _outgtext( text[i * 2] );
- _moveto( vc.numxpixels / 2,
- (i * vc.numypixels) / NFONTS );
- _outgtext( text[(i * 2) + 1] );
- }
- else
- {
- _setvideomode( _DEFAULTMODE );
- _outtext( "Error: can't set font" );
- exit( 0 );
- }
- }
- getch();
- _setvideomode( _DEFAULTMODE );
-
- /* Return memory when finished with fonts */
-
- _unregisterfonts();
- exit( 0 );
- }
-
-
- FUNCPTR.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\FUNCPTR.C
-
- /* FUNCPTR.C: Demonstrate function pointers. */
-
- #include <stdio.h>
-
- main()
- {
- int (*func_ptr) ();
- func_ptr = printf;
- (*func_ptr) ( "Curiouser and curiouser...\n" );
- }
-
-
- FUNCPTR1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\FUNCPTR1.C
-
- /* FUNCPTR1.C: Passing function pointers as arguments.
- */
-
- #include <stdio.h>
-
- void gimme_func( void (*func_ptr) () );
-
- main()
- {
- gimme_func( puts );
- gimme_func( printf );
- }
-
- void gimme_func( void (*func_ptr) () )
- {
- (*func_ptr) ( "Ausgezeichnet!" );
- }
-
-
- FUNGET.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\FUNGET.C
-
- /* FUNGET.C illustrates getting and ungetting characters from a file.
- * Functions illustrated include:
- * getc getchar ungetc
- * fgetc fgetchar
- *
- * Although getchar and fgetchar are not specifically used in the example,
- * they are equivalent to using getc or fgetc with stdin. See HEXDUMP.C
- * for another example of getc and fgetc.
- */
-
- #include <conio.h>
- #include <stdio.h>
- #include <ctype.h>
- #include <string.h>
- #include <stdlib.h>
-
- void getword( FILE *stream, char *buf );
- void skiptoword( FILE *stream );
-
- main()
- {
- char buffer[128];
- FILE *infile;
-
- printf( "Enter file name: " );
- gets( buffer );
- if( (infile = fopen( buffer, "rb" )) == NULL )
- {
- perror( "Can't open file" );
- exit( 1 );
- }
-
- /* Read each word and print reversed version. */
- while( 1 )
- {
- skiptoword( infile );
- getword( infile, buffer );
- puts( strrev( buffer ) );
- }
- }
-
- /* Read one word (defined as a string of alphanumeric characters). */
- void getword( FILE *stream, char *p )
- {
- int ch;
-
- do
- {
- /* Macro version used here, but function version could be used:
- ch = fgetc( stream );
- */
- ch = getc( stream ); /* Get characters until EOF */
- if( ch == EOF ) /* or non-alphanumeric */
- exit( 0 );
- *(p++) = (char)ch;
- } while( isalnum( ch ) );
- ungetc( ch, stream ); /* Put non-alphanumeric back */
- *(--p) = '\0'; /* Null-terminate */
- }
-
- /* Throw away non-digit characters. */
- void skiptoword( FILE *stream )
- {
- int ch;
-
- do
- {
- ch = getc( stream );
- if( ch == EOF )
- exit( 0 );
- } while( !isalnum( ch ) );
- ungetc( ch, stream );
- }
-
-
- GETCH.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\GETCH.C
-
- /* GETCH.C illustrates how to process ASCII or extended keys.
- * Functions illustrated include:
- * getch getche
- */
-
- #include <conio.h>
- #include <ctype.h>
- #include <stdio.h>
-
- main()
- {
- int key;
-
- /* Read and display keys until ESC is pressed. */
- while( 1 )
- {
- /* If first key is 0, then get second extended. */
- if( !(key = getch()) )
- {
- key = getch();
- printf( "ASCII: no\tChar: NA\t" );
- }
-
- /* Otherwise there's only one key. */
- else
- printf( "ASCII: yes\tChar: %c \t", isgraph( key ) ? key : ' ' );
-
- printf( "Decimal: %d\tHex: %X\n", key, key );
-
- /* Echo character response to prompt. */
- if( key == 27)
- {
- printf( "Do you really want to quit? (Y/n) " );
- key = getche();
- printf( "\n" );
- if( (toupper( key ) == 'Y') || (key == 13) )
- break;
- }
- }
- }
-
-
- GOODMAC.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\GOODMAC.C
-
- /* GOODMAC.C: Parentheses in macro arguments. */
- #include <stdio.h>
-
- #define FOURX(arg) ( (arg) * 4 )
-
- main()
- {
- int val;
- val = FOURX( 2 + 3 );
- printf( "val = %d\n", val );
- }
-
-
- GOODSEMI.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\GOODSEMI.C
-
- /* GOODSEMI.C */
-
- #include <stdio.h>
-
- main()
- {
- int count;
- for( count = 0; count < 500; count++ )
- {
- printf( "count = %d\n", count );
- printf( "And the beat goes on...\n" );
- }
- }
-
-
- GRAPHIC.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\GRAPHIC.C
-
- /* GRAPHIC.C: Displays every graphics mode */
-
- #include <stdio.h>
- #include <graph.h>
- #include <conio.h>
-
- struct videoconfig screen;
- int modes[12] =
- {
- _MRES4COLOR, _MRESNOCOLOR, _HRESBW,
- _HERCMONO,
- _MRES16COLOR, _HRES16COLOR, _ERESNOCOLOR, _ERESCOLOR,
- _VRES2COLOR, _VRES16COLOR, _MRES256COLOR
- };
-
- void print_menu( void );
- void show_mode( char );
-
- main()
- {
- char key;
- print_menu();
- while( (key = getch()) != 'x' )
- show_mode( key );
- }
-
- void print_menu( void )
- {
- _setvideomode( _DEFAULTMODE );
- _clearscreen( _GCLEARSCREEN );
- printf( "Please choose a graphics mode\nType 'x' to exit.\n\n" );
- printf( "0 _MRES4COLOR\n1 _MRESNOCOLOR\n2 _HRESBW\n" );
- printf( "3 _HERCMONO\n4 _MRES16COLOR\n5 _HRES16COLOR\n" );
- printf( "6 _ERESNOCOLOR\n7 _ERESCOLOR\n" );
- printf( "8 _VRES2COLOR\n9 _VRES16COLOR\na _MRES256COLOR\n" );
- }
-
- void show_mode( char which )
- {
- int nc, i;
- int height, width;
- int mode = which;
-
- if( mode < '0' || mode > '9' )
- if( mode == 'a' )
- mode = '9' + 1;
- else if( mode == 'b' )
- mode = '9' + 2;
- else
- return;
-
- if( _setvideomode( modes[mode - '0'] ) )
- {
- _getvideoconfig( &screen );
- nc = screen.numcolors;
- width = screen.numxpixels/nc;
- height = screen.numypixels/2;
- for( i = 0; i < nc; i++ )
- {
- _setcolor( i );
- _rectangle( _GFILLINTERIOR, i * width, 0, (i + 1) * width, height );
- }
- }
- else
- {
- printf( " \nVideo mode %c is not available.\n", which);
- printf( "Please press a key.\n" );
- }
- getch();
- _setvideomode( _DEFAULTMODE );
- print_menu();
- }
-
-
- HALLOC.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\MEMORY\HALLOC.C
-
- /* HALLOC.C illustrates dynamic allocation of huge memory using functions:
- * halloc hfree
- */
-
- #include <stdio.h>
- #include <malloc.h>
- #include <stdlib.h>
-
- main()
- {
- char huge *bigbuf, huge *p;
- long count = 100000L;
-
- /* Allocate huge buffer. */
- bigbuf = (char huge *)halloc( count, sizeof( char ) );
- if( bigbuf == NULL )
- {
- printf( "Insufficient memory" );
- exit( 1 );
- }
-
- /* Fill the buffer with characters. */
- for( p = bigbuf; count; count--, p++ )
- *p = (char)(count % 10) + '0';
-
- /* Free huge buffer. */
- hfree( bigbuf );
- exit( 0 );
- }
-
-
- HARDERR.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\HARDERR.C
-
- /* HARDERR.C illustrates handling of hardware errors using functions:
- * _harderr _hardresume _hardretn
- */
-
- #include <stdio.h>
- #include <conio.h>
- #include <stdlib.h>
- #include <direct.h>
- #include <string.h>
- #include <dos.h>
- #include <bios.h>
-
- void far hardhandler( unsigned deverr, unsigned doserr, unsigned far *hdr );
- int _bios_str( char *p );
-
- main()
- {
- /* Install our hard error handler. */
- _harderr( hardhandler );
-
- /* Test it. */
- printf( "Make sure there is no disk in drive A:\n" );
- printf( "Press a key when ready...\n" );
- getch();
- if( mkdir( "a:\test" ) )
- {
- printf( "Failed" );
- exit( 1 );
- }
- else
- {
- printf( "Succeeded" );
- rmdir( "a:test" );
- exit( 0 );
- }
- }
-
- /* Handler to deal with hard error codes. Since DOS is not reentrant,
- * it is not safe use DOS calls to do I/O within the DOS Critical Error
- * Handler (int 24h) used by _harderr. Therefore, screen output and
- * keyboard input must be done through the BIOS.
- */
- void far hardhandler( unsigned deverr, unsigned doserr, unsigned far *hdr )
- {
- int ch;
- static char buf[200], tmpbuf[10];
-
- /* Copy message to buffer, then use BIOS to print it. */
- strcpy( buf, "\n\rDevice error code: " );
- strcat( buf, itoa( deverr, tmpbuf, 10 ) );
- strcat( buf, "\n\rDOS error code: " );
- strcat( buf, itoa( doserr, tmpbuf, 10 ) );
- strcat( buf, "\n\r(R)etry, (F)ail, or (Q)uit? " );
-
- /* Use BIOS to write strings and get a key. */
- _bios_str( buf );
- ch = _bios_keybrd( _KEYBRD_READ ) & 0x00ff;
- _bios_str( "\n\r" );
-
- switch( ch )
- {
- case 'R':
- case 'r': /* Try again */
- default:
- _hardresume( _HARDERR_RETRY );
- case 'F':
- case 'f': /* Return to DOS with error code */
- _hardretn( doserr );
- case 'Q':
- case 'q': /* Quit program */
- _hardresume( _HARDERR_ABORT );
-
- }
- }
-
- /* Display a string using BIOS interrupt 0x0e (Write TTY). Return length
- * of string displayed.
- */
- int _bios_str( char *p )
- {
- union REGS inregs, outregs;
- char *start = p;
-
- inregs.h.ah = 0x0e;
- for( ; *p; p++ )
- {
- inregs.h.al = *p;
- int86( 0x10, &inregs, &outregs );
- }
- return p - start;
- }
-
-
- HEAPWALK.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\MEMORY\HEAPWALK.C
-
- /* HEAPWALK.C illustrates heap testing functions including:
- * _heapchk _fheapchk _nheapchk
- * _heapset _fheapset _nheapset
- * _heapwalk _fheapwalk _nheapwalk
- * _msize _fmsize _nmsize
- *
- * Only the model independent versions are shown. They map to the model
- * dependent versions, depending on the memory model.
- */
-
- #include <stdio.h>
- #include <conio.h>
- #include <malloc.h>
- #include <stdlib.h>
- #include <time.h>
-
- /* Macro to get a random integer within a specified range */
- #define getrandom( min, max ) ((rand() % (int)((max) - (min))) + (min) + 1)
-
- void heapdump( char fill );
- void heapstat( int status );
-
- main()
- {
- int *p[10], i;
-
- srand( (unsigned)time( 0L ) ); /* Seed with current time. */
-
- /* Check heap status. Should be OK at start of heap. */
- heapstat( _heapchk() );
-
- /* Now do some operations that affect the heap. In this example,
- * allocate random-size blocks.
- */
- for( i = 0; i < 10; i++ )
- {
- if( (p[i] = (int *)calloc( getrandom( 1, 10000 ),
- sizeof( int ) )) == NULL )
- {
- --i;
- break;
- }
- printf( "Allocated %u at %p\n", _msize( p[i] ), (void far *)p[i] );
- }
-
- /* Fill all free blocks with the test character. */
- heapstat( _heapset( 254 ) );
-
- /* In a real program, you might do operations here on the allocated
- * buffers. Then do heapdump to make sure none of the operations wrote
- * to free blocks.
- */
- heapdump( 254 );
-
- /* Do some more heap operations. */
- for( ; i >= 0; i-- )
- {
- free( p[i] );
- printf( "Deallocating %u at %p\n", _msize( p[i] ), (void far *)p[i] )
- }
-
- /* Check heap again. */
- heapdump( 254 );
- }
-
- /* Test routine to check each block in the heap. */
- void heapdump( char fill )
- {
- struct _heapinfo hi;
- int heapstatus, i;
- char far *p;
-
- /* Walk through entries, displaying results and checking free blocks. */
- printf( "\nHeap dump:\n" );
- hi._pentry = NULL;
- while( (heapstatus = _heapwalk( &hi )) == _HEAPOK )
- {
- printf( "\n\t%s block at %p of size %u\t",
- hi._useflag == _USEDENTRY ? "USED" : "FREE",
- hi._pentry, hi._size );
-
- /* For free entries, check each byte to see that it still has
- * only the fill character.
- */
- if( hi._useflag != _USEDENTRY )
- {
- for( p = (char far *)hi._pentry, i = 0; i < hi._size; p++, i++ )
- if( (char)*p != fill )
- break;
- if( i == hi._size )
- printf( "Not changed" );
- else
- printf( "Changed" );
- }
- }
- heapstat( heapstatus );
- }
-
- /* Report on the status returned by _heapwalk, _heapset, or _heapchk. */
- void heapstat( int status )
- {
- printf( "\nHeap status: " );
- switch( status )
- {
- case _HEAPOK:
- printf( "OK - heap is fine" );
- break;
- case _HEAPEMPTY:
- printf( "OK - empty heap" );
- break;
- case _HEAPEND:
- printf( "OK - end of heap" );
- break;
- case _HEAPBADPTR:
- printf( "ERROR - bad pointer to heap" );
- break;
- case _HEAPBADBEGIN:
- printf( "ERROR - bad start of heap" );
- break;
- case _HEAPBADNODE:
- printf( "ERROR - bad node in heap" );
- break;
- }
- printf( "\n\n" );
- }
-
-
- HEXDUMP1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\HEXDUMP1.C
-
- /* HEXDUMP.C illustrates directory splitting and character stream I/O.
- * Functions illustrated include:
- * _splitpath _makepath
- * fgetc fputc fgetchar fputchar
- * getc putc getchar putchar
- *
- * While fgetchar, getchar, fputchar, and putchar are not specifically
- * used in the example, they are equivalent to using fgetc or getc with
- * stdin, or to using fputc or putc with stdout. See FUNGET.C for another
- * example of fgetc and getc.
- */
-
- #include <stdio.h>
- #include <conio.h>
- #include <io.h>
- #include <dos.h>
- #include <stdlib.h>
- #include <string.h>
-
- main()
- {
- FILE *infile, *outfile;
- char inpath[_MAX_PATH], outpath[_MAX_PATH];
- char drive[_MAX_DRIVE], dir[_MAX_DIR];
- char fname[_MAX_FNAME], ext[_MAX_EXT];
- int in, size;
- long i = 0L;
-
- /* Query for and open input file. */
- printf( "Enter input file name: " );
- gets( inpath );
- strcpy( outpath, inpath );
- if( (infile = fopen( inpath, "rb" )) == NULL )
- {
- printf( "Can't open input file" );
- exit( 1 );
- }
-
- /* Build output file by splitting path and rebuilding with
- * new extension.
- */
- _splitpath( outpath, drive, dir, fname, ext );
- strcpy( ext, "hx" );
- _makepath( outpath, drive, dir, fname, ext );
-
- /* If file does not exist, open it */
- if( access( outpath, 0 ) )
- {
- outfile = fopen( outpath, "wb" );
- printf( "Creating %s from %s . . .\n", outpath, inpath );
- }
- else
- {
- printf( "Output file already exists" );
- exit( 1 );
- }
-
- printf( "(B)yte or (W)ord: " );
- size = getche();
-
- /* Get each character from input and write to output. */
- while( !feof( infile ) )
- {
- if( (size == 'W') || (size == 'w') )
- {
- in = getw( infile );
- fprintf( outfile, " %.4X", in );
- if( !(++i % 8) )
- putw( 0x0D0A, outfile ); /* New line */
- }
- else
- {
- /* This example uses the fgetc and fputc functions. You
- * could also use the macro versions:
- in = getc( infile );
- */
- in = fgetc( infile );
- fprintf( outfile, " %.2X", in );
- if( !(++i % 16) )
- {
- /* Macro version:
- putc( 13, outfile );
- */
- fputc( 13, outfile ); /* New line */
- fputc( 10, outfile );
- }
- }
- }
- fclose( infile );
- fclose( outfile );
- exit( 0 );
- }
-
-
- HORIZON.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\HORIZON.C
-
- /* HORIZON.C: VGA graphics with cycling of 256 colors */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- #include <graph.h>
-
- #define RED 0x0000003FL
- #define GRN 0x00003F00L
- #define BLU 0x003F0000L
- #define WHT 0x003F3F3FL
- #define STEP 21
-
- struct videoconfig screen;
- long int rainbow[512];
-
- main()
- {
- int i;
- long int col, gray;
-
- if( _setvideomode( _MRES256COLOR ) == 0 )
- {
- printf("This program requires a VGA card.\n" );
- exit( 0 );
- }
- for( col = 0; col < 64; col++ )
- {
- gray = col | (col << 8) | (col << 16);
- rainbow[col] = rainbow[col + 256] = BLU & gray;
- rainbow[col + 64] = rainbow[col + 64 + 256] = BLU | gray;
- rainbow[col + 128] = rainbow[col + 128 + 256] = RED | (WHT & ~gray);
- rainbow[col + 192] = rainbow[col + 192 + 256] = RED & ~gray;
- }
- _setvieworg( 160, 85 );
-
- for( i = 0; i < 255; i++ )
- {
- _setcolor( 255 - i );
- _moveto( i, i - 255 );
- _lineto( -i, 255 - i );
- _moveto( -i, i - 255 );
- _lineto( i, 255 - i );
- _ellipse( _GBORDER, -i, -i / 2, i, i / 2 );
- }
- for( i = 0; !kbhit(); i += STEP, i %= 256 )
- _remapallpalette( &(rainbow[i]) );
-
- _setvideomode( _DEFAULTMODE );
- }
-
-
- IF1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\IF1.C
-
- /* IF.C: Demonstrate if statement. */
-
- #include <stdio.h>
- #include <conio.h>
- #define B_KEY 'b'
-
- main()
- {
- char ch;
- printf( "Press the b key to hear a bell.\n" );
- ch = getche();
- if( ch == B_KEY )
- printf( "Beep!\a\n" );
- }
-
-
- INCMAC.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\INCMAC.C
-
- /* INCMAC.C: Increment operator in macro argument.
- */
-
- #include <stdio.h>
- #define ABS(value) ( (value) >= 0 ? (value) : -(value) )
-
- main()
- {
- static int array[4] = {3, -20, -555, 6};
- int *ptr = array;
- int val, count;
- for( count = 0; count < 4; count++ )
- {
- val = ABS(*ptr++); /* Error! */
- printf( "abs of array[%d] = %d\n", count, val );
- }
- }
-
-
- INCMAC1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\INCMAC1.C
-
- /* INCMAC1.C: Increment operator in the for statement.
- */
-
- #include <stdio.h>
- #define ABS(value) ( (value) >= 0 ? (value) : -(value) )
-
- main()
- {
- static int array[4] = {3, -20, -555, 6};
- int *ptr = array;
- int val, count;
- for( count = 0; count < 4; count++, ptr++ )
- {
- val = ABS(*ptr);
- printf( "abs of array[%d] = %d\n", count, val );
- }
- }
-
-
- INTMATH.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\MATH\INTMATH.C
-
- /* INTMATH.C illustrates integer math functions including:
- * abs labs min max div ldiv
- *
- * See MATH.C for an example of the similar fabs function.
- */
-
- #include <stdlib.h>
- #include <stdio.h>
- #include <math.h>
-
- main()
- {
- int x, y;
- long lx, ly;
- div_t divres;
- ldiv_t ldivres;
-
- printf( "Enter two integers: " );
- scanf( "%d %d", &x, &y );
-
- printf("Function\tResult\n\n" );
- printf( "abs\t\tThe absolute value of %d is %d\n", x, abs( x ) );
- printf( "min\t\tThe lesser of %d and %d is %d\n", x, y, min( x, y ) );
- printf( "max\t\tThe greater of %d and %d is %d\n", x, y, max( x, y ) );
- divres = div( x, y );
- printf( "div\t\tFor %d / %d, quotient is %d and remainder is %d\n\n",
- x, y, divres.quot, divres.rem );
-
- printf( "Enter two long integers: " );
- scanf( "%ld %ld", &lx, &ly );
-
- printf("Function\tResult\n\n" );
- ldivres = ldiv( lx, ly );
- printf( "labs\t\tThe absolute value of %ld is %ld\n", lx, labs( lx ) );
- printf( "ldiv\t\tFor %ld / %ld, quotient is %ld and remainder is %ld\n",
- lx, ly, ldivres.quot, ldivres.rem );
- }
-
-
- IS.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\IS.C
-
- /* IS.C illustrates character classification functions including:
- * isprint isascii isalpha isalnum
- * isupper islower isdigit isxdigit
- * ispunct isspace iscntrl isgraph
- *
- * Console output is also shown using:
- * cprintf
- *
- * See PRINTF.C for additional examples of formatting for cprintf.
- */
-
- #include <ctype.h>
- #include <conio.h>
-
- main()
- {
- int ch;
-
- /* Display each ASCII character with character type table. */
- for( ch = 0; ch < 256; ch++ )
- {
- if( ch % 22 == 0 )
- {
- if( ch )
- getch();
-
- /* Note that cprintf does not convert "\n" to a CR/LF sequence.
- * You can specify this sequence with "\n\r".
- */
- cprintf( "\n\rNum Char ASCII Alpha AlNum Cap Low Digit " );
- cprintf( "XDigit Punct White CTRL Graph Print \n\r" );
- }
- cprintf( "%3d ", ch );
-
- /* Console output functions (cprint, cputs, and putch) display
- * graphic characters for all values except 7 (bell), 8 (backspace),
- * 10 (line feed), 13 (carriage return), and 255.
- */
- if( ch == 7 || ch == 8 || ch == 10 || ch == 13 || ch == 255 )
- cprintf("NV" );
- else
- cprintf("%c ", ch );
- cprintf( "%5s", isascii( ch ) ? "Y" : "N" );
- cprintf( "%6s", isalpha( ch ) ? "Y" : "N" );
- cprintf( "%6s", isalnum( ch ) ? "Y" : "N" );
- cprintf( "%5s", isupper( ch ) ? "Y" : "N" );
- cprintf( "%4s", islower( ch ) ? "Y" : "N" );
- cprintf( "%5s", isdigit( ch ) ? "Y" : "N" );
- cprintf( "%7s", isxdigit( ch ) ? "Y" : "N" );
- cprintf( "%6s", ispunct( ch ) ? "Y" : "N" );
- cprintf( "%6s", isspace( ch ) ? "Y" : "N" );
- cprintf( "%5s", iscntrl( ch ) ? "Y" : "N" );
- cprintf( "%6s", isprint( ch ) ? "Y" : "N" );
- cprintf( "%6s\n\r", isgraph( ch ) ? "Y" : "N" );
- }
- }
-
-
- KBHIT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\KBHIT.C
-
- /* KBHIT.C illustrates:
- * kbhit
- */
-
- #include <conio.h>
-
- main()
- {
- /* Display message until key is pressed. Use getch to throw key away. */
- while( !kbhit() )
- cputs( "Hit me!! " );
- getch();
- }
-
-
- KEYBRD.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\UTILITY\KEYBRD.C
-
- /* KEYBRD.C illustrates:
- * _bios_keybrd
- */
-
- #include <bios.h>
- #include <stdio.h>
- #include <ctype.h>
-
- main()
- {
- unsigned key, shift;
- unsigned char scan, ascii = 0;
-
- /* Read and display keys until ESC is pressed. */
- while( ascii != 27 )
- {
- /* Drain any keys in the keyboard type-ahead buffer, then get
- * the current key. If you want the last key typed rather than
- * the key currently being typed, omit the initial loop.
- */
- while( _bios_keybrd( _KEYBRD_READY ) )
- _bios_keybrd( _KEYBRD_READ );
- key = _bios_keybrd( _KEYBRD_READ );
-
- /* Get shift state. */
- shift = _bios_keybrd( _KEYBRD_SHIFTSTATUS );
-
- /* Split key into scan and ascii parts. */
- scan = key >> 8;
- ascii = key & 0x00ff;
-
- /* Categorize key. */
- if( ascii )
- printf( "ASCII: yes\tChar: %c \t",
- isgraph( ascii ) ? ascii : ' ' );
- else
- printf( "ASCII: no\tChar: NA\t" );
- printf( "Code: %.2X\tScan: %.2X\t Shift: %.2X\n",
- ascii, scan, shift );
- }
- }
-
-
- LOCK.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\LOCK.C
-
- /* LOCK.C illustrates network file sharing functions:
- * sopen locking
- *
- * Also the global variable:
- * _osmajor
- *
- * The program requires DOS 3.0 or higher. The DOS SHARE command must
- * be loaded. The locking mechanism will only work if the program is
- * run from a network drive.
- */
-
- #include <stdio.h>
- #include <conio.h>
- #include <io.h>
- #include <fcntl.h>
- #include <sys\types.h>
- #include <sys\stat.h>
- #include <sys\locking.h>
- #include <share.h>
- <stdlib.h> /* For _osmajor and exit */
-
- void error( char *msg );
-
- main( int argc, char *argv[] )
- {
- int handle, i;
- static char msg[] = "Are any of these bytes locked?";
- char buf[1];
-
- /* Check for DOS version >= 3.0 */
- if( _osmajor < 3 )
- error( "Must be DOS 3.0 or higher" );
-
- /* If no argument, write file and lock some bytes in it. */
- if( argc == 1 )
- {
- /* Open file with deny none sharing. */
- handle = sopen( "tmpfil", O_BINARY | O_RDWR | O_CREAT,
- SH_DENYNO, S_IREAD | S_IWRITE );
- if( handle == -1 )
- error( "Can't open file\n" );
-
- write( handle, msg, sizeof( msg ) - 1 );
-
- /* Lock 10 bytes starting at byte 10. */
- lseek( handle, 10L, SEEK_SET );
- if( locking( handle, LK_LOCK, 10L ) )
- error( "Locking failed\n" );
- printf( "Locked 10 bytes starting at byte 10\n" );
-
- system( "LOCK read" );
- getch();
-
- /* Unlock. */
- lseek( handle, 10L, SEEK_SET );
- locking( handle, LK_UNLCK, 10L );
- printf( "\nUnlocked 10 bytes starting at byte 10\n" );
-
- system( "LOCK read" );
- getch();
- }
-
- /* If argument, Try to read some locked bytes. */
- else
- {
- /* Open file with deny none sharing. */
- handle = sopen( "tmpfil", O_BINARY | O_RDWR,
- SH_DENYNO, S_IREAD | S_IWRITE );
- if( handle == -1 )
- error( "Can't open file\n" );
-
- for( i = 0; i < sizeof( msg ) - 1; i++ )
- {
- /* Print characters until locked bytes are reached. */
- if( read( handle, buf, 1 ) == -1 )
- break;
- else
- putchar( *buf );
- }
- }
- close( handle );
- exit( 0 );
- }
-
- void error( char *errmsg )
- {
- printf( errmsg );
- exit( 1 );
- }
-
-
- MATH.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\MATH\MATH.C
-
- /* MATH.C illustrates floating point math functions including:
- * exp pow sqrt frexp
- * log log10 ldexp modf
- * ceil floor fabs fmod
- */
-
- #include <math.h>
- #include <float.h>
- #include <stdio.h>
- #include <stdlib.h>
-
- main()
- {
- double x, rx, y;
- int n;
-
- printf( "\nEnter a real number: " );
- scanf( "%lf", &x );
-
- printf( "Mantissa: %2.2lf\tExponent: %d\n", frexp( x, &n ), n );
- printf( "Fraction: %2.2lf\tInteger: %lf\n", modf( x, &y ), y );
-
- printf("\nFunction\tResult for %2.2f\n\n", x );
- if( (rx = exp( x )) && (errno != ERANGE) )
- printf( "exp\t\t%2.2f\n", rx );
- else
- errno = 0;
- if( x > 0.0 )
- printf( "log\t\t%2.2f\n", log( x ) );
- if( x > 0.0 )
- printf( "log10\t\t%2.2f\n", log10( x ) );
- if( x >= 0.0 )
- printf( "sqrt\t\t%2.2f\n", sqrt( x ) );
- printf( "ceil\t\t%2.2f\n", ceil( x ) );
- printf( "floor\t\t%2.2f\n", floor( x ) );
- printf( "fabs\t\t%2.2f\n", fabs( x ) );
-
- printf( "\nEnter another real number: " );
- scanf( "%lf", &y );
- printf("\nFunction\tResult for %2.2f and %2.2f\n\n", x, y );
- printf( "fmod\t\t%2.2f\n", fmod( x, y ) );
- rx = pow( x, y );
- if( (errno != ERANGE) && (errno != EDOM) )
- printf( "pow\t\t%2.2f\n", rx );
- else
- errno = 0;
- rx = hypot( x, y );
- if( errno != ERANGE )
- printf( "hypot\t\t%2.2f\n", hypot( x, y ) );
- else
- errno = 0;
-
- printf( "\nEnter an integer exponent: " );
- scanf( "%d", &n );
- rx = ldexp( x, n );
- if( errno != ERANGE )
- {
- printf("\nFunction\tResult for %2.2f to power %d\n\n", x, n );
- printf( "ldexp\t\t%2.2f\n", ldexp( x, n ) );
- }
- }
-
-
- MATHERR.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\MATH\MATHERR.C
-
- /* MATHERR.C illustrates writing an error routine for math functions.
- * The error function must be:
- * matherr
- *
- * To use matherr, you must turn off the Extended Dictionary flag within
- * the QC environment (Options-Make-Linker Flags) or use the /NOE linker
- * option outside the environment. For example:
- * QCL matherr.c /link /NOE
- */
-
- #include <math.h>
- #include <string.h>
- #include <stdio.h>
-
- main()
- {
- /* Do several math operations that cause errors. The matherr
- * routine handles DOMAIN errors, but lets the system handle
- * other errors normally.
- */
- printf( "log( -2.0 ) = %e\n", log( -2.0 ) );
- printf( "log10( -5.0 ) = %e\n", log10( -5.0 ) );
- printf( "log( 0.0 ) = %e\n", log( 0.0 ) );
- }
-
- /* Routine to handle several math errors caused by passing a negative
- * argument to log or log10 (DOMAIN errors). If this happens, matherr
- * returns the natural or base-10 logarithm of the absolute value of
- * the argument and suppresses the usual error message.
- */
- int matherr( struct exception *except )
- {
- /* Handle DOMAIN errors for log or log10. */
- if( except->type == DOMAIN )
- {
- if( strcmp( except->name, "log" ) == 0 )
- {
- except->retval = log( -(except->arg1) );
- printf( "Special: using absolute value: %s: DOMAIN error\n",
- except->name );
- return 1;
- }
- else if( strcmp( except->name, "log10" ) == 0 )
- {
- except->retval = log10( -(except->arg1) );
- printf( "Special: using absolute value: %s: DOMAIN error\n",
- except->name );
- return 1;
- }
- }
- else
- {
- printf( "Normal: " );
- return 0; /* Else use the default actions */
- }
- }
-
-
- MENU.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\UTILITY\MENU.C
-
- /* MENU - Module of functions to put menus on the screen and handle keyboard
- * input. To use it, include the MENU.H file in your program. The following
- * functions are public:
- *
- * Menu - Puts a menu on screen and reads input for it
- * Box - Puts a box on screen (fill it yourself)
- * GetKey - Gets ASCII or function key
- * _outchar - Displays character using current text position and color
- *
- * The following structures are defined:
- *
- * MENU - Defines menu colors, box type, and centering
- * ITEM - Defines text of menu item and index of highlight characte
- *
- * The global variable "mnuAtrib" has type MENU. Change this variable to
- * change menu appearance.
- */
-
- #include <string.h>
- #include <stddef.h>
- #include <ctype.h>
- #include <graph.h>
- #include <bios.h>
- #include "menu.h"
-
- /* Default menu attribute. The default works for color or B&W. You can
- * override the default value by defining your own MENU variable and
- * assigning it to mnuAtrib. Or you can modify specific fields at
- * run time. For example, you could use a different attribute for color
- * than for black and white.
- */
- struct MENU mnuAtrib =
- {
- _TBLACK, _TBLACK, _TWHITE, _TBRIGHTWHITE, _TBRIGHTWHITE,
- _TWHITE, _TWHITE, _TBLACK, _TWHITE, _TBLACK,
- TRUE,
- '┌', '┐', '┘', '└', '│', '─'
- };
-
- /* Menu - Puts menu on screen and reads menu input from keyboard. When a
- * highlighted hot key or ENTER is pressed, returns the index of the
- * selected menu item.
- *
- * Params: row and col - If "fCentered" attribute of "mnuAtrib" is true,
- * center row and column of menu; otherwise top left of menu
- * aItem - array of structure containing the text of each item
- * and the index of the highlighted hot key
- * iCur - index of the current selection--pass 0 for first item,
- * or maintain a static value
- *
- * Return: The index of the selected item
- *
- * Uses: mnuAtrib
- */
- int Menu( int row, int col, struct ITEM aItem[], int iCur )
- {
- int cItem, cchItem = 2; /* Counts of items and chars per item */
- int i, iPrev; /* Indexes - temporary and previous */
- int acchItem[MAXITEM]; /* Array of counts of character in items */
- char *pchT; /* Temporary character pointer */
- char achHilite[36]; /* Array for highlight characters */
- unsigned uKey; /* Unsigned key code */
- long bgColor; /* Screen color, position, and cursor */
- short fgColor;
- struct rccoord rc;
- unsigned fCursor;
-
- /* Save screen information. */
- fCursor = _displaycursor( _GCURSOROFF );
- bgColor = _getbkcolor();
- fgColor = _gettextcolor();
- rc = _gettextposition();
-
- /* Count items, find longest, and put count of each in array. Also,
- * put the highlighted character from each in a string.
- */
- for( cItem = 0; aItem[cItem].achItem[0]; cItem++ )
- {
- acchItem[cItem] = strlen( aItem[cItem].achItem );
- cchItem = (acchItem[cItem] > cchItem) ? acchItem[cItem] : cchItem;
- i = aItem[cItem].iHilite;
- achHilite[cItem] = aItem[cItem].achItem[i];
- }
- cchItem += 2;
- achHilite[cItem] = 0; /* Null-terminate and lowercase string */
- strlwr( achHilite );
-
- /* Adjust if centered, and draw menu box. */
- if( mnuAtrib.fCentered )
- {
- row -= cItem / 2;
- col -= cchItem / 2;
- }
- Box( row++, col++, cItem, cchItem );
-
- /* Put items on menu. */
- for( i = 0; i < cItem; i++ )
- {
- if( i == iCur )
- Itemize( row + i, col, TRUE, aItem[i], cchItem - acchItem[i] );
- else
- Itemize( row + i, col, FALSE, aItem[i], cchItem - acchItem[i] );
- }
-
- while( TRUE )
- {
- /* Wait until a uKey is pressed, then evaluate it. */
- uKey = GetKey( WAIT );
- switch( uKey )
- {
- case U_UP: /* Up key */
- iPrev = iCur;
- iCur = (iCur > 0) ? (--iCur % cItem) : cItem - 1;
- break;
- case U_DN: /* Down key */
- iPrev = iCur;
- iCur = (iCur < cItem) ? (++iCur % cItem) : 0;
- break;
- default:
- if( uKey > 256 ) /* Ignore unknown function key
- continue;
- pchT = strchr( achHilite, (char)tolower( uKey ) );
- if( pchT != NULL ) /* If in highlight string, *
- iCur = pchT - achHilite;/* evaluate and fall through *
- else
- continue; /* Ignore unkown ASCII key *
- case ENTER:
- _setbkcolor( bgColor );
- _settextcolor( fgColor );
- _settextposition( rc.row, rc.col );
- _displaycursor( fCursor );
- return iCur;
- }
- /* Redisplay current and previous. */
- Itemize( row + iCur, col, TRUE, aItem[iCur], cchItem - acchItem[iCur]
- Itemize( row + iPrev, col, FALSE, aItem[iPrev], cchItem - acchItem[iP
- }
- }
-
- /* Box - Draw menu box, filling interior with blanks of the border color.
- *
- * Params: row and col - upper left of box
- * rowLast and colLast - height and width
- *
- * Return: None
- *
- * Uses: mnuAtrib
- */
- void Box( int row, int col, int rowLast, int colLast )
- {
- int i;
- char achT[MAXITEM + 2]; /* Temporary array of characters */
-
- /* Set color and position. */
- _settextposition( row, col );
- _settextcolor( mnuAtrib.fgBorder );
- _setbkcolor( mnuAtrib.bgBorder );
-
- /* Draw box top. */
- achT[0] = mnuAtrib.chNW;
- memset( achT + 1, mnuAtrib.chEW, colLast );
- achT[colLast + 1] = mnuAtrib.chNE;
- achT[colLast + 2] = 0;
- _outtext( achT );
-
- /* Draw box sides and center. */
- achT[0] = mnuAtrib.chNS;
- memset( achT + 1, ' ', colLast );
- achT[colLast + 1] = mnuAtrib.chNS;
- achT[colLast + 2] = 0;
- for( i = 1; i <= rowLast; ++i )
- {
- _settextposition( row + i, col );
- _outtext( achT );
- }
-
- /* Draw box bottom. */
- _settextposition( row + rowLast + 1, col );
- achT[0] = mnuAtrib.chSW;
- memset( achT + 1, mnuAtrib.chEW, colLast );
- achT[colLast + 1] = mnuAtrib.chSE;
- achT[colLast + 2] = 0;
- _outtext( achT );
- }
-
- /* Itemize - Display one (item) selection of a menu. This function
- * is normally only used internally by Menu.
- *
- * Params: row and col - top left of menu
- * fCur - flag set if item is current selection
- * itm - structure containing item text and index of highlight
- * cBlank - count of blanks to fill
- *
- * Return: none
- *
- * Uses: mnuAtrib
- */
- void Itemize( int row, int col, int fCur, struct ITEM itm, int cBlank )
- {
- int i;
- char achT[MAXITEM]; /* Temporary array of characters */
-
- /* Set text position and color. */
- _settextposition( row, col );
- if( fCur )
- {
- _settextcolor( mnuAtrib.fgSelect );
- _setbkcolor( mnuAtrib.bgSelect );
- }
- else
- {
- _settextcolor( mnuAtrib.fgNormal );
- _setbkcolor( mnuAtrib.bgNormal );
- }
-
- /* Display item and fill blanks. */
- strcat( strcpy( achT, " " ), itm.achItem );
- _outtext( achT );
- memset( achT, ' ', cBlank-- );
- achT[cBlank] = 0;
- _outtext( achT );
-
- /* Set position and color of highlight character, then display it. */
- i = itm.iHilite;
- _settextposition( row, col + i + 1 );
- if( fCur )
- {
- _settextcolor( mnuAtrib.fgSelHilite );
- _setbkcolor( mnuAtrib.bgSelHilite );
- }
- else
- {
- _settextcolor( mnuAtrib.fgNormHilite );
- _setbkcolor( mnuAtrib.bgNormHilite );
- }
- _outchar( itm.achItem[i] );
- }
-
- /* GetKey - Gets a key from the keyboard. This routine distinguishes
- * between ASCII keys and function or control keys with different shift
- * states. It also accepts a flag to return immediately if no key is
- * available.
- *
- * Params: fWait - Code to indicate how to handle keyboard buffer:
- * NO_WAIT Return 0 if no key in buffer, else return key
- * WAIT Return first key if available, else wait for key
- * CLEAR_WAIT Throw away any key in buffer and wait for new key
- *
- * Return: One of the following:
- *
- * Keytype High Byte Low Byte
- * ------- --------- --------
- * No key available (only with NO_WAIT) 0 0
- * ASCII value 0 ASCII code
- * Unshifted function or keypad 1 scan code
- * Shifted function or keypad 2 scan code
- * CTRL function or keypad 3 scan code
- * ALT function or keypad 4 scan code
- *
- * Note: getkey cannot return codes for keys not recognized by BIOS
- * int 16, such as the CTRL-UP or the 5 key on the numeric keypad.
- */
- unsigned GetKey( int fWait )
- {
- unsigned uKey, uShift;
-
- /* If CLEAR_WAIT, drain the keyboard buffer. */
- if( fWait == CLEAR_WAIT )
- while( _bios_keybrd( _KEYBRD_READY ) )
- _bios_keybrd( _KEYBRD_READ );
-
- /* If NO_WAIT, return 0 if there is no key ready. */
- if( !fWait && !_bios_keybrd( _KEYBRD_READY ) )
- return FALSE;
-
- /* Get key code. */
- uKey = _bios_keybrd( _KEYBRD_READ );
-
- /* If low byte is not zero, its an ASCII key. Check scan code to see
- * if it's on the numeric keypad. If not, clear high byte and return.
- */
- if( uKey & 0x00ff )
- if( (uKey >> 8) < 69 )
- return( uKey & 0x00ff );
-
- /* For function keys and numeric keypad, put scan code in low byte
- * and shift state codes in high byte.
- */
- uKey >>= 8;
- uShift = _bios_keybrd( _KEYBRD_SHIFTSTATUS ) & 0x000f;
- switch( uShift )
- {
- case 0:
- return( 0x0100 | uKey ); /* None (1) */
- case 1:
- case 2:
- case 3:
- return( 0x0200 | uKey ); /* Shift (2) */
- case 4:
- return( 0x0300 | uKey ); /* Control (3) */
- case 8:
- return( 0x0400 | uKey ); /* Alt (4) */
- }
- }
-
- /* _outchar - Display a character. This is the character equivalent of
- * _outtext. It is affected by _settextposition, _settextcolor, and
- * _setbkcolor. It should not be used in loops. Build strings and then
- * _outtext to show multiple characters.
- *
- * Params: out - character to be displayed
- *
- * Return: none
- */
- void _outchar( char out )
- {
- static char achT[2] = " "; /* Temporary array of characters */
-
- achT[0] = out;
- _outtext( achT );
- }
-
-
- MKFPSTR.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\MKFPSTR.C
-
- /* MKFPSTR.C illustrates building and displaying floating point strings
- * without printf. Functions illustrated include:
- * strcat strncat cscanf fcvt
- */
-
- #include <stdlib.h>
- #include <conio.h>
- #include <string.h>
-
- main()
- {
- int decimal, sign;
- int precision = 7;
- static char numbuf[50] = "";
- char *pnumstr, tmpbuf[50];
- double number1, number2;
-
- cputs( "Enter two floating point numbers: " );
- cscanf( "%lf %lf", &number1, &number2 );
- putch( '\n' );
-
- /* Use information from fcvt to format number string. */
- pnumstr = fcvt( number1 + number2, precision, &decimal, &sign );
-
- /* Start with sign if negative. */
- if( sign )
- strcat( numbuf, "-" );
-
- if( decimal <= 0 )
- {
- /* If decimal is left of first digit (decimal negative), put
- * in leading zeros, then add digits.
- */
- strcat( numbuf, "0." );
- memset( tmpbuf, '0', (size_t)abs( decimal ) );
- tmpbuf[abs( decimal )] = 0;
- strcat( numbuf, tmpbuf );
- strcat( numbuf, pnumstr );
- }
- else
- {
- /* If decimal is right of first digit, put in leading digits.
- * then add decimal and trailing digits.
- */
- strncat( numbuf, pnumstr, (size_t)decimal );
- strcat( numbuf, "." );
- strcat( numbuf, pnumstr + decimal );
- }
- cputs( strcat( "Total is: ", numbuf ) );
- }
-
-
- MORE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\MORE.C
-
- /* MORE.C illustrates line input and output using:
- * gets puts isatty fileno
- *
- * Like the DOS MORE command, it is a filter whose input and output can
- * be redirected.
- */
-
- #include <stdio.h>
- #include <bios.h>
- #include <io.h>
-
- main()
- {
- long line = 0, page = 0;
- char tmp[128];
-
- /* Get each line from standard input and write to standard output. */
- while( 1 )
- {
- /* If standard out is the screen, wait for key after each screen. */
- if( isatty( fileno( stdout ) ) )
- {
- /* Wait for key every 23 lines. You must get the key directly
- * from the BIOS, since input is usually redirected.
- */
- if( !(++line % 23 ) )
- _bios_keybrd( _KEYBRD_READ );
- }
- /* Must be redirected to file, so send a header every 58 lines. */
- else
- {
- if( !(line++ % 58) )
- printf( "\f\nPage: %d\n\n", ++page );
- }
-
- /* Get and put a line of text. */
- if( gets( tmp ) == NULL )
- break;
- puts( tmp );
-
- }
- }
-
-
- MOVEMEM.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\MEMORY\MOVEMEM.C
-
- /* MOVEMEM.C illustrate direct memory access using functions:
- * movedata FP_SEG FP_OFF
- *
- * Also illustrated:
- * pack pragma
- *
- * See COPY2.C for another example of FP_SEG.
- */
-
- #include <memory.h>
- #include <stdio.h>
- #include <dos.h>
-
- pack(1) /* Use pragma to force packing on byte boundaries. */
-
- struct LOWMEMVID
- {
- char vidmode; /* 0x449 */
- unsigned scrwid; /* 0x44A */
- unsigned scrlen; /* 0x44C */
- unsigned scroff; /* 0x44E */
- struct LOCATE
- {
- unsigned char col;
- unsigned char row;
- } csrpos[8]; /* 0x450 */
- struct CURSIZE
- {
- unsigned char end;
- unsigned char start;
- } csrsize; /* 0x460 */
- char page; /* 0x462 */
- } vid;
- struct LOWMEMVID far *pvid = &vid;
-
- main()
- {
- int page;
-
- /* Move system information into uninitialized structure variable. */
- movedata( 0, 0x449, FP_SEG( pvid ), FP_OFF( pvid ), sizeof( vid ) );
-
- printf( "Move data from low memory 0000:0449 to structure at %Fp\n\n",
- (void far *)&vid );
-
- printf( "Mode:\t\t\t%u\n", vid.vidmode );
- printf( "Page:\t\t\t%u\n", vid.page );
- printf( "Screen width:\t\t%u\n", vid.scrwid );
- printf( "Screen length:\t\t%u\n", vid.scrlen );
- printf( "Cursor size:\t\tstart: %u\tend: %u\n",
- vid.csrsize.start, vid.csrsize.end );
- printf( "Cursor location:\t" );
- for( page = 0; page < 8; page++ )
- printf( "page:\t%u\tcolumn: %u\trow: %u\n\t\t\t",
- page, vid.csrpos[page].col, vid.csrpos[page].row );
- }
-
-
- NFORMAT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\NFORMAT.C
-
- /* NFORMAT.C: Prints numbers and a string. */
-
- #include <stdio.h>
- #include <string.h>
-
- main()
- {
- int a = -765,
- b = 1,
- c = 44000,
- d = 33;
- float e = 1.33E8,
- f = -0.1234567,
- g = 12345.6789,
- h = 1.0;
- char i[80];
-
- strcpy( i, "word 1, word 2, word 3, word 4, word 5" );
-
- printf( "Unformatted:\n%d %d %d %d\n", a, b, c, d );
- printf( "%f %f %f %f\n", e, f, g, h );
- printf( "%s\n", i );
- }
-
-
- NOT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\NOT.C
-
- /* NOT.C: Demonstrate logical NOT operator. */
-
- #include <stdio.h>
-
- main()
- {
- int val = 0;
- if( !val )
- printf( "val is zero" );
- }
-
-
- NULLFILE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\NULLFILE.C
-
- /* NULLFILE.C illustrates these functions:
- * chsize umask setmode
- * creat fstat
- */
-
- #include <stdio.h>
- #include <conio.h>
- #include <io.h>
- #include <fcntl.h>
- #include <sys\types.h>
- #include <sys\stat.h>
- #include <stdlib.h>
- #include <time.h>
-
- main()
- {
- int fhandle;
- long fsize;
- struct stat fstatus;
- char fname[80];
-
- /* Create a file of a specified length. */
- printf( "What dummy file do you want to create: " );
- gets( fname );
- if( !access( fname, 0 ) )
- {
- printf( "File exists" );
- exit( 1 );
- }
-
- /* Mask out write permission. This means that a later call to open
- * will not be able to set write permission. This is not particularly
- * useful in DOS, but umask is provided primarily for compatibility
- * with systems (such as Unix) that allow multiple permission levels.
- */
- umask( S_IWRITE );
-
- /* Despite write request, file is read only because of mask. */
- if( (fhandle = creat( fname, S_IREAD | S_IWRITE )) == -1 )
- {
- printf( "File can't be created" );
- exit( 1 );
- }
-
- /* Since creat uses the default mode (usually text), you must
- * use setmode to make sure the mode is binary.
- */
- setmode( fhandle, O_BINARY );
-
- printf( "How long do you want the file to be? " );
- scanf( "%ld", &fsize );
- chsize( fhandle, fsize );
-
- /* Display statistics. */
- fstat( fhandle, &fstatus );
- printf( "File: %s\n", fname );
- printf( "Size: %ld\n", fstatus.st_size );
- printf( "Drive %c:\n", fstatus.st_dev + 'A' );
- printf( "Permission: %s\n",
- (fstatus.st_mode & S_IWRITE) ? "Read/Write" : "Read Only" );
- printf( "Created: %s", ctime( &fstatus.st_atime ) );
-
- close( fhandle );
- exit( 0 );
- }
-
-
- NUMTOA.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\NUMTOA.C
-
- /* NUMTOA.C illustrates number to string conversion functions including:
- * itoa ltoa ultoa
- */
-
- #include <stdlib.h>
- #include <stdio.h>
-
- main()
- {
- int base, i;
- long l;
- unsigned long ul;
- char buffer[60];
-
- printf( "Enter an integer: " );
- scanf( "%d", &i );
- for( base = 2; base <= 16; base += 2 )
- {
- itoa( i, buffer, base );
- if( base != 10 )
- printf( "%d in base %d is: %s\n", i, base, buffer );
- }
-
- printf( "Enter a long integer: " );
- scanf( "%ld", &l );
- for( base = 2; base <= 16; base += 2 )
- {
- ltoa( l, buffer, base );
- if( base != 10 )
- printf( "%ld in base %d is: %s\n", l, base, buffer );
- }
-
- printf( "Enter an unsigned long integer: " );
- scanf( "%lu", &ul );
- for( base = 2; base <= 16; base += 2 )
- {
- ultoa( ul, buffer, base );
- if( base != 10 )
- printf( "%lu in base %d is: %s\n", ul, base, buffer );
- }
- }
-
-
- PAGE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\PAGE.C
-
- /* PAGE.C illustrates video page functions including:
- * _getactivepage _getvisualpage _setactivepage _setvisualpage
- */
-
- #include <conio.h>
- #include <graph.h>
- #include <time.h>
-
- void delay( clock_t wait ); /* Prototype */
- char *jumper[] = { { "\\o/\n O \n/ \\" },
- { "_o_\n O \n( )" },
- { " o \n/O\\\n/ \\" },
- { " o \n O \n( )" }
- };
- main()
- {
- int i, oldvpage, oldapage, oldcursor;
-
- _clearscreen( _GCLEARSCREEN );
- oldcursor = _displaycursor( _GCURSOROFF );
- oldapage = _getactivepage();
- oldvpage = _getvisualpage();
-
- /* Draw image on each page */
- for( i = 0; i < 4; i++ )
- {
- _setactivepage( i );
- _settextposition( 1, 1 );
- _outtext( jumper[i] );
- }
-
- while( !kbhit() )
- /* Cycle through pages 0 to 3 */
- for( i = 0; i < 4; i++ )
- {
- _setvisualpage( i );
- delay( 100L );
- }
- getch();
-
- /* Restore original page and cursor. */
- _displaycursor( oldcursor );
- _setactivepage( oldapage );
- _setvisualpage( oldvpage );
- }
-
- /* delay - Pauses for a specified number of microseconds. */
- void delay( clock_t wait )
- {
- clock_t goal;
-
- goal = wait + clock();
- while( goal > clock() )
- ;
- }
-
-
- PAGER.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\PAGER.C
-
- /* PAGER.C illustrates line input and output on stream text files.
- * Functions illustrated include:
- * fopen fclose fcloseall feof
- * fgets fputs rename
- */
-
- #include <stdio.h>
- #include <io.h>
- #include <dos.h>
- #include <stdlib.h>
- #include <string.h>
-
- #define MAXSTRING 128
- #define PAGESIZE 55
- enum BOOL { FALSE, TRUE };
-
- void quit( int error );
- FILE *infile, *outfile;
- char outpath[] = "tmXXXXXX";
-
- main( int argc, char *argv[] )
- {
- char tmp[MAXSTRING];
- long line = 0, page = 1;
- int endflag = FALSE;
-
- /* Open file (from command line) and output (temporary) files. */
- if( (infile = fopen( argv[1], "rt" )) == NULL )
- quit( 1 );
- mktemp( outpath );
- if( (outfile = fopen( outpath, "wt" )) == NULL )
- quit( 2 );
-
- /* Get each line from input and write to output. */
- while( 1 )
- {
- /* Insert form feed and page header at the top of each page. */
- if( !(line++ % PAGESIZE) )
- fprintf( outfile, "\f\nPage %d\n\n", page++ );
-
- if( fgets( tmp, MAXSTRING - 1, infile ) == NULL )
- if( feof( infile ) )
- break;
- else
- quit( 3 );
- if( fputs( tmp, outfile ) == EOF )
- quit( 3 );
- }
-
- /* Close files and move temporary file to original by deleting
- * original and renaming temporary.
- */
- fcloseall();
- remove( argv[1] );
- rename( outpath, argv[1] );
- exit( 0 );
- }
-
- /* Handle errors. */
- void quit( int error )
- {
- switch( error )
- {
- case 1:
- perror( "Can't open input file" );
- break;
- case 2:
- perror( "Can't open output file" );
- fclose( infile );
- break;
- case 3:
- perror( "Error processing file" );
- fclose( infile );
- fclose( outfile );
- remove( outpath );
- break;
- }
- exit( error );
- }
-
-
- PALETTE1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\PALETTE1.C
-
- /* PALETTE.C illustrates functions for assigning color values to
- * color indexes. Functions illustrated include:
- * _remappalette _remapallpalette
- */
-
- #include <graph.h>
- #include <conio.h>
- #include <stdio.h>
- #include <stdlib.h>
-
- /* Macro for mixing Red, Green, and Blue elements of color */
- #define RGB(r,g,b) (((long) ((b) << 8 | (g)) << 8) | (r))
-
- main()
- {
- short red, blue, green;
- short inc, i, mode, cells, x, y, xinc, yinc;
- long tmp, pal[256];
- char buf[40];
- struct videoconfig vc;
-
- /* Make sure all palette numbers are valid */
- for( i = 0; i < 256; i++ )
- pal[i] = _BLACK;
-
- /* Loop through each graphics mode that supports palettes. */
- for( mode = _MRES4COLOR; mode <= _MRES256COLOR; mode++ )
- {
- if( mode == _ERESNOCOLOR )
- mode++;
- if( !_setvideomode( mode ) )
- continue;
-
- /* Set variables for each mode. */
- _getvideoconfig( &vc );
- switch( vc.numcolors )
- {
- case 256: /* Active bits in this order: */
- cells = 13;
- inc = 12; /* ???????? ??bbbbbb ??gggggg ??rrrrrr */
- break;
- case 16:
- cells = 4;
- if( (vc.mode == _ERESCOLOR) || (vc.mode == _VRES16COLOR) )
- inc = 16; /* ???????? ??????bb ??????gg ??????rr */
- else
- inc = 32; /* ???????? ??????Bb ??????Gg ??????Rr */
- break;
- case 4:
- cells = 2;
- inc = 32; /* ???????? ??????Bb ??????Gg ??????Rr */
- break;
- default:
- continue;
- }
- xinc = vc.numxpixels / cells;
- yinc = vc.numypixels / cells;
-
- /* Fill palette arrays in BGR order */
- for( i = 0, blue = 0; blue < 64; blue += inc )
- for( green = 0; green < 64; green += inc )
- for( red = 0; red < 64; red += inc )
- {
- pal[i] = RGB( red, green, blue );
- /* Special case of using 6 bits to represent 16 colors.
- * If both bits are on for any color, intensity is set.
- * If one bit is set for a color, the color is on.
- */
- if( inc == 32 )
- pal[i + 8] = pal[i] | (pal[i] >> 1);
- i++;
- }
-
- /* If palettes available, remap all palettes at once. */
- if( !_remapallpalette( pal ) )
- {
- _setvideomode( _DEFAULTMODE );
- _outtext( "Palettes not available with this adapter" );
- exit( 1 );
- }
-
- /* Draw colored squares */
- for( i = 0, x = 0; x < vc.numxpixels; x += xinc )
- for( y = 0; y < vc.numypixels; y += yinc )
- {
- _setcolor( i++ );
- _rectangle( _GFILLINTERIOR, x, y, x + xinc, y + yinc );
- }
- sprintf( buf, "Mode %d has %d colors", vc.mode, vc.numcolors );
- _setcolor( vc.numcolors / 2 );
- _outtext( buf );
- getch();
-
- /* Change each palette entry separately in GRB order. */
- for( i = 0, green = 0; green < 64; green += inc )
- for( red = 0; red < 64; red += inc )
- for(blue = 0; blue < 64; blue += inc )
- {
- tmp = RGB( red, green, blue );
- _remappalette( i, tmp );
- if( inc == 32 )
- _remappalette( i + 8, tmp | (tmp >> 1) );
- i++;
- }
- getch();
- }
- exit( !_setvideomode( _DEFAULTMODE ) );
- }
-
-
- PARRAY.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\PARRAY.C
-
- /* PARRAY.C: Demonstrate pointer to array. */
-
- #include <stdio.h>
-
- int i_array[] = { 25, 300, 2, 12 };
-
- main()
- {
- int *ptr;
- int count;
- ptr = &i_array[0];
- for( count = 0; count < 4 ; count++ )
- {
- printf( "array[%d] = %d\n", count, *ptr );
- ptr++;
- }
- }
-
-
- PARRAY1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\PARRAY1.C
-
- /* PARRAY1.C: Compact version of PARRAY.C. */
-
- #include <stdio.h>
-
- int i_array[] = { 25, 300, 2, 12 };
-
-
- main()
- {
- int count;
- int *ptr = i_array;
- for( count = 0; count < 4 ; count++ )
- printf( "array[%d] = %d\n", count, *ptr++ );
- }
-
-
- PFUNC.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\PFUNC.C
-
- /* PFUNC.C: Passing pointers to a function. */
-
- #include <stdio.h>
-
- void swap( int *ptr1, int *ptr2 );
-
- main()
- {
- int first = 1, second = 3;
- int *ptr = &second;
- printf( "first: %d second: %d\n", first, *ptr );
- swap( &first, ptr );
- printf( "first: %d second: %d\n", first, *ptr );
- }
-
- void swap( int *ptr1, int *ptr2 )
- {
- int temp;
- temp = *ptr1;
- *ptr1 = *ptr2;
- *ptr2 = temp;
- }
-
-
- POINTER.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\POINTER.C
-
- /* POINTER.C: Demonstrate pointer basics. */
-
- #include <stdio.h>
-
- main()
- {
- int val = 25;
- int *ptr;
- ptr = &val;
- printf( " val = %d\n", val );
- printf( "*ptr = %d\n\n", *ptr );
- printf( "&val = %u\n", &val );
- printf( " ptr = %d\n", ptr );
- }
-
-
- PRINTF.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\PRINTF.C
-
- /* PRINTF.C illustrates output formatting with:
- * printf
- *
- * The rules for formatting also apply to cprintf, sprintf, vfprintf,
- * vprintf, and vsprintf. For other examples of printf formatting,
- * see EXTDIR.C (sprintf), VPRINTF (vprintf), TABLE.C (fprintf),
- * ROTATE.C (printf), and IS.C (cprintf).
- */
-
- #include <stdio.h>
-
- main()
- {
- char ch = 'h', *string = "computer";
- int count = 234, *ptr, hex = 0x10, oct = 010, dec = 10;
- double fp = 251.7366;
-
- /* Display integers. */
- printf("%d %+d %06d %X %x %o\n\n",
- count, count, count, count, count, count );
-
- /* Count characters printed. */
- printf( " V\n" );
- printf( "1234567890123%n45678901234567890\n", &count );
- printf( "Number of characters printed: %d\n\n", count );
-
- /* Display characters. */
- printf( "%10c%5c\n\n", ch, ch );
-
- /* Display strings. */
- printf( "%25s\n%25.4s\n\n", string, string );
-
- /* Display real numbers. */
- printf( "%f %.2f %e %E\n\n", fp, fp, fp, fp );
-
- /* Display in different radixes. */
- printf( "%i %i %i\n\n", hex, oct, dec );
-
- /* Display pointers. */
- ptr = &count;
- printf( "%Np %p %Fp\n", ptr, (int far *)ptr, (int far *)ptr );
- }
-
-
- PRTESC.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\PRTESC.C
-
- /* PRTESC.C: Prints escape characters \",\n, and \t.
- */
-
- #include <stdio.h>
- #include <string.h>
-
- main()
- {
- char b[80];
- int i,j;
-
- strcpy( b, "and seven years ago\n" );
- printf( "\"Four score\n" );
- printf( b );
- printf( "\tone tab\n\t\ttwo tabs\n\t\t\tthree tabs\n" );
- i = sizeof( b );
- j = strlen( b );
- printf( "Size is %d\nLength is %d.\n", i, j );
- }
-
-
- PSTRING.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\PSTRING.C
-
- /* PSTRING.C: Demonstrate pointer to a string. */
-
- #include <stdio.h>
-
- main()
- {
- int count;
- static char name[] = "john";
- char *ptr = name;
- for( count = 0; count < 4; count++ )
- {
- printf( "name[%d]: %c\n", count, *ptr++ );
- }
- }
-
-
- PSTRING1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\PSTRING1.C
-
- /* PSTRING1.C: Look for null at string's end. */
-
- #include <stdio.h>
-
- main()
- {
- static char name[] = "john";
- char *ptr = name;
- while( *ptr )
- printf( "*ptr = %c\n", *ptr++ );
- }
-
-
- PSTRING2.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\PSTRING2.C
-
- /* PSTRING2.C: Demonstrate strings and array notation.
- */
-
- #include <stdio.h>
- #include <string.h>
-
- main()
- {
- int count;
- static char name[] = "john";
- for( count = 0; count < strlen( name ); count++ )
- printf( "name[%d]: %c\n", count, name[count] );
- }
-
-
- PSTRING3.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\PSTRING3.C
-
- /* PSTRING3.C: Strings and pointer notation. */
-
- #include <stdio.h>
- #include <string.h>
-
- main()
- {
- int count;
- static char name[] = "john";
- for( count = 0; count < strlen( name ); count++ )
- printf( "*(name+count) = %c\n", *(name+count) );
- }
-
-
- PTRPTR.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\PTRPTR.C
-
- /* PTRPTR.C: Demonstrate a pointer to a pointer. */
-
- #include <stdio.h>
-
- main()
- {
- int val = 501;
- int *ptr = &val;
- int **ptr_ptr = &ptr;
- printf( "val = %d\n", **ptr_ptr );
- }
-
-
- QSORT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\QSORT.C
-
- /* QSORT.C illustates randomizing, sorting, and searching. Functions
- * illustrated include:
- * srand rand qsort
- * lfind lsearch bsearch
- *
- * The lsearch function is not specifically shown in the program, but
- * its use is the same as lfind except that if it does not find the
- * element, it inserts it at the end of the array rather than failing.
- */
-
- #include <search.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- #include <time.h>
-
- #define ASIZE 1000
- unsigned array[ASIZE];
-
- /* Macro to get a random integer within a specified range */
- #define getrandom( min, max ) ((rand() % (int)((max) - (min))) + (min) + 1)
-
- /* Must be declared before call */
- unsigned cmpgle( unsigned *arg1, unsigned *arg2 );
- unsigned cmpe( unsigned *arg1, unsigned *arg2 );
-
- main()
- {
- unsigned i, *result, elements = ASIZE, key = ASIZE / 2;
-
- /* Seed the random number generator with current time. */
- srand( (unsigned)time( 0L ) );
-
- /* Build a random array of integers. */
- printf( "Randomizing . . .\n" );
- for( i = 0; i < ASIZE; i++ )
- array[i] = getrandom( 1, ASIZE );
-
- /* Show every tenth element. */
- printf( "Printing every tenth element . . .\n" );
- for( i = 9; i < ASIZE; i += 10 )
- {
- printf( "%5u", array[i] );
- if( !(i % 15) )
- printf( "\n" );
- }
-
- /* Find element using linear search. */
- printf( "\nDoing linear search . . .\n" );
- result = (unsigned *)lfind( (char *)&key, (char *)array, &elements,
- sizeof( unsigned ), cmpe);
- if( result == NULL )
- printf( " Value %u not found\n", key );
- else
- printf( " Value %u found in element %u\n", key, result - array + 1);
-
- /* Sort array using Quicksort algorithm. */
- printf( "Sorting . . .\n" );
- qsort( (void *)array, (size_t)ASIZE, sizeof( int ), cmpgle );
-
- /* Show every tenth element. */
- printf( "Printing every tenth element . . .\n" );
- for( i = 9; i < ASIZE; i += 10 )
- {
- printf( "%5u", array[i] );
- if( !(i % 15) )
- printf( "\n" );
- }
-
- /* Find element using binary search. Note that the array must
- * be previously sorted before using binary search.
- */
- printf( "\nDoing binary search . . .\n" );
- result = (unsigned *)bsearch( (char *)&key, (char *)array, elements,
- sizeof( unsigned ), cmpgle);
- if( result == NULL )
- printf( " Value %u not found\n", key );
- else
- printf( " Value %u found in element %u\n", key, result - array + 1 )
- }
-
- /* Compare and return greater than (1), less than (-1), or equal to (0).
- * This function is called by qsort and bsearch.
- */
- unsigned cmpgle( unsigned *arg1, unsigned *arg2 )
- {
- if( *arg1 > *arg2 )
- return 1;
- else if( *arg1 < *arg2 )
- return -1;
- else
- return 0;
- }
-
- /* Compare and return equal (1) or not equal (0). This function is
- * called by lfind and lsearch.
- */
- unsigned cmpe( unsigned *arg1, unsigned *arg2 )
- {
- return !( *arg1 == *arg2 );
- }
-
-
- RDFILE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\RDFILE.C
-
- /* RDFILE.C: Reads a file and prints characters to
- * the screen. If you get "Error in opening file" try
- * running wrfile.c before you run this again.
- */
-
- #include <stdio.h>
-
- main()
- {
- int c;
- FILE *fp;
-
- if( fp = fopen( "c:\\testfile.asc", "rb" ) )
- {
- while( (c = fgetc( fp )) != EOF )
- printf( " %c\t%d\n", c, c );
- printf( "\nEnd of file marker: %d", c );
- fclose( fp );
- }
- else
- printf( "Error in opening file\n" );
- }
-
-
- RDKEYBRD.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\RDKEYBRD.C
-
- /* INPUT.C: Reads keyboard. */
-
- #include <stdio.h>
- #include <conio.h>
- #include <ctype.h>
-
- main()
- {
- int num;
- char c;
- char name[80];
- float rb;
-
- puts( "** Type \"Name:\" and your name" );
- scanf( "Name: %40s", name );
- printf( "** You typed this:\n%s", name );
- puts( "\n\n** Try again, with the gets function." );
- fflush( stdin );
- gets( name );
- printf( "** You typed this:\n%s\n", name );
-
- printf( "\n** Now type an integer.\n" );
- scanf( "%i", &num );
- sprintf( name, "** You typed this number: %i\n", num );
- puts( name );
-
- fflush( stdin );
- printf( "** Enter a floating-point value.\n" );
- scanf( "%f", &rb );
- printf( "** The answer is %f or %e\n", rb, rb );
-
- printf( "** Continue? Y or N\n" );
-
- do
- c = tolower( getch() );
- while( c != 'y' && c != 'n' );
-
- }
-
-
- REALG.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\REALG.C
-
- /* REALG.C: Example of real-coordinate graphics */
-
- #include <stdio.h>
- #include <conio.h>
- #include <graph.h>
-
- #define TRUE 1
- #define FALSE 0
-
- int four_colors( void );
- void three_graphs( void );
- void grid_shape( void );
-
- int halfx, halfy;
- struct videoconfig screen;
- double bananas[] =
- { -0.3, -0.2, -0.224, -0.1, -0.5, +0.21, +2.9,
- +0.3, +0.2, 0.0, -0.885, -1.1, -0.3, -0.2,
- +.001, +.005, +0.14, 0.0, -0.9, -0.13, +0.3
- };
-
-
- main()
- {
- if( four_colors() )
- three_graphs();
- else
- printf( "This program requires a CGA, EGA, or VGA graphics card.\n"
- );
- }
- /*
- . Additional functions defined below
- .
- .
- */
- /* four_colors function from REALG.C */
-
- int four_colors( void )
- {
- _getvideoconfig( &screen );
- switch( screen.adapter )
- {
- case _CGA:
- case _OCGA:
- _setvideomode( _MRES4COLOR );
- break;
- case _EGA:
- case _OEGA:
- _setvideomode( _ERESCOLOR );
- break;
- case _VGA:
- case _OVGA:
- _setvideomode( _VRES16COLOR );
- break;
- default:
- return( FALSE );
- }
- _getvideoconfig( &screen );
- return( TRUE );
- }
- /* three_graphs function from REALG.C */
-
- void three_graphs( void )
- {
- int xwidth, yheight, cols, rows;
- struct _wxycoord upleft, botright;
-
- _clearscreen( _GCLEARSCREEN );
- xwidth = screen.numxpixels;
- yheight = screen.numypixels;
- halfx = xwidth/2;
- halfy = yheight/2;
- cols = screen.numtextcols;
- rows = screen.numtextrows;
-
- /* first window */
- _setviewport( 0, 0, halfx-1, halfy-1 );
- _settextwindow( 1, 1, rows/2, cols/2 );
- _setwindow( FALSE, -2.0, -2.0, 2.0, 2.0 );
- grid_shape();
- _rectangle( _GBORDER, 0, 0, halfx-1, halfy-1 );
-
- /* second window */
- _setviewport( halfx, 0, xwidth-1, halfy-1 );
- _settextwindow( 1, cols/2+1, rows/2, cols );
- _setwindow( FALSE, -3.0, -3.0, 3.0, 3.0 );
- grid_shape();
- _rectangle_w( _GBORDER, -3.0, -3.0, 3.0, 3.0 );
-
- /* third window */
- _setviewport( 0, halfy, xwidth-1, yheight-1 );
- _settextwindow( rows/2+1, 1, rows, cols );
- _setwindow( TRUE, -3.0, -1.5, 1.5, 1.5 );
- grid_shape();
- upleft.wx = -3.0;
- upleft.wy = -1.5;
- botright.wx = 1.5;
- botright.wy = 1.5;
- _rectangle_wxy( _GBORDER, &upleft, &botright );
-
- getch();
- _setvideomode( _DEFAULTMODE );
- }
- /* grid_shape from the REALG.C program */
-
- void grid_shape( void )
- {
- int i, numc, x1, y1, x2, y2;
- double x, y;
- char txt[80];
-
- numc = screen.numcolors;
- for( i = 1; i < numc; i++ )
- {
- _settextposition( i, 2 );
- _settextcolor( i );
- sprintf( txt, "Color %d", i );
- _outtext( txt );
- }
-
- _setcolor( 1 );
- _rectangle_w( _GBORDER, -1.0, -1.0, 1.0, 1.0 );
- _rectangle_w( _GBORDER, -1.02, -1.02, 1.02, 1.02 );
-
- for( x = -0.9, i = 0; x < 0.9; x += 0.1 )
- {
- _setcolor( 2 );
- _moveto_w( x, -1.0 );
- _lineto_w( x, 1.0 );
- _moveto_w( -1.0, x );
- _lineto_w( 1.0, x );
-
- _setcolor( 3 );
- _moveto_w( x - 0.1, bananas[i++] );
- _lineto_w( x, bananas[i] );
- }
- _moveto_w( 0.9, bananas[i++] );
- _lineto_w( 1.0, bananas[i] );
- }
-
-
- REALLOC1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\MEMORY\REALLOC1.C
-
- /* REALLOC.C illustrates heap functions:
- * calloc realloc _expand
- */
-
- #include <stdio.h>
- #include <malloc.h>
-
- main()
- {
- int *bufint;
- char *bufchar;
-
- printf( "Allocate two 512 element buffers\n" );
- if( (bufint = (int *)calloc( 512, sizeof( int ) )) == NULL )
- exit( 1 );
- printf( "Allocated %d bytes at %Fp\n",
- _msize( bufint ), (void far *)bufint );
-
- if( (bufchar = (char *)calloc( 512, sizeof( char ) )) == NULL )
- exit( 1 );
- printf( "Allocated %d bytes at %Fp\n",
- _msize( bufchar ), (void far *)bufchar );
-
- /* Expand the second buffer, reallocate the first. Note that trying
- * to expand the first buffer would fail because the second buffer
- * would be in the way.
- */
- if( (bufchar = (char *)_expand( bufchar, 1024 )) == NULL )
- printf( "Can't expand" );
- else
- printf( "Expanded block to %d bytes at %Fp\n",
- _msize( bufchar ), (void far *)bufchar );
-
- if( (bufint = (int *)realloc( bufint, 1024 * sizeof( int ) )) == NULL )
- printf( "Can't reallocate" );
- else
- printf( "Reallocated block to %d bytes at %Fp\n",
- _msize( bufint ), (void far *)bufint );
-
- /* Free memory */
- free( bufint );
- free( bufchar );
- exit( 0 );
- }
-
-
- RECORDS1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\RECORDS1.C
-
- /* RECORDS1.C illustrates reading and writing of file records using seek
- * functions including:
- * fseek rewind ftell
- *
- * Other general functions illustrated include:
- * tmpfile rmtmp fread fwrite
- *
- * Also illustrated:
- * struct
- *
- * See RECORDS2.C for a version program using fgetpos and fsetpos.
- */
-
- #include <stdio.h>
- #include <io.h>
- #include <string.h>
-
- /* File record */
- struct RECORD
- {
- int integer;
- long doubleword;
- double realnum;
- char string[15];
- } filerec = { 0, 1, 10000000.0, "eel sees tar" };
-
- main()
- {
- int c, newrec;
- size_t recsize = sizeof( filerec );
- FILE *recstream;
- long recseek;
-
- /* Create and open temporary file. */
- recstream = tmpfile();
-
- /* Write 10 unique records to file. */
- for( c = 0; c < 10; c++ )
- {
- ++filerec.integer;
- filerec.doubleword *= 3;
- filerec.realnum /= (c + 1);
- strrev( filerec.string );
-
- fwrite( &filerec, recsize, 1, recstream );
- }
-
- /* Find a specified record. */
- do
- {
- printf( "Enter record betweeen 1 and 10 (or 0 to quit): " );
- scanf( "%d", &newrec );
-
- /* Find and display valid records. */
- if( (newrec >= 1) && (newrec <= 10) )
- {
- recseek = (long)((newrec - 1) * recsize);
- fseek( recstream, recseek, SEEK_SET );
-
- fread( &filerec, recsize, 1, recstream );
-
- printf( "Integer:\t%d\n", filerec.integer );
- printf( "Doubleword:\t%ld\n", filerec.doubleword );
- printf( "Real number:\t%.2f\n", filerec.realnum );
- printf( "String:\t\t%s\n\n", filerec.string );
- }
- } while( newrec );
-
- /* Starting at first record, scan each for specific value. The following
- * line is equivalent to:
- * fseek( recstream, 0L, SEEK_SET );
- */
- rewind( recstream );
-
- do
- {
- fread( &filerec, recsize, 1, recstream );
- } while( filerec.doubleword < 1000L );
-
- recseek = ftell( recstream );
- /* Equivalent to: recseek = fseek( recstream, 0L, SEEK_CUR ); */
- printf( "\nFirst doubleword above 1000 is %ld in record %d\n",
- filerec.doubleword, recseek / recsize );
-
- /* Close and delete temporary file. */
- rmtmp();
- }
-
-
- RECORDS2.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\RECORDS2.C
-
- /* RECORDS2.C illustrates reading and writing of file records with the
- * following functions:
- * fgetpos fsetpos
- *
- * See RECORDS1.C for a version using fseek, rewind, and ftell.
- */
-
- #include <stdio.h>
- #include <io.h>
-
- /* File record */
- struct RECORD
- {
- int integer;
- long doubleword;
- double realnum;
- } filerec = { 0, 1, 10000000.0 };
-
- main()
- {
- int c, newrec;
- size_t recsize = sizeof( filerec );
- FILE *recstream;
- fpos_t *recpos;
-
- /* Create and open temporary file. */
- recstream = tmpfile();
-
- /* Write 10 unique records to file. */
- for( c = 0; c < 10; c++ )
- {
- ++filerec.integer;
- filerec.doubleword *= 3;
- filerec.realnum /= (c + 1);
-
- fwrite( &filerec, recsize, 1, recstream );
- }
-
- /* Find a specified record. */
- do
- {
- printf( "Enter record betweeen 1 and 10 (or 0 to quit): " );
- scanf( "%d", &newrec );
-
- /* Find and display valid records. */
- if( (newrec >= 1) && (newrec <= 10) )
- {
- *recpos = (fpos_t)((newrec - 1) * recsize);
- fsetpos( recstream, recpos );
- fread( &filerec, recsize, 1, recstream );
-
- printf( "Integer:\t%d\n", filerec.integer );
- printf( "Doubleword:\t%ld\n", filerec.doubleword );
- printf( "Real number:\t%.2f\n", filerec.realnum );
- }
- } while( newrec );
-
- /* Starting at first record, scan each for specific value. */
- *recpos = (fpos_t)0;
- fsetpos( recstream, recpos );
- do
- {
- fread( &filerec, recsize, 1, recstream );
- } while( filerec.doubleword < 1000L );
-
- fgetpos( recstream, recpos );
- printf( "\nFirst doubleword above 1000 is %ld in record %d\n",
- filerec.doubleword, *recpos / recsize );
-
- /* Close and delete temporary file. */
- rmtmp();
- }
-
-
- ROTATE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\ROTATE.C
-
- /* ROTATE.C illustrates bit rotation functions including:
- * _rotl _rotr _lrotl _lrotr
- *
- * _lrotl and _lrotr are not shown in the program, but they are the
- * same as _rotl and _rotr except that they work on long integers.
- */
-
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
-
- char *binstr( int num, char *buffer ); /* Prototype */
-
- main()
- {
- int shift, i, ir, il;
- char tmpbuf[20];
-
- printf( "Enter integer: " );
- scanf( "%d", &i );
- printf( "\n\n" );
-
- /* Display table header for rotates. */
- printf( "%6s %-7s %16s %-7s %16s\n",
- " ", "Left", " ", "Right", " " );
- printf( "%6s %7s %16s %7s %16s\n\n",
- "Shift", "Decimal", "Binary", "Decimal", "Binary" );
-
- /* Display table of rotated values. */
- for( shift = 0; shift <= 16; shift++ )
- {
- il = _rotl( i, shift ); ;
- printf( "%5d %7d %16s ", shift, il, binstr( il, tmpbuf ) );
- ir = _rotr( i, shift );
- printf( "%7d %16s\n", ir, binstr( ir, tmpbuf ) );
- }
- }
-
- /* Convert integer to string of 16 binary characters. */
- char *binstr( int num, char *buffer )
- {
- char tmp[17];
- int len;
-
- memset( buffer, '0', 16 );
- len = strlen( itoa( num, tmp, 2 ) );
- strcpy( buffer + 16 - len, tmp );
- return buffer;
- }
-
-
- RWFILE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\RWFILE.C
-
- /* RWFILE.C: Reads and writes a file. */
-
- #include <stdio.h>
- #include <string.h>
- #include <fcntl.h>
- #include <sys\types.h>
- #include <sys\stat.h>
- #include <io.h>
-
- #define BUFF 512
-
- main()
- {
- char inbuffer[BUFF];
- char outbuffer[BUFF];
- int infile, outfile, length, num;
-
- strcpy( outbuffer, "Happy Birthday." );
- length = strlen( outbuffer );
- length++;
-
- if( (outfile = open( "testfile.bin",
- O_CREAT | O_WRONLY | O_BINARY, S_IWRITE )) != -1 )
- {
- if( (num = write( outfile, outbuffer, length )) == -1 )
- perror( "Error in writing" );
- printf( "\nBytes written to file: %d\n", num );
- close( outfile );
- }
- else
- perror( "Error opening outfile" );
-
- if( (infile = open( "testfile.bin", O_RDONLY | O_BINARY )) != -1 )
- {
- while( length = read( infile, inbuffer, BUFF ) )
- printf( "%d bytes received so far.\n", length );
- close( infile );
- printf( "%s\n", inbuffer );
- }
- else
- perror( "Error opening infile" );
- }
-
-
- SBRK.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\MEMORY\SBRK.C
-
- /* SBRK.C illustrates memory allocation with function:
- * sbrk
- */
-
- #include <malloc.h>
- #include <stdio.h>
- #include <stdlib.h>
-
- main()
- {
- char *bufA, *bufB, *bufC;
-
- /* Allocate 512 bytes. */
- if( (bufA = sbrk( 512 )) == (char *)-1 )
- exit( 1 );
- printf( "Allocate:\t256\tLocation:\t%p\n", (int far *)bufA );
-
- /* Allocate 50 bytes. */
- if( (bufB = sbrk( 50 )) == (char *)-1 )
- exit( 1 );
- printf( "Allocate:\t50\tLocation:\t%p\n", (int far *)bufB );
-
- /* Deallocate 256 bytes. */
- sbrk( -256 );
- printf( "Deallocate:\t256\n" );
-
- /* Allocate 20 bytes. */
- if( (bufC = sbrk( 20 )) == (char *)-1 )
- exit( 1 );
- printf( "Allocate:\t20\tLocation:\t%p\n", (int far *)bufC );
- exit( 0 );
- }
-
-
- SCANF.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\SCANF.C
-
- /* SCANF.C illustrates formatted input. Functions illustrated include:
- * scanf fflush flushall
- *
- * For other examples of formatted input, see TABLE.C (fscanf) and
- * SETTIME.C (sscanf).
- */
-
- #include <stdio.h>
- #include <conio.h>
-
- main()
- {
- int result, integer;
- float fp;
- char string[81];
-
- /* Get numbers. */
- printf( "Enter an integer and a floating point number: " );
- scanf( "%d %f", &integer, &fp );
- printf( "%d + %f = %f\n\n", integer, fp, integer + fp );
-
- /* Read each word as a string. */
- printf( "Enter a sentence of four words with scanf: " );
- for( integer = 0; integer < 4; integer++ )
- {
- scanf( "%s", string );
- printf( "%s\n", string );
- }
-
- /* Clear the input buffer and get with gets. */
- fflush( stdin );
- printf( "Enter the same sentence with gets: " );
- gets( string );
- printf( "%s\n", string );
-
- /* Specify delimiters. The ^ inside the brackets says accept any
- * character except the following other characters in brackets (tab
- * and newline in the example).
- */
- printf( "Enter the same sentence with scanf and delimiters: " );
- scanf( "%[^\n\t]s", string );
- printf( "%s\n", string );
-
- /* Loop until input value is 0. */
- printf( "\n\nEnter numbers in C decimal (num), hex (0xnum), " );
- printf( "or octal (0num) format.\nEnter 0 to quit\n\n" );
- do
- {
- printf( "Enter number: " );
- result = scanf( "%i", &integer );
- if( result )
- /* Display valid integers. */
- printf( "Decimal: %i Octal: 0%o Hexadecimal: 0x%X\n\n",
- integer, integer, integer );
- else
- { /* Read invalid characters. Then flush and continue. */
- scanf( "%s", string );
- printf( "Invalid number: %s\n\n", string );
- flushall();
- integer = 1;
- }
- } while( integer );
- }
-
-
- SEEK.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\SEEK.C
-
- /* SEEK.C illustrates low-level file I/O functions including:
- * filelength lseek tell
- */
-
- #include <io.h>
- #include <conio.h>
- #include <stdio.h>
- <fcntl.h> /* O_ constant definitions */
- #include <process.h>
-
- void error( char *errmsg );
-
- main()
- {
- int handle, ch;
- unsigned count;
- long position, length;
- char buffer[2], fname[80];
-
- /* Get file name and open file. */
- do
- {
- printf( "Enter file name: " );
- gets( fname );
- handle = open( fname, O_BINARY | O_RDONLY );
- } while( handle == -1 );
-
- /* Get and print length. */
- length = filelength( handle );
- printf( "\nFile length of %s is: %ld\n\n", fname, length );
-
- /* Report the character at a specified position. */
- do
- {
- printf( "Enter integer position less than file length: " );
- scanf( "%ld", &position );
- } while( position > length );
-
- lseek( handle, position, SEEK_SET );
- if( read( handle, buffer, 1 ) == -1 )
- error( "Read error" );
- printf( "Character at byte %ld is ASCII %u ('%c')\n\n",
- position, *buffer, *buffer );
-
- /* Search for a specified character and report its position. */
- lseek( handle, 0L, SEEK_SET); /* Set to position 0 */
- printf( "Type character to search for: " );
- ch = getche();
-
- /* Read until character is found */
- do
- {
- if( (count = read( handle, buffer, 1 )) == -1 )
- error( "Read error" );
- } while( (*buffer != (char)ch) && count );
-
- /* Report the current position. */
- position = tell( handle );
- if( count )
- printf( "\nFirst ASCII %u ('%c') is at byte %ld\n",
- ch, ch, position );
- else
- printf( "\nASCII %u ('%c') not found\n", ch, ch );
- close( handle );
- exit( 0 );
- }
-
- void error( char *errmsg )
- {
- perror( errmsg );
- exit( 1 );
- }
-
-
- SETROWS.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\SETROWS.C
-
- /* SETROWS.C illustrates
- * _settextrows
- */
-
- #include <graph.h>
- #include <stdlib.h>
-
- main( int argc, char ** argv )
- {
- struct videoconfig vc;
- short rows = atoi( argv[1] );
-
- _getvideoconfig( &vc );
-
- /* Make sure new rows is valid and the same as requested rows. */
- if( !rows || (_settextrows( rows ) != rows) )
- _outtext( "\nSyntax: SETROWS [ 25 | 43 | 50 ]\n" );
-
- /* Always return old rows for batch file testing. */
- exit( vc.numtextrows );
- }
-
-
- SETSTR.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\SETSTR.C
-
- /* SETSTR.C illustrate string and memory set functions including:
- * memset strnset strset
- */
-
- #include <memory.h>
- #include <string.h>
- #include <stdio.h>
-
- char string[60] = "The quick brown dog jumps over the lazy fox ";
- /* 1 2 3 4 5 *
- * 12345678901234567890123456789012345678901234567890 */
- main()
- {
- printf( "Function:\tmemset with fill character '█'\n" );
- printf( "Destination:\t%s\n", string );
- memset( string + 10, '█', 5 );
- printf( "Result:\t\t%s\n\n", string );
-
- printf( "Function:\tstrnset with fill character '█'\n" );
- printf( "Destination:\t%s\n", string );
- strnset( string + 15, '█', 5 );
- printf( "Result:\t\t%s\n\n", string );
-
- printf( "Function:\tstrset with fill character '█'\n" );
- printf( "Destination:\t%s\n", string );
- strset( string + 20, '█' );
- printf( "Result:\t\t%s\n\n", string );
- }
-
-
- SETTIME.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\SETTIME.C
-
- /* SETTIME.C illustates getting and setting the DOS time and date using:
- * _dos_gettime _dos_settime _dos_getdate _dos_setdate
- *
- * Formatted input to a string is illustrated using:
- * sscanf
- */
-
- #include <dos.h>
- #include <stdio.h>
- #include <conio.h>
- #include <string.h>
-
- struct dosdate_t ddate;
- struct dostime_t dtime;
-
- main()
- {
- unsigned tmpday, tmpmonth, tmpyear;
- unsigned tmphour, tmpminute, tmpsecond;
- static char *days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }
- char tmpbuf[20];
-
- /* Get current date. */
- _dos_getdate( &ddate );
- printf( "Date: %u/%02u/%02u %s\n",
- ddate.month, ddate.day, ddate.year - 1900,
- days[ddate.dayofweek] );
- printf( "Enter new date: " );
-
- /* Get a date string and if it's not 0 (for CR), assign it to date. */
- gets( tmpbuf );
- if( strlen( tmpbuf ) )
- {
- /* NOTE: You must read the month and day into a temporary unsigned
- * variable. If you try to read directly into the unsigned char
- * values ddate.day or ddate.month, sscanf (or scanf) will read a
- * word, thus overriding adjacent bytes.
- */
- sscanf( tmpbuf, "%u/%u/%u", &tmpmonth, &tmpday, &tmpyear );
- if( (tmpyear - 80) <= 20 )
- ddate.year = tmpyear + 1900;
- else if( (tmpyear >= 1980) && (tmpyear <= 2099 ) )
- ddate.year = tmpyear;
- if( (tmpmonth + 1) <= 13 )
- ddate.month = (unsigned char)tmpmonth;
- if( (tmpday + 1) <= 32 )
- ddate.day = (unsigned char)tmpday;
- _dos_setdate( &ddate );
- _dos_getdate( &ddate );
- printf( "New date: %u/%02u/%02u %s\n",
- ddate.month, ddate.day, ddate.year - 1900,
- days[ddate.dayofweek] );
- }
-
- /* Get current time. */
- _dos_gettime( &dtime );
- printf( "Time: %u:%02u:%02u\n", dtime.hour, dtime.minute, dtime.second );
- printf( "Enter new time: " );
-
- /* Get a time string and if it's not 0 (for CR), assign it to time. */
- gets( tmpbuf );
- if( strlen( tmpbuf ) )
- {
- sscanf( tmpbuf, "%u:%u:%u", &tmphour, &tmpminute, &tmpsecond );
- if( tmphour < 24 )
- dtime.hour = (unsigned char)tmphour;
- if( tmpminute < 60 )
- dtime.minute = (unsigned char)tmpminute;
- if( tmpsecond < 60 )
- dtime.second = (unsigned char)tmpsecond;
- _dos_settime( &dtime );
- _dos_gettime( &dtime );
- printf( "New time: %u:%02u:%02u\n",
- dtime.hour, dtime.minute, dtime.second );
- }
- }
-
-
-
- SHOWME1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\SHOWME1.C
-
- /* SHOWME1.C: Demonstrate passing by value. */
-
- #include <stdio.h>
-
- void showme( int any, int old, int name );
-
- main()
- {
- int x = 10, y = 20, z = 30;
- showme( z, y, x );
-
- printf( "z=%d y=%d x=%d\n", z, y, x );
- }
-
- void showme( int any, int old, int name )
- {
- printf( "any=%d old=%d name=%d\n", any, old, name );
- any = 55;
- old = 66;
- name = 77;
- printf( "any=%d old=%d name=%d\n", any, old, name );
- }
-
-
- SIGNAL1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\SIGNAL1.C
-
- /* SIGNAL.C illustrates setting up signal interrupt routines. Functions
- * illustrated include:
- * signal abort raise _fpreset
- *
- * The program also illustrates saving an environment and then doing a
- * long jump to return to it using functions:
- * setjmp longjmp
- */
-
- #include <stdio.h>
- #include <conio.h>
- #include <signal.h>
- #include <process.h>
- #include <setjmp.h>
- #include <stdlib.h>
- #include <float.h>
-
- void ctrlchandler( void ); /* Prototypes */
- void aborthandler( void );
- void fphandler( int sig, int num );
-
- jmp_buf mark; /* Address for long jump to jump to */
-
- main()
- {
- double n1, n2, r;
- int jmpret;
-
- /* Modify abort behavior. */
- if( signal( SIGABRT, aborthandler ) == SIG_ERR )
- {
- printf( "Couldn't set SIGABRT\n" );
- exit( 1 );
- }
-
- /* Modify CTRL+C behavior. */
- if( signal( SIGINT, ctrlchandler ) == SIG_ERR )
- {
- fprintf( stderr, "Couldn't set SIGINT\n" );
- abort();
- }
-
- /* Set up pointer to error handler. */
- if( signal( SIGFPE, fphandler ) == SIG_ERR )
- {
- fprintf( stderr, "Couldn't set SIGFPE\n" );
- abort();
- }
-
- /* Save stack environment for return in case of error. First time
- * through, jmpret is 0, so true conditional is executed. If an
- * error occurs, jmpret will be set to -1 and false conditional
- * will be executed.
- */
- jmpret = setjmp( mark );
- if( jmpret == 0 )
- {
- /* Try forcing error by dividing by 0 or using very large numbers. */
- printf( "Enter number to divide or CTRL-C: " );
- scanf( "%lf", &n1 );
- printf( "Enter number to divide by or CTRL-C: " );
- scanf( "%lf", &n2 );
- r = n1 / n2;
-
- /* This won't be reached if error occurs. */
- printf( "\n%4.3g / %4.3g = %4.3g\n", n1, n2, r );
- }
- else
- printf( "Recovered from floating-point error\n" );
-
- /* Fake CTRL+C. Program will abort or exit, depending on user
- * response in handler.
- */
- raise( SIGINT );
- exit( 0 );
- }
-
- /* Function called whenever SIGINT (CTRL+C) interrupt is called. */
- void ctrlchandler()
- {
- int ch;
-
- /* Disallow CTRL+C during handler. */
- signal( SIGINT, SIG_IGN );
-
- printf( "Abort processing? " );
- ch = getche();
- printf( "\n" );
- if( (ch == 'y') || (ch == 'Y') )
- abort();
- else
-
- /* The CTRL+C interrupt must be reset to our handler since by
- * default DOS resets it to the system handler.
- */
- signal( SIGINT, ctrlchandler );
- }
-
- /* Function called whenever SIGABRT interrupt is called. */
- void aborthandler()
- {
- printf( "The abort() function was called\n" );
- exit( 1 );
- }
-
- /* Function called whenever SIGFPE interrupt is called. */
- void fphandler( int sig, int num )
- {
- printf( "Signal: %d Subcode: 0x%x\n", sig, num );
-
- /* Initialize floating-point package. */
- _fpreset();
-
- /* Restore calling environment and jump back to setjmp. Return -1
- * so that setjmp will return false for conditional test.
- */
- longjmp( mark, -1 );
- }
-
-
- SIZEOF.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\SIZEOF.C
-
- /* SIZEOF.C: Demonstrate sizeof operator. */
-
- #include <stdio.h>
-
- char string[] = "Hello, world";
-
- main()
- {
- int val;
- printf( "An int is %d bytes long\n", sizeof( int ) );
- printf( "The string is %d bytes long\n", sizeof string );
- }
-
-
- SORT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\SORT.C
-
- /* SORT.C illustates randomizing, sorting, and searching. Functions
- * illustrated include:
- * srand rand qsort
- * lfind lsearch bsearch
- *
- * The lsearch function is not specifically shown in the program, but
- * its use is the same as lfind except that if it does not find the
- * element, it inserts it at the end of the array rather than failing.
- */
-
- #include <search.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- #include <time.h>
-
- #define ASIZE 1000
- unsigned array[ASIZE];
-
- /* Macro to get a random integer within a specified range */
- #define getrandom( min, max ) ((rand() % (int)((max) - (min))) + (min) + 1)
-
- /* Must be declared before call */
- unsigned cmpgle( unsigned *arg1, unsigned *arg2 );
- unsigned cmpe( unsigned *arg1, unsigned *arg2 );
-
- main()
- {
- unsigned i, *result, elements = ASIZE, key = ASIZE / 2;
-
- /* Seed the random number generator with current time. */
- srand( (unsigned)time( 0L ) );
-
- /* Build a random array of integers. */
- printf( "Randomizing . . .\n" );
- for( i = 0; i < ASIZE; i++ )
- array[i] = getrandom( 1, ASIZE );
-
- /* Show every tenth element. */
- printf( "Printing every tenth element . . .\n" );
- for( i = 9; i < ASIZE; i += 10 )
- {
- printf( "%5u", array[i] );
- if( !(i % 15) )
- printf( "\n" );
- }
-
- /* Find element using linear search. */
- printf( "\nDoing linear search . . .\n" );
- result = (unsigned *)lfind( (char *)&key, (char *)array, &elements,
- sizeof( unsigned ), cmpe);
- if( result == NULL )
- printf( " Value %u not found\n", key );
- else
- printf( " Value %u found in element %u\n", key, result - array + 1);
-
- /* Sort array using Quicksort algorithm. */
- printf( "Sorting . . .\n" );
- qsort( (void *)array, (size_t)ASIZE, sizeof( int ), cmpgle );
-
- /* Show every tenth element. */
- printf( "Printing every tenth element . . .\n" );
- for( i = 9; i < ASIZE; i += 10 )
- {
- printf( "%5u", array[i] );
- if( !(i % 15) )
- printf( "\n" );
- }
-
- /* Find element using binary search. Note that the array must
- * be previously sorted before using binary search.
- */
- printf( "\nDoing binary search . . .\n" );
- result = (unsigned *)bsearch( (char *)&key, (char *)array, elements,
- sizeof( unsigned ), cmpgle);
- if( result == NULL )
- printf( " Value %u not found\n", key );
- else
- printf( " Value %u found in element %u\n", key, result - array + 1 )
-
- }
-
- /* Compare and return greater than (1), less than (-1), or equal to (0).
- * This function is called by qsort and bsearch.
- */
- unsigned cmpgle( unsigned *arg1, unsigned *arg2 )
- {
- if( *arg1 > *arg2 )
- return 1;
- else if( *arg1 < *arg2 )
- return -1;
- else
- return 0;
- }
-
- /* Compare and return equal (1) or not equal (0). This function is
- * called by lfind and lsearch.
- */
- unsigned cmpe( unsigned *arg1, unsigned *arg2 )
- {
- return !( *arg1 == *arg2 );
- }
-
-
- SORT1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\SORT1.C
-
- /* SORT1.C: Demonstrate sort with pointer notation.
- */
-
- #include <stdio.h>
- #define SIZE 4
-
- void sort( int size, double **p );
- void show( int size, double **p, double dd[] );
-
- main()
- {
- int x;
- static double d[] = { 3.333, 1.111, 2.222, 4.444 };
- static double *d_ptr[SIZE];
- for( x = 0; x < SIZE; x++ )
- d_ptr[x] = &d[x];
- show( SIZE, d_ptr, d );
- sort( SIZE, d_ptr );
- show( SIZE, d_ptr, d );
- }
-
- void sort( int size, double **p )
- {
- int x, x1;
- double *temp;
- for( x = 0; x < size - 1; x++ )
- for( x1 = x + 1; x1 < size; x1++ )
- {
- if( **(p+x) > **(p+x1) )
- {
- temp = *(p+x1);
- *(p+x1) = *(p+x);
- *(p+x) = temp;
- }
- }
- }
-
- void show( int size, double **p, double dd[] )
- {
- int x;
- printf( "------------------------" );
- printf( "------------------------\n" );
- for( x = 0; x < size; x++ )
- {
- printf( "*d_ptr[%d] = %1.3f ", x, **(p+x) );
- printf( "d_ptr[%d] = %u ", x, *(p+x) );
- printf( " d[%d] = %1.3f\n", x, dd[x] );
- }
- }
-
-
- SPAWN.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\SPAWN.C
-
- /* SPAWN.C illustrates the different versions of spawn including:
- * spawnl spawnle spawnlp spawnlpe
- * spawnv spawnve spawnvp spawnvpe
- *
- * Although SPAWN.C can spawn any program, you can verify how different
- * versions handle arguments and environment by compiling and
- * specifying the sample program ARGS.C. See EXEC.C for examples
- * of the similar exec functions.
- */
-
- #include <stdio.h>
- #include <conio.h>
- #include <process.h>
-
- char *my_env[] = /* Environment for spawn?e */
- {
- "THIS=environment will be",
- "PASSED=to child by the",
- "SPAWN=functions",
- NULL
- };
-
- main()
- {
- char *args[4], prog[80];
- int ch, r;
-
- printf( "Enter name of program to spawn: " );
- gets( prog );
- printf( " 1. spawnl 2. spawnle 3. spawnlp 4. spawnlpe\n" );
- printf( " 5. spawnv 6. spawnve 7. spawnvp 8. spawnvpe\n" );
- printf( "Type a number from 1 to 8 (or 0 to quit): " );
- ch = getche();
- if( (ch < '1') || (ch > '8') )
- exit( -1 );
- printf( "\n\n" );
-
- /* Arguments for spawnv? */
- args[0] = prog; /* First argument ignored under most */
- args[1] = "spawn??"; /* recent versions of DOS */
- args[2] = "two";
- args[2] = "two";
- args[3] = NULL;
-
- switch( ch )
- {
- case '1':
- r = spawnl( P_WAIT, prog, prog, "spawnl", "two", NULL );
- break;
- case '2':
- r = spawnle( P_WAIT, prog, prog, "spawnle", "two", NULL, my_env )
- break;
- case '3':
- r = spawnlp( P_WAIT, prog, prog, "spawnlp", "two", NULL );
- break;
- case '4':
- r = spawnlpe( P_WAIT, prog, prog, "spawnlpe", "two", NULL, my_env
- break;
- case '5':
- r = spawnv( P_WAIT, prog, args );
- break;
- case '6':
- r = spawnve( P_WAIT, prog, args, my_env );
- break;
- case '7':
- r = spawnvp( P_WAIT, prog, args );
- break;
- case '8':
- r = spawnvpe( P_WAIT, prog, args, my_env );
- break;
- default:
- break;
- }
- if( r == -1 )
- printf( "Couldn't spawn process" );
- else
- printf( "\nReturned from SPAWN!" );
- exit( r );
- }
-
-
- STACK.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\MEMORY\STACK.C
-
- /* STACK.C illustrates stack functions including:
- * alloca stackavail
- */
-
- #include <malloc.h>
- #include <stdio.h>
-
- main()
- {
- char *buffer;
-
- printf( "Bytes available on stack: %u\n", stackavail() );
-
- /* Allocate memory for string. */
- buffer = alloca( 120 * sizeof( char ) );
- printf( "Enter a string: " );
- gets( buffer );
- printf( "You entered: %s\n", buffer );
-
- printf( "Bytest available on stack: %u\n", stackavail() );
- }
-
-
- STATIC.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\STATIC.C
-
- /* STATIC.C: Demonstrate static variables. */
-
- #include <stdio.h>
-
- void add_ten( int val );
-
- main()
- {
- int val = 10;
- add_ten( val++ );
- add_ten( val );
- }
-
- void add_ten( int value )
- {
- static int methuselah;
- if( value == 10 )
- methuselah = 0;
- methuselah = methuselah + value;
- printf( "methuselah = %d\n", methuselah );
- }
-
-
- STRTONUM.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\STRTONUM.C
-
- /* STRTONUM.C illustrates string to number conversion functions including:
- * strtod strtol strtoul
- */
-
- #include <stdlib.h>
- #include <stdio.h>
-
- main()
- {
- char *string, *stopstring;
- double x;
- long l;
- unsigned long ul;
- int base;
-
- /* Convert string to double. */
- string = "3.1415926INVALID";
- x = strtod( string, &stopstring );
- printf( "\nString: %s\n", string );
- printf( "\tDouble:\t\t\t%f\n", x );
- printf( "\tScan stopped at:\t%s\n", stopstring );
-
- /* Convert string to long using bases 2, 4, and 8. */
- string = "-10110134932";
- printf( "\nString: %s\n", string );
- for( base = 2; base <= 8; base *= 2 )
- {
- l = strtol( string, &stopstring, base );
- printf( "\tBase %d signed long:\t%ld\n", base, l );
- printf( "\tScan stopped at:\t%s\n", stopstring );
- }
-
- /* Convert string to unsigned long using bases 2, 4, and 8. */
- string = "10110134932";
- printf( "\nString: %s\n", string );
- for( base = 2; base <= 8; base *= 2 )
- {
- ul = strtoul( string, &stopstring, base);
- printf("\tBase %d unsigned long:\t%ld\n", base, ul );
- printf("\tScan stopped at:\t%s\n", stopstring );
- }
- }
-
-
- SVBIN.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\SVBIN.C
-
- /* SVBIN.C: Saves integer variables in binary format.
- */
-
- #include <stdio.h>
- #define ASIZE 10
-
- main()
- {
- FILE *ap;
- int zebra[ASIZE], acopy[ASIZE], bcopy[ASIZE];
- int i;
-
- for( i = 0; i < ASIZE; i++ )
- zebra[i] = 7700 + i;
-
- if( (ap = fopen( "binfile", "wb" )) != NULL )
- {
- fwrite( zebra, sizeof(zebra), 1, ap );
- fclose( ap );
- }
- else
- perror( "Write error" );
-
- if( (ap = fopen( "morebin", "wb" )) != NULL )
- {
- fwrite( &zebra[0], sizeof(zebra[0]), ASIZE, ap );
- fclose( ap );
- }
- else
- perror( "Write error" );
-
- if( (ap = fopen( "binfile", "rb" )) != NULL )
- {
- printf( "Hexadecimal values in binfile:\n" );
- while( (i = fgetc( ap )) != EOF )
- printf( "%02X ", i );
- rewind( ap );
- fread( acopy, sizeof(acopy), 1, ap );
-
-
-
- rewind( ap );
- fread( &bcopy[0], sizeof( bcopy[0] ), ASIZE, ap);
- for( i=0; i<ASIZE; i++ )
- printf( "\nItem %d = %d\t%d", i, acopy[i], bcopy[i] );
- fclose( ap );
-
- }
- else
- perror( "Read error" );
-
- }
-
-
- SVTEXT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\SVTEXT.C
-
- /* SVTEXT.C: Save integer variables as text. */
-
- #include <stdio.h>
-
- int list[] = { 53, -23456, 50, 500, 5000, -99 };
- extern int errno;
- char fname[] = "numtext";
- char temp[81];
-
- main()
- {
- FILE *fptr;
- int i;
-
- if( (fptr = fopen( "numtext","wt" )) != NULL )
- {
- for( i=0; i<6; i++ )
- fprintf( fptr, "Item %d: %6d \n", i, list[i] );
- fclose( fptr );
- }
- else
- printf( "Error: Couldn't create file.\n" );
-
- if( (fptr = fopen( "badname", "rt" )) != NULL )
- {
- /* do nothing */
- }
- else
- {
- printf( "Error number: %d\n\t", errno );
- perror( "Couldn't open file BADNAME\n\t" );
- }
-
- if( (fptr = fopen( fname, "rt" )) != NULL )
- {
- list[0] = 0;
- fscanf( fptr, "Item %d: %d \n", &i, &list[0] );
- printf( "Values read from file:\t %d %d\n", i, list[0] );
- fgets( temp, 80, fptr );
- printf( "String from file: \t%s\n", temp );
- while( (i = fgetc( fptr )) != '\n' )
- printf( "char: %c \t ASCII: %d \n", i, i );
- rewind( fptr );
- printf( "Rewind to start -->\t%s", fgets( temp, 80, fptr ) );
- fclose( fptr );
- }
- else printf( "Trouble opening %s \n", fname );
- }
-
-
- SWAB.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\SWAB.C
-
- /* SWAB.C illustrates:
- * swab
- */
-
- #include <stdlib.h>
- #include <stdio.h>
-
- char from[] = "BADCFEHGJILKNMPORQTSVUXWZY";
- char to[] = "..........................";
-
- main()
- {
- printf( "Before:\t%s\n\t%s\n\n", from, to );
- swab( from, to, sizeof( from ) );
- printf( "After:\t%s\n\t%s\n\n", from, to );
- }
-
-
- SWITCH.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\SWITCH.C
-
- /* SWITCH.C: Demonstrate switch statement. */
-
- #include <stdio.h>
- #include <conio.h>
- #define B_KEY 'b'
- #define ENTER_KEY '\r'
-
- main()
- {
- char ch;
- printf( "Press the b key to hear a bell.\n" );
- ch = getch();
- switch( ch )
- {
- case B_KEY:
- printf( "Beep!\a\n" );
- break;
- case ENTER_KEY:
- printf( "What a boring selection...\n" );
- break;
- default:
- printf( "Bye bye." );
- break;
- }
- }
-
-
- SYSCALL.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\SYSCALL.C
-
- /* SYSCALL.C illustrates system calls to DOS and BIOS interrupts using
- * functions:
- * intdos intdosx bdos
- * int86 int86x segread
- *
- * The int86x call is not specifically shown in the example, but it is
- * the same as intdosx except that an interrupt number must be supplied.
- */
-
- #include <dos.h>
- #include <stdio.h>
- #define LPT1 0
-
- union REGS inregs, outregs;
- struct SREGS segregs;
-
- main()
- {
- const char far *buffer = "Dollar-sign terminated string\n\r$";
- char far *p;
-
- /* Print a $-terminated string on the screen using DOS function 0x9. */
- inregs.h.ah = 0x9;
- inregs.x.dx = FP_OFF( buffer );
- segregs.ds = FP_SEG( buffer );
- intdosx( &inregs, &outregs, &segregs );
-
- /* Get DOS version using DOS function 0x30. */
- inregs.h.ah = 0x30;
- intdos( &inregs, &outregs );
- printf( "\nMajor: %d\tMinor: %d\tOEM number: %d\n\n",
- outregs.h.al, outregs.h.ah, outregs.h.bh );
-
- segread( &segregs );
- printf( "Segments:\n\tCS\t%.4x\n\tDS\t%.4x\n\tES\t%.4x\n\tSS\t%.4x\n\n",
- segregs.cs, segregs.ds, segregs.es, segregs.ss );
-
- /* Make sure printer is available. Fail if any error bit is on,
- * or if either operation bit is off.
- */
- inregs.h.ah = 0x2;
- inregs.x.dx = LPT1;
- int86( 0x17, &inregs, &outregs );
- if( (outregs.h.ah & 0x29) || !(outregs.h.ah & 0x80) ||
- !(outregs.h.ah & 0x10) )
- printf( "Printer not available." );
- else
- {
- /* Output a string to the printer using DOS function 0x5. */
- for( p = buffer; *p != '$'; p++ )
- bdos( 0x05, *p, 0 );
-
- /* Do print screen. */
- inregs.h.ah = 0x05;
- int86( 0x05, &inregs, &outregs );
- }
- }
-
-
- SYSINFO.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\SYSINFO.C
-
- /* SYSINFO.C illustrates miscellaneous DOS and BIOS status functions
- * including:
- * _dos_getdrive _dos_setdrive _dos_getdiskfree
- * _bios_memsize _bios_equiplist _bios_printer
- *
- * See DISK.C for another example of _dos_getdiskfree.
- *
- * Also illustrated:
- * union bitfield struct
- */
-
- #include <dos.h>
- #include <bios.h>
- #include <conio.h>
- #include <stdio.h>
- #define LPT1 0
-
- main()
- {
- struct diskfree_t drvinfo;
- unsigned drive, drivecount, memory, pstatus;
- union
- { /* Access equiment either as: */
- unsigned u; /* unsigned or */
- struct /* bit fields */
- {
- unsigned diskflag : 1; /* Diskette drive installed? */
- unsigned coprocessor : 1; /* Coprocessor? (except on PC) */
- unsigned sysram : 2; /* Ram on system board */
- unsigned video : 2; /* Startup video mode */
- unsigned disks : 2; /* Drives 00=1, 01=2, 10=3, 11=4 */
- unsigned dma : 1; /* 0=Yes, 1=No (1 for PC Jr.) */
- unsigned comports : 3; /* Serial ports */
- unsigned game : 1; /* Game adapter installed? */
- unsigned modem : 1; /* Internal modem? */
- unsigned printers : 2; /* Number of printers */
- } bits;
- } equip;
- static char y[] = "YES", n[] = "NO";
-
- /* Get current drive. */
- _dos_getdrive( &drive );
- printf( "Current drive:\t\t\t%c:\n", 'A' + drive - 1 );
-
- /* Set drive to current drive in order to get number of drives. */
- _dos_setdrive( drive, &drivecount );
-
- _dos_getdiskfree( drive, &drvinfo );
- printf( "Disk space free:\t\t%ld\n",
- (long)drvinfo.avail_clusters *
- drvinfo.sectors_per_cluster *
- drvinfo.bytes_per_sector );
-
- /* Get new drive and number of logical drives in system. */
- _dos_getdrive( &drive );
- printf( "Number of logical drives:\t%d\n", drivecount );
-
- memory = _bios_memsize();
- printf( "Memory:\t\t\t\t%dK\n", memory );
-
- equip.u = _bios_equiplist();
-
- printf( "Disk drive installed:\t\t%s\n", equip.bits.diskflag ? y : n );
- printf( "Coprocessor installed:\t\t%s\n", equip.bits.coprocessor ? y : n
- printf( "Game adapter installed:\t\t%s\n", equip.bits.game ? y : n );
- printf( "Serial ports:\t\t\t%d\n", equip.bits.comports );
- printf( "Number of printers:\t\t%d\n", equip.bits.printers );
-
- /* Fail if any error bit is on, or if either operation bit is off. */
- pstatus = _bios_printer( _PRINTER_STATUS, LPT1, 0 );
- if( (pstatus & 0x29) || !(pstatus & 0x80) || !(pstatus & 0x10) )
- pstatus = 0;
- else
- pstatus = 1;
- printf( "Printer available:\t\t%s\n", pstatus ? y : n );
- }
-
-
-
- TABLE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\TABLE.C
-
- /* TABLE.C illustrates reading and writing formatted file data using
- * functions:
- * fprintf fscanf
- */
-
- #include <stdio.h>
- #include <io.h>
- #include <fcntl.h>
- #include <sys\types.h>
- #include <sys\stat.h>
- #include <stdlib.h>
-
- main()
- {
- char buf[128];
- FILE *ftable;
- long l, tl;
- float fp, tfp;
- int i, c = 'A';
-
- /* Open an existing file for reading. Fail if file doesn't exist. */
- if( (ftable = fopen( "table.smp", "r")) != NULL )
- {
- /* Read data from file and total it. */
- for( i = 0, tl = 0, tfp = 0.0; i < 10; i++ )
- {
- fscanf( ftable, "\t%s %c: %ld %f\n", buf, &c, &l, &fp );
- tl += l;
- tfp += fp;
- printf( "\t%s %c: %7ld %9.2f\n", buf, c, l, fp );
- }
- printf( "\n\tTotal: %7ld %9.2f\n", tl, tfp );
- }
- else
- {
- /* File did not exist. Create it for writing. */
- if( (ftable = fopen( "table.smp", "w" )) == NULL )
- exit( 1 );
-
- /* Write table to file. */
- for( i = 0, l = 99999, fp = 3.14; i < 10; i++ )
- fprintf( ftable, "\tLine %c: %7ld %9.2f\n",
- c++, l /= 2, fp *= 2 );
-
- printf( "Created table file. Run again to read it.\n" );
- }
- fclose( ftable );
- exit( 0 );
- }
-
-
- TEMPNAME.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\TEMPNAME.C
-
- /* TEMPNAME.C illustrates:
- * tmpnam tempnam
- */
-
- #include <stdio.h>
-
- main()
- {
- char *name1, *name2;
- int c;
-
- /* Create several temporary file names in the current directory. */
- for( c = 0; c < 5; c++ )
- if( (name1 = tmpnam( NULL )) != NULL )
- printf( "%s is a safe temporary file name.\n", name1 );
-
- /* Create a temporary file name with prefix TEMP and place it in
- * the first of these directories that exists:
- * 1. TMP environment directory
- * 2. C:\TEMPFILE
- * 3. P_tmpdir directory (defined in stdio.h)
- */
- if( (name2 = tempnam( "C:\\TEMPFILE", "TEMP" )) != NULL )
- printf( "%s is a safe temporary file name.\n", name2 );
-
- }
-
-
- TEXT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\TEXT.C
-
- /* TEXT.C illustrates text output functions including:
- * _gettextcolor _getbkcolor _gettextposition _outtext
- * _settextcolor _setbkcolor _settextposition _clearscreen
- *
- * See MODES.C for another use of _outtext and WINDOW.C for another
- * use of _clearscreen.
- */
-
- #include <conio.h>
- #include <stdio.h>
- #include <graph.h>
-
- char buffer [80];
-
- main()
- {
- short blink, fgd, oldfgd;
- long bgd, oldbgd;
- struct rccoord oldpos;
-
- /* Save original foreground, background, and text position. */
- oldfgd = _gettextcolor();
- oldbgd = _getbkcolor();
- oldpos = _gettextposition();
- _clearscreen( _GCLEARSCREEN );
-
- /* First time no blink, second time blinking. */
- for( blink = 0; blink <= 16; blink += 16 )
- {
-
- /* Loop through 8 background colors. */
- for( bgd = 0; bgd < 8; bgd++ )
- {
- _setbkcolor( bgd );
- _settextposition( (short)bgd + ((blink / 16) * 9) + 3, 1 );
- _settextcolor( 7 );
- sprintf(buffer, "Back: %d Fore:", bgd );
- _outtext( buffer );
-
- /* Loop through 16 foreground colors. */
- for( fgd = 0; fgd < 16; fgd++ )
- {
- _settextcolor( fgd + blink );
- sprintf( buffer, " %2d ", fgd + blink );
- _outtext( buffer );
- }
- }
- }
- getch();
-
- /* Restore original foreground and background. */
- _settextcolor( oldfgd );
- _setbkcolor( oldbgd );
- _clearscreen( _GCLEARSCREEN );
- _settextposition( oldpos.row, oldpos.col );
- }
-
-
- TIMES.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\TIMES.C
-
- /* TIMES.C illustrates various time and date functions including:
- * time ftime ctime
- * localtime asctime gmtime mktime
- * _strtime _strdate tzset
- *
- * Also the global variable:
- * tzname
- */
-
- #include <time.h>
- #include <stdio.h>
- #include <sys\types.h>
- #include <sys\timeb.h>
- #include <string.h>
-
- main()
- {
- char timebuf[9], datebuf[9];
- static char ampm[] = "AM";
- time_t ltime;
- struct timeb tstruct;
- struct tm *today, *tomorrow, *gmt;
-
- /* Set time zone from TZ environment variable. If TZ is not set,
- * PST8PDT is used (Pacific standard time, daylight savings).
- */
- tzset();
-
- /* Get Xenix-style time and display as number and string. */
- time( <ime );
- printf( "Time in seconds since GMT 1/1/70:\t%ld\n", ltime );
- printf( "Xenix time and date:\t\t\t%s", ctime( <ime ) );
-
- /* Display GMT. */
- gmt = gmtime( <ime );
- printf( "Greenwich Mean Time:\t\t\t%s", asctime( gmt ) );
-
- /* Convert to local time structure and adjust for PM if necessary. */
- today = localtime( <ime );
- if( today->tm_hour > 12 )
- {
- strcpy( ampm, "PM" );
- today->tm_hour -= 12;
- }
- /* Note how pointer addition is used to skip the first 11 characters
- * and printf is used to trim off terminating characters.
- */
- printf( "12-hour time:\t\t\t\t%.8s %s\n",
- asctime( today ) + 11, ampm );
-
- /* Make tomorrow's time. */
- *tomorrow = *today;
- tomorrow->tm_mday++;
- if( mktime( tomorrow ) != (time_t)-1 )
- printf( "Tomorrow's date:\t\t\t%d/%d/%.2d\n",
- tomorrow->tm_mon + 1, tomorrow->tm_mday, tomorrow->tm_year );
-
- /* Display DOS date and time. */
- _strtime( timebuf );
- printf( "DOS time:\t\t\t\t%s\n", timebuf );
- _strdate( datebuf );
- printf( "DOS date:\t\t\t\t%s\n", datebuf );
-
- /* Print additional time information. */
- ftime( &tstruct );
- printf( "Plus miliseconds:\t\t\t%u\n", tstruct.millitm );
- printf( "Zone difference in seconds from GMT:\t%u\n", tstruct.timezone );
- printf( "Time zone name:\t\t\t\t%s\n", tzname[0] );
- printf( "Daylight savings:\t\t\t%s\n", tstruct.dstflag ? "YES" : "NO" );
- }
-
-
- TOKEN.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\TOKEN.C
-
- /* TOKEN.C illustrates tokenizing and searching for any of several
- * characters. Functions illustrated include:
- * strcspn strspn strpbrk strtok
- */
-
- #include <string.h>
- #include <stdio.h>
-
- main()
- {
- char string[100];
- static char vowels[] = "aeiouAEIOU", seps[] = " \t\n,";
- char *p;
- int count;
-
- printf( "Enter a string: " );
- gets( string );
-
- /* Delete one word at a time. */
- p = string;
- while( *p )
- {
- printf( "String remaining: %s\n", p );
- p += strcspn( p, seps ); /* Find next separator */
- p += strspn( p, seps ); /* Find next non-separator */
- }
-
- /* Count vowels. */
- p = string;
- count = 0;
- while( *(p - 1) )
- {
- p = strpbrk( p, vowels ); /* Find next vowel */
- p++;
- count++;
- }
- printf( "\nVowels in string: %d\n\n", count - 1 );
-
- /* Break into tokens. */
- count = 0;
- p = strtok( string, seps ); /* Find first token */
- while( p != NULL )
- {
- printf( "Token %d: %s\n", ++count, p );
- p = strtok( NULL, seps ); /* Find next token */
- }
- }
-
-
- TOOLS.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\UTILITY\TOOLS.C
-
- /* TOOLS - Module containing several general functions that can be used
- * from any program. Include TOOLS.H to use.
- */
-
- #include <conio.h>
- #include <string.h>
- #include <time.h>
- #include <graph.h>
- #include <bios.h>
- #include "tools.h"
-
- /* delay - Pauses for a specified number of microseconds. Used to slow
- * life by delaying between generations.
- *
- * Params: wait - time in microseconds
- *
- * Return: None
- */
- void delay( clock_t wait )
- {
-
- clock_t t1, t2;
-
- if( !wait )
- return;
-
- t1 = wait + clock();
- do
- {
- t2 = clock();
- } while( t2 < t1 );
- }
-
- /* getkey - Gets a key from the keyboard. This routine distinguishes
- * between ASCII keys and function or control keys with different shift
- * states. It also accepts a flag to return immediately if no key is
- * available.
- *
- * Params: waitflag - Code to indicate how to handle keyboard buffer:
- * NO_WAIT Return 0 if no key in buffer, else return key
- * WAIT Return first key if available, else wait for key
- * CLEAR_WAIT Throw away any key in buffer and wait for new key
- *
- * Return: One of the following:
- *
- * Keytype High Byte Low Byte
- * ------- --------- --------
- * No key available (only with NO_WAIT) 0 0
- * ASCII value 0 ASCII code
- * Unshifted function or keypad 1 scan code
- * Shifted function or keypad 2 scan code
- * CTRL function or keypad 3 scan code
- * ALT function or keypad 4 scan code
- *
- * Note: getkey cannot return codes for keys not recognized by BIOS
- * int 16, such as the CTRL-UP or the 5 key on the numeric keypad.
- */
- unsigned getkey( int waitflag )
- {
- unsigned inkey, shiftstate;
-
- /* If CLEAR_WAIT, drain the keyboard buffer. */
- if( waitflag == CLEAR_WAIT )
- while( _bios_keybrd( _KEYBRD_READY ) )
- _bios_keybrd( _KEYBRD_READ );
-
- /* If NO_WAIT, return 0 if there is no key ready. */
- if( !waitflag && !_bios_keybrd( _KEYBRD_READY ) )
- return FALSE;
-
- /* Get key code. */
- inkey = _bios_keybrd( _KEYBRD_READ );
-
- /* If low byte is not zero, its an ASCII key. Check scan code to see
- * if it's on the numeric keypad. If not, clear high byte and return.
- */
- if( inkey & 0x00ff )
- if( (inkey >> 8) < 69 )
- return( inkey & 0x00ff );
-
- /* For function keys and numeric keypad, put scan code in low byte
- * and shift state codes in high byte.
- */
- inkey >>= 8;
- shiftstate = _bios_keybrd( _KEYBRD_SHIFTSTATUS ) & 0x000f;
- switch( shiftstate )
- {
- case 0:
- return( 0x0100 | inkey ); /* None (1) */
- case 1:
- case 2:
- case 3:
- return( 0x0200 | inkey ); /* Shift (2) */
- case 4:
- return( 0x0300 | inkey ); /* Control (3) */
- case 8:
- return( 0x0400 | inkey ); /* Alt (4) */
- }
- }
-
-
- TOUCH1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\TOUCH1.C
-
- /* TOUCH.C illustrates wild card handling and changing file time and
- * attribute. Functions used include:
- * _dos_findfirst _dos_findnext
- * utime chmod
- */
-
- #include <stdlib.h>
- #include <stdio.h>
- #include <conio.h>
- #include <ctype.h>
- #include <dos.h>
- #include <io.h>
- #include <sys\types.h>
- #include <sys\utime.h>
- #include <sys\stat.h>
-
- void fileinfo( struct find_t *find );
- char *timestr( unsigned d, char *buf );
- char *datestr( unsigned d, char *buf );
-
- main( int argc, char *argv[] )
- {
- struct find_t find;
-
- /* Find first matching file, then find additional matches. */
- if( !_dos_findfirst( argv[1], 0xffff, &find ) )
- fileinfo( &find );
- else
- {
- printf( " SYNTAX: TOUCH <wildfilespec>" );
- return 1;
- }
- while( !_dos_findnext( &find ) )
- fileinfo( &find );
- }
-
- void fileinfo( struct find_t *pfind )
- {
- char timebuf[10], datebuf[10], *pkind;
- int ch;
-
- datestr( pfind->wr_date, datebuf );
- timestr( pfind->wr_time, timebuf );
-
- if( pfind->attrib & _A_SUBDIR )
- pkind = "Directory";
- else if( pfind->attrib & _A_VOLID )
- pkind = "Label";
- else
- pkind = "File";
-
- printf( "%-12s %6ld %8s %9s %-9s %c %c %c %c\n",
- pfind->name, pfind->size, timebuf, datebuf, pkind,
- (pfind->attrib & _A_RDONLY) ? 'R' : ' ',
- (pfind->attrib & _A_HIDDEN) ? 'H' : ' ',
- (pfind->attrib & _A_SYSTEM) ? 'S' : ' ',
- (pfind->attrib & _A_ARCH) ? 'A' : ' ' );
-
- printf( "(T)ime update (R)ead only (Q)uit Any other next\n" );
- ch = getch();
- switch( toupper( ch ) )
- {
- case 'T': /* Set to current time */
- utime( pfind->name, NULL );
- break;
- case 'R': /* Toggle read only */
- if( pfind->attrib & _A_RDONLY )
- chmod( pfind->name, S_IWRITE );
- else
- chmod( pfind->name, S_IREAD );
- break;
- case 'Q': /* Quit */
- exit( 1 );
- }
- }
-
- /* Take unsigned date in the format: fedcba9876543210
- * (year is 1980 - year) yyyyyyymmmmddddd
- * Change to a 9-byte string: mm/dd/yy
- */
- char *datestr( unsigned d, char *buf )
- {
- sprintf( buf, "%2.2d/%02.2d/%02.2d",
- (d >> 5) & 0x0f, d & 0x1f, (d >> 9) + 80 );
- return buf;
- }
-
- /* Take unsigned time in the format: fedcba9876543210
- * (hours and minutes 0-based) hhhhhmmmmmmsssss
- * Change to a 9-byte string (ignore seconds): hh:mm ?m
- */
- char *timestr( unsigned t, char *buf )
- {
- int h = (t >> 11) & 0x1f, m = (t >> 5) & 0x3f;
-
- sprintf( buf, "%2.2d:%02.2d %cm", h % 12, m, h > 11 ? 'p' : 'a' );
- return buf;
- }
-
-
- TRIG.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\MATH\TRIG.C
-
- /* TRIG.C illustrates trignometric functions including:
- * cos cosh acos
- * sin sinh asin
- * tan tanh atan atan2
- */
-
- #include <math.h>
- #include <float.h>
- #include <stdio.h>
- #include <stdlib.h>
-
- main()
- {
- double x, rx, y;
-
- do
- {
- printf( "\nEnter a real number between 1 and -1: " );
- scanf( "%lf", &x );
- } while( (x > 1.0) || (x < -1.0) );
-
- printf("\nFunction\tResult for %2.2f\n\n", x );
- if( (x <= 1.0) && (x >= -1.0) )
- {
- printf( "acos\t\t%2.2f\n", acos( x ) );
- printf( "asin\t\t%2.2f\n", asin( x ) );
- }
- if( (rx = cos( x )) && (errno != ERANGE) )
- printf( "cos\t\t%2.2f\n", rx );
- else
- errno = 0;
- if( (rx = sin( x )) && (errno != ERANGE) )
- printf( "sin\t\t%2.2f\n", rx );
- else
- errno = 0;
- if( (rx = cosh( x )) && (errno != ERANGE) )
- printf( "cosh\t\t%2.2f\n", rx );
- else
- errno = 0;
- if( (rx = sinh( x )) && (errno != ERANGE) )
- printf( "sinh\t\t%2.2f\n", rx );
- else
- errno = 0;
-
- printf( "\nEnter a real number of any size: " );
- scanf( "%lf", &x );
- printf("\nFunction\tResult for %2.2f\n\n", x );
- printf( "atan\t\t%2.2f\n", atan( x ) );
- if( (rx = tan( x )) && (errno != ERANGE) )
- printf( "tan\t\t%2.2f\n", rx );
- else
- errno = 0;
- printf( "tanh\t\t%2.2f\n", tanh( x ) );
-
- printf( "\nEnter another real number of any size: " );
- scanf( "%lf", &y );
- printf("\nFunction\tResult for %2.2f and %2.2f\n\n", x, y );
- if( rx = atan2( x, y ) )
- printf( "atan2\t\t%2.2f\n", rx );
- else
- errno = 0;
- }
-
-
- TRUTH.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\TRUTH.C
-
- /* TRUTH.C: Demonstrate true and false values. */
-
- #include <stdio.h>
-
- main()
- {
- printf( "C generates %d for true\n", 2 == 2 );
- printf( "C generates %d for false\n", 2 == 4 );
- if( -33 )
- printf( "C recognizes any nonzero value as true\n" );
- }
-
-
- TYPEIT.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\FILE\TYPEIT.C
-
- /* TYPEIT.C illustrates reassigning handles and streams using functions:
- * freopen dup dup2
- *
- * The example also illustrates:
- * setargv
- *
- * To make the program handle wild cards, link it with the SETARGV.OBJ
- * file. You can do this in the QC environment by creating a program list
- * containg TYPEIT.C and SETARGV.OBJ (include the path or put in current
- * directory). You must also turn off the Extended Dictionary flag
- * within the QC environment (Options-Make-Linker Flags) or use the /NOE
- * linker option outside the environment. For example:
- * QCL typeit.c setargv /link /NOE
- */
-
- #include <stdio.h>
- #include <conio.h>
- #include <io.h>
- #include <process.h>
-
- main( int argc, char **argv )
- {
- FILE *ftmp;
- int htmp;
-
- /* Duplicate handle of stdin. Save the original to restore later. */
- htmp = dup( fileno( stdin ) );
-
- /* Process each command line argument. */
- while( *(++argv) != NULL )
- {
- /* Original stdin used for getch. */
- printf( "Press any key to display file: %s\n", *argv );
- getch();
-
- /* Reassign stdin to input file. */
- ftmp = freopen( *argv, "rb", stdin );
-
- if( (ftmp == NULL) || (htmp == -1 ) )
- {
- perror( "Can't reassign standard input" );
- exit( 1 );
- }
-
- /* Spawn MORE, which will receive the open input file as its standard
- * input. MORE can be the DOS MORE or the sample program MORE.C.
- */
- spawnvp( P_WAIT, "MORE", NULL );
-
- /* Reassign stdin back to original so that we can use the
- * original stdin to get a key.
- */
- dup2( htmp, fileno( stdin ) );
- }
- exit( 0 );
- }
-
-
- TYPES.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\TYPES.C
-
- /* TYPES.C: Illustrate basic data types. */
-
- #include <stdio.h>
-
- main()
- {
- char char_val = 'a';
- int int_val = 543;
- float float_val = 11.1;
- double double_val = 66.123456789;
- printf( "char_val = %c\n", char_val );
- printf( "int_val = %d\n", int_val );
- printf( "float_val = %f\n", float_val );
- printf( "double_val = %2.9f\n", double_val );
- }
-
-
- UNGET.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\UNGET.C
-
- /* UNGET.C illustrates getting and ungetting characters from the console.
- * Functions illustrated include:
- * getch ungetch putch
- */
-
- #include <conio.h>
- #include <stdio.h>
- #include <ctype.h>
-
- void skiptodigit( void );
- int getnum( void );
-
- main()
- {
- int c, array[10];
-
- /* Get five numbers from console. Then display them. */
- for( c = 0; c < 5; c++ )
- {
- skiptodigit();
- array[c] = getnum();
- printf( "\t" );
- }
- for( c = 0; c < 5; c++ )
- printf( "\n\r%d", array[c] );
- printf( "\n" );
- }
-
- /* Convert digit characters into a number until a non-digit is received. */
- int getnum()
- {
- int ch, num = 0;
-
- while( isdigit( ch = getch() ) )
- {
- putch( ch ); /* Display digit */
- num = (num * 10) + ch - '0'; /* Convert to number */
- }
- ungetch( ch ); /* Put non-digit back */
- return num; /* Return result */
- }
-
- /* Throw away non-digit characters. */
- void skiptodigit()
- {
- int ch;
-
- while( !isdigit( ch = getch() ) )
- ;
- ungetch( ch );
- }
-
-
- VARARG.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\VARARG.C
-
- /* VARARG.C illustrates passing a variable number of arguments using the
- * following macros:
- * va_start va_arg va_end
- * va_list va_decl (Unix only)
- */
-
- #include <stdio.h>
- ANSI /* Comment out for UNIX version */
- ANSI /* ANSI compatible version */
- #include <stdarg.h>
- int average( int first, ... );
- /* UNIX compatible version */
- #include <varargs.h>
- int average( va_list );
- #endif
-
- main()
- {
- /* Call with 3 integers. Minus -1 is used as terminator. */
- printf( "Average is: %d\n", average( 2, 3, 4, -1 ) );
-
- /* Call with 4 integers. */
- printf( "Average is: %d\n", average( 5, 7, 9, 11, -1 ) );
-
- /* Call with just -1 terminator. */
- printf( "Average is: %d\n", average( -1 ) );
- }
-
- /* Return the average of a variable list of integers. */
- ANSI /* ANSI compatible version */
- int average( int first, ... )
- {
- int count = 0, sum = 0, i = first;
- va_list marker;
-
- va_start( marker, first ); /* Initialize variable arguments */
- while( i != -1 )
- {
- sum += i;
- count++;
- i = va_arg( marker, int);
- }
- va_end( marker ); /* Reset variable arguments */
- return( sum ? (sum / count) : 0 );
- }
- /* UNIX compatible version must use old-style definition */
- int average( va_alist )
- va_dcl
- {
- int i, count, sum;
- va_list marker;
-
- va_start( marker ); /* Initialize variable arguments */
- for( sum = count = 0; (i = va_arg( marker, int)) != -1; count++ )
- sum += i;
- va_end( marker ); /* Reset variable arguments */
- return( sum ? (sum / count) : 0 );
- }
- #endif
-
-
- VISIBLE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\VISIBLE.C
-
- /* VISIBLE.C: Demonstrate visibility of variables.
- */
-
- #include <stdio.h>
- void be_bop( void );
-
- main()
- {
- int var1 = 10;
- be_bop();
- }
-
- void be_bop( void )
- {
- printf( "var1 = %d", var1 ); /* Error! */
- }
-
-
- VISIBLE1.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\VISIBLE1.C
-
- /* VISIBLE1.C: Demonstrate visibility of variables.
- */
-
- #include <stdio.h>
-
- void be_bop( int param );
-
- main()
- {
- int var1 = 10;
- be_bop( var1 );
- }
-
- void be_bop( int param )
- {
- printf( "%d\n", param );
- }
-
-
- VISIBLE2.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\VISIBLE2.C
-
- /* VISIBLE2.C: Demonstrate visibility of variables.
- */
-
- #include <stdio.h>
-
- void be_bop( int param );
-
- main()
- {
- be_bop( var1 ); /* Error! */
- }
-
- int var1 = 10;
-
- void be_bop( int param )
- {
- printf( "var1 = %d\n", param );
- }
-
-
- VOLUME.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\VOLUME.C
-
- /* VOLUME.C: Calculate sphere's volume. */
-
- #include <stdio.h>
- #define PI 3.14
-
- float sphere( int rad );
-
- main()
- {
- float volume;
- int radius = 3;
- volume = sphere( radius );
- printf( "Volume: %f\n", volume );
- }
-
- float sphere( int rad )
- {
- float result;
- result = rad * rad * rad;
- result = 4 * PI * result;
- result = result / 3;
- return result;
- }
-
-
- WHILE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\WHILE.C
-
- /* WHILE.C: Demonstrate while loop. */
-
- #include <stdio.h>
-
- main()
- {
- int test = 10;
-
- while( test > 0 )
- {
- printf( "test = %d\n", test );
- test -= 2;
- }
- }
-
-
- WINDOW.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\WINDOW.C
-
- /* WINDOW.C illustrates windows and coordinate systems, using the
- * following functions:
- * _setviewport _setvieworg _setcliprgn _setwindow
- * _rectangle _rectangle_w _rectangle_wxy _clearscreen
- * _ellipse _ellipse_w _ellipse_wxy
- *
- * Although not all illustrated here, functions ending in _w
- * are similar to _rectangle_w and _ellipse_w; functions ending
- * in _wxy are similar to _rectangle_wxy and _ellipse_wxy.
- */
-
- #include <conio.h>
- #include <graph.h>
- #include <stdlib.h>
-
- main()
- {
- short xhalf, yhalf, xquar, yquar;
- struct _wxycoord upleft, botright;
- struct videoconfig vc;
- short mode = _VRES16COLOR;
-
- while( !_setvideomode( mode ) ) /* Find best graphics mode */
- mode--;
- if( mode == _TEXTMONO )
- exit( 1 ); /* No graphics available */
- _getvideoconfig( &vc );
-
- xhalf = vc.numxpixels / 2;
- yhalf = vc.numypixels / 2;
- xquar = xhalf / 2;
- yquar = yhalf / 2;
-
- /* First window - integer physical coordinates */
- _setviewport( 0, 0, xhalf - 1, yhalf - 1 );
- _rectangle( _GBORDER, 0, 0, xhalf - 1, yhalf - 1 );
- _ellipse( _GFILLINTERIOR, xquar / 4, yquar / 4,
- xhalf - (xquar / 4), yhalf - (yquar / 4) );
- getch();
- _clearscreen( _GVIEWPORT );
- _rectangle( _GBORDER, 0, 0, xhalf - 1, yhalf - 1 );
-
- /* Second window - integer world coordinates with clip region */
- _setcliprgn( xhalf, 0, vc.numxpixels, yhalf );
- _setvieworg( xhalf + xquar - 1, yquar - 1 );
- _rectangle( _GBORDER, -xquar + 1, -yquar + 1, xquar, yquar );
- _ellipse( _GFILLINTERIOR, (-xquar * 3) / 4, (-yquar * 3) / 4,
- (xquar * 3) / 4, (yquar * 3) / 4 );
- getch();
- _clearscreen( _GVIEWPORT );
- _rectangle( _GBORDER, -xquar + 1, -yquar + 1, xquar, yquar );
-
- /* Third window */
- _setviewport( xhalf, yhalf, vc.numxpixels - 1, vc.numypixels - 1 );
- _setwindow( 0, -4.0, -5.0, 4.0, 5.0 );
- _rectangle_w( _GBORDER, -4.0, -5.0, 4.0, 5.0 );
- _ellipse_w( _GFILLINTERIOR, -3.0, -3.5, 3.0, 3.5 );
- getch();
- _clearscreen( _GVIEWPORT );
- _rectangle_w( _GBORDER, -4.0, -5.0, 4.0, 5.0 );
-
- /* Fourth window */
- _setviewport( 0, yhalf, xhalf - 1, vc.numypixels - 1 );
- _setwindow( 0, -4.0, -5.0, 4.0, 5.0 );
- upleft.wx = -4.0;
- upleft.wy = -5.0;
- botright.wx = 4.0;
- botright.wy = 5.0;
- _rectangle_wxy( _GBORDER, &upleft, &botright );
- upleft.wx = -3.0;
- upleft.wy = -3.5;
- botright.wx = 3.0;
- botright.wy = 3.5;
- _ellipse_wxy( _GFILLINTERIOR, &upleft, &botright );
-
- getch();
- exit( !_setvideomode( _DEFAULTMODE ) );
- }
-
-
- WPRINTF.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\GRAPHICS\WPRINTF.C
-
- /* WPRINTF.C shows how to use vprintf functions to write new versions
- * of printf. Functions illustrated include:
- * vsprintf vprintf vfprintf
- *
- * The vsprintf function is used in the example. The other variations
- * can be used similarly.
- */
-
- #include <stdio.h>
- #include <graph.h>
- #include <string.h>
- #include <stdarg.h>
- #include <malloc.h>
-
- int wprintf( short row, short col, short clr, long bclr, char *fmt, ... );
-
- main()
- {
- short fgd = 0;
- long bgd = 0L;
-
- _clearscreen( _GCLEARSCREEN );
- _outtext( "Color text example:\n\n" );
-
- /* Loop through 8 background colors. */
- for( bgd = 0L; bgd < 8; bgd++ )
- {
- wprintf( (int)bgd + 3, 1, 7, bgd, "Back: %d Fore:", bgd );
-
- /* Loop through 16 foreground colors. */
- for( fgd = 0; fgd < 16; fgd++ )
- wprintf( -1, -1, fgd, -1L, " %2d ", fgd );
- }
- }
-
- /* Full-screen window version of printf that takes row, column, textcolor,
- * and background color as its first arguments, followed by normal printf
- * format strings (except that \t is not handled). You can specify -1 for
- * any of the first arguments to use the current value. The function returns
- * the number of characters printed, or a negative number for errors.
- */
- int wprintf( short row, short col, short clr, long bclr, char *fmt, ... )
- {
- struct rccoord tmppos;
- short ret, size;
- va_list marker;
- char *buffer;
-
- /* It's probably safe to use a buffer 512 bytes long or five times
- * longer than the format string.
- */
- size = strlen( fmt );
- size = (size > 512) ? 512 : size * 5;
- if( (buffer = (char *)malloc( size )) == NULL )
- return -1;
-
- /* Set text position. */
- tmppos = _gettextposition();
- if( row < 1 )
- row = tmppos.row;
- if( col < 1 )
- col = tmppos.col;
- _settextposition( row, col );
-
- /* Set foreground and background colors. */
- if( clr >= 0 )
- _settextcolor( clr );
- if( bclr >= 0 )
- _setbkcolor( bclr );
-
- /* Write text to a string and output the string. */
- va_start( marker, fmt );
- ret = vsprintf( buffer, fmt, marker );
- va_end( marker );
- _outtext( buffer );
- free( buffer );
- return ret;
- }
-
-
- WRAP.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\WRAP.C
-
- /* WRAP.C illustrates:
- * _wrapon
- */
-
- #include <conio.h>
- #include <graph.h>
-
- main()
- {
- _wrapon( _GWRAPON );
- while( !kbhit() )
- _outtext( "Wrap on! " );
-
- getch();
- _clearscreen( _GCLEARSCREEN );
- _wrapon( _GWRAPOFF );
- while( !kbhit() )
- _outtext( "Wrap off!" );
- getch();
- }
-
-
- WRFILE.C
- CD-ROM Disc Path: \SAMPCODE\C\OTHER\LEARN\WRFILE.C
-
- /* WRFILE.C: Creates and writes to a disk file. */
-
- #include <stdio.h>
-
- main()
- {
- FILE *fp;
-
- if( (fp = fopen( "c:\\testfile.asc","w" )) != NULL )
- {
- fputs( "Example string", fp );
- fputc( '\n', fp );
- fclose( fp );
- }
- else
- printf( "error message\n" );
- }
- ALDE Public Domain Sample Code
-
-
- 2UP.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\UTIL\CUG236\2UP.C
-
- /*
- HEADER: CUG236;
- TITLE: Multi-Column Output Stacker;
- DATE: 05/23/87;
- DESCRIPTION: "Formats text into one or more columns. Has seve
- command line parameters that can be set.";
- KEYWORDS: Software tools, Text filters, Text formatters;
- FILENAME: 2UP.C;
- WARNINGS: "The author claims copyrights and authorizes
- non-commercial use only.";
- AUTHORS: Eugene H. Mallory, William C. Colley III;
- COMPILERS: vanilla;
- */
-
- /*********************************************************************
- * 2UP *
- **********************************************************************
- * COPYRIGHT 1983 EUGENE H. MALLORY *
- * *
- * Hacked from BDS C to portable C 23 MAY 1987 by W. C. Colley, III. *
- * This involved removing the -w option as it relies upon a non- *
- * portable direct console I/O call. In the process, I also reworked *
- * the thing into standard C puncutation and optimized various *
- * sections of code so that even a stupid compiler can make a good *
- * executable from it. *
- * *
- *********************************************************************/
-
- #include <stdio.h>
-
- #define MAXW 132
-
- /* Portability Note: 8-bit systems often don't have header file
- ctype.h. If your system doesn't have it, uncomment the #define
- NO_CTYPE_H.
-
- /*
- #define NO_CTYPE_H
- */
-
- /* Portability Note: Some older compilers don't know the new data
- type void. If yours is one of these compilers, uncomment the
- following #define:
-
- /*
- #define void int
- */
-
- #ifdef NO_CTYPE_H
- int isdigit();
- #else
- #include <ctype.h>
- #endif
-
- #ifndef TRUE
- #define TRUE 1
- #endif
-
- #ifndef FALSE
- #define FALSE 0
- #endif
-
- char string[MAXW + 2];
- char array[90][MAXW + 2];
- int ncol = 0, col = 0, len = 0, margin = 0, space = 0, width;
- int bm = 0, doneflag = FALSE, tm = 0;
- void exit();
-
- int main(argc,argv)
- int argc;
- char **argv;
- {
- int i, j, k, atoi();
- void error(), strmov();
-
- /*********************************************************************
- *** ARGUMENT PROCESSING **
- *********************************************************************/
-
- char c, *ss;
- int ii, jj, optionerr;
-
- optionerr = 0;
- for (ii = argc - 1; ii > 0; --ii)
- if (argv[ii][0] == '-') {
- for (ss = &argv[ii][1]; *ss != '\0';) {
- c = *ss++;
- switch (toupper(c)) {
- case 'L': len = atoi(ss); break;
-
- case 'C': col= atoi(ss); break;
-
- case 'M': margin = atoi(ss); break;
-
- case 'T': tm = atoi(ss); break;
-
- case 'B': bm = atoi(ss); break;
-
- case 'S': space = atoi(ss); break;
-
- case 'N': ncol= atoi(ss); break;
-
- case 'H': optionerr = TRUE; break;
-
- default: fprintf(stderr,"2UP: Illegal option %c.\n
- optionerr = TRUE; break;
- }
- while (isdigit(*ss)) ss++;
- }
- for (jj = ii; jj < (argc-1); ++jj) argv[jj] = argv[jj + 1];
- argc--;
- }
- if (optionerr) {
- fprintf(stderr,"2UP: Legal options are:\n");
- fprintf(stderr,"-Ln Page length.\n");
- fprintf(stderr,"-Cn Column width .\n");
- fprintf(stderr,"-Mn Margin.\n");
- fprintf(stderr,"-Tn Top margin.\n");
- fprintf(stderr,"-Bn Bottom margin.\n");
- fprintf(stderr,"-Sn Space between columns.\n");
- fprintf(stderr,"-Nn Number of columns.\n");
- return !0;
- }
- if (ncol == 0) ncol = 2;
- if (len == 0) len = 66;
- if (col == 0) col = (80 - margin - space * (ncol - 1)) / ncol;
- if (len > 88) error("2UP: Too long a page, 88 lines is maximum.");
- if ((margin + ncol * col + (ncol - 1) * space) > MAXW)
- error("2UP: Total width exceeds 132.");
- len = len - tm - bm;
- if (len < 1) error("2UP: Insufficient length.");
-
- /*********************************************************************
- *** END OF ARGUMENT PROCESSING
- *********************************************************************/
- /*********************************/
- /* MAIN LOOP */
- /*********************************/
- width = margin + ncol * col + (ncol - 1) * space;
- do {
- for (i = 1; i <= len; ++i)
- for (j = 1;j <= MAXW + 1; ++j) array[i][j] = ' ';
- for (k = 0; k < ncol; ++k) {
- for (i = 1; i <= len; ++i) {
- if (gets(string))
- strmov(&array[i][margin+k*col+k*space+1],string,col);
- else {
- if (!k && i == 1) return 0;
- doneflag = TRUE; goto end_of_file;
- }
- }
- }
- end_of_file:
- for (i = 1; i <= tm; ++i) puts("\n");
- for (i = 1; i <= len; ++i) {
- for (j = MAXW + 1; j; --j)
- if (array[i][j] != ' ' || j == 1) {
- array[i][j+1] = 0; break;
- }
- puts(&array[i][1]);
- }
- for (i = bm; i; --i) puts("\n");
- } while (!doneflag);
- return 0;
- }
-
- void strmov(s1,s2,n)
- char *s1,*s2;
- int n;
- {
- char c;
-
- while (n--) {
- if (!(c = *s2++) || c == '\n') break;
- *s1++ = c;
- }
- }
-
- void error(msg)
- char *msg;
- {
- fprintf(stderr,"%s\n",msg);
- exit(!0);
- }
-
-
- ABORT.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\LIB\DLIBSSRC\ABORT.C
-
- #include <stdio.h>
-
- void abort()
- /*
- * Prints the message "Abnormal program termination" to stderr and
- * calls _exit() with a status code of 3.
- */
- {
- fputs("Abnormal program termination\n", stderr);
- fflush(stderr);
- _exit(3);
- }
-
-
- ABOUT.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\ZED\ABOUT\ABOUT.C
-
- /* about.c
- *
- * Usage: about <name> [<catfile>]
- *
- * Examples: about calloc
- * about *
- * about * b:c.cat
- * about fourier b:math.dat
- *
- * Description: For each line in <catfile> beginning as ":<name>",
- * successive lines are displayed until the next line
- * begins with ":"; if <name> is *, all entries are
- * displayed; <catfile> defaults to "about.dat".
- *
- * Purpose: The file about.dat contains synopses of C functions,
- * thus making "about" an elementary "help facility".
- *
- * However, <catfile> may be any list of :<name>'s of
- * interest, with each name on a separate line, and
- * each followed by its respective text to be displayed.
- *
- * Limitations: A simple linear search is used, so probably no more
- * than a few hundred names can be handled usefully.
- *
- * Language: C (DeSmet 2.4)
- *
- * Author: R. E. Sawyer
- * 3620 Spencer St. 30, Torrance, CA 90503
- * 1 Jan 85
- */
-
- #define CATFILE "about.dat"
- #define DEFCHAR ':'
- #define BUFLEN 82
-
- int fin;
-
- main(ac, av)
- int ac;
- char *av[];
- {
- char *catfile;
- char buf[BUFLEN];
- int showall;
- int done;
- int more;
-
- showall = 0;
- done = 0;
-
- if ((ac < 2) || (ac > 3))
- {
- printf("\nUsage: about <name> [<catfile>]\n");
- printf("\nFor each line in <catfile> beginning as \":<name>\",");
- printf("\nsuccessive lines are displayed until the next line");
- printf("\nbegins with \":\"; if <name> is *, all entries are");
- printf("\ndisplayed; <catfile> defaults to \"about.dat\".\n");
- exit();
- }
- else if (ac == 2)
- {
- if ((fin = fopen(catfile = CATFILE, "r")) == 0)
- {
- printf("\n---File %s not found", catfile);
- exit();
- }
- }
- else if (ac ==3)
- {
- if ((fin = fopen(catfile = av[2], "r")) == 0)
- {
- printf("\n---File %s not found", catfile);
- exit();
- }
- }
- if (*av[1] == '*')
- showall = 1;
- printf("\n(Catalogue file: %s)\n\n", catfile);
- more = fgets(buf, BUFLEN - 1, fin);
- while (more)
- {
- if ((buf[0] == DEFCHAR)
- && ((comp(av[1], buf + 1) == 0) || showall))
- {
- more = print_text(buf);
- if (!showall)
- {
- done = 1;
- break;
- }
- }
- else
- more = fgets(buf, BUFLEN - 1, fin);
- }
- if ((done != 1) && !showall)
- printf("\"%s\" is not catalogued\n\n", av[1]);
- fclose(fin);
- }
-
- int comp(s, t)
- char *s, *t;
- {
- int i;
-
- for (i = 0; (t[i] > ' ') && (t[i] <= '~'); ++i)
- ;
- t[i] = '\0';
- return strcmp(s, t);
- }
-
- int print_text(buf)
- char buf[];
- {
- int more;
- printf("%s:\n", &buf[1]);
- while (((more = fgets(buf, BUFLEN - 1, fin)) != 0)
- && (buf[0] != DEFCHAR))
- {
- puts(buf);
- }
- return more;
- }
-
-
- ABS.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\LIB\JPLC2\ABS.C
-
- /* 1.0 07-06-84 */
- /************************************************************************
- * Robert C. Tausworthe
- * Jet Propulsion Laboratory *
- * Pasadena, CA 91009 1984
- ************************************************************************/
-
- #include "defs.h"
-
- /************************************************************************/
- int
- abs(n) /* return the integer absolute value of int n
-
- /*----------------------------------------------------------------------*/
- int n;
- {
- return ABS(n);
- }
-
-
- ABSREAD.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\LATTICE\DSKTST\ABSREAD.C
-
- #include <dos.h>
- /****************************************************************************
- *
- * absolute disk read (calls disk bios) 0x80 = 1st hard disk
- *
- *****************************************************************************
- absread(drive,cyl,head,record,count,buffer)
- int drive, cyl, head, record, count;
- char *buffer;
- {
- union REGS reg;
- struct SREGS seg;
- int err = 0;
- segread(&seg);
- reg.h.ch = (cyl & 0x00ff); /* lo order cylinder */
- reg.h.cl = (((cyl & 0xff00) << 6) | record);
- reg.h.dh = head;
- reg.h.dl = drive;
- reg.h.al = count;
- reg.h.ah = 2;
- reg.x.bx = (unsigned int) buffer; /* point to buffer */
- err = int86x(0x13,®,®,&seg); /* read the disk */
- err = (err >> 8);
- return(err);
- }
-
-
- ADD1TO2.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\UTIL\SUPER_C\ADD1TO2.C
-
- /* Example: Add 1 to 2 and Print It
- */
-
- /* main()
-
- Function: Add 1 and 2 and print the result.
-
- Algorithm: Call add to add the two numbers, and printf to print them.
- */
-
- main()
-
- {
- printf("1 + 2 = %d.\n",add(1,2));
- }
-
-
-
- ADDLF.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MSC\ADDLF.C
-
- /* addlf -- copy input to output; add line-feeds only if necessary.
- * WHRauser 10-4-83 a better mouse trap.
- */
- <stdio.h> /* Microsoft C Ver 1.04 */
-
- CR 0x000D /* carriage return */
- LF 0x000A /* line feed */
- #define TRUE 1
- #define FALSE 0
-
- main() /* copy input to output and add line-feeds only if needed.
- {
- int c;
- int addlf = FALSE;
-
- while ((c = getchar()) != EOF) {
- if (addlf & c != LF) {
- putchar(LF);
- addlf = FALSE;
- }
- putchar(c);
- if (c == CR) addlf = TRUE;
- }
- }
-
-
- ADDLF.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\UTIL\TABS\ADDLF.C
-
-
- /* addlf -- copy input to output; add line-feeds only if necessary.
- * WHRauser 10-4-83 a better mouse trap.
- */
- <stdio.h> /* Microsoft C Ver 1.04 */
-
- CR 0x000D /* carriage return */
- LF 0x000A /* line feed */
- #define TRUE 1
- #define FALSE 0
-
- main() /* copy input to output and add line-feeds only if needed. */
- {
- int c;
- int addlf = FALSE;
-
- while ((c = getchar()) != EOF) {
- if (addlf & c != LF) {
- putchar(LF);
- addlf = FALSE;
- }
- putchar(c);
- if (c == CR) addlf = TRUE;
- }
- }
-
-
-
- AGENT.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\LIB\R_LA4_01\AGENT.C
-
- /* AGENTS.C - From "Microsoft C Programming for the IBM, page */
- /* 300, by Robert Lafore. The program uses an array of struct- */
- /* ures to maintain a list of agents in memory. It is also a */
- /* continuation of the development of a simple database started */
- /* on page 292. */
- /****************************************************************/
-
- #include <stdio.h>
- #define TRUE 1
-
- struct personnel {
- char name [30];
- int agnumb;
- float height;
- };
- struct personnel agent[50]; /*array of 50 structures*/
- int n = 0;
-
- main()
- {
- char ch;
-
- while(TRUE) {
- printf("\nType 'e' to enter new agent");
- printf("\n 'L' to list all agents: ");
- ch = getche();
- switch (ch) {
- case 'e':
- newname();
- break;
- case 'L':
- listall();
- break;
- default:
- puts("\nEnter only selections listed");
- }
- }
- }
-
- /* newname */
- /* puts a new agent in the database */
- newname()
- {
- printf("\nRecord %d: \nEnter name: ", n + 1);
- gets(agent[n].name);
- printf("Enter agent number (3 digits): ");
- scanf("%d", &agent[n].agnumb);
- printf("Enter height in inches: ");
- scanf("%f", &agent[n++].height);
- fflush(stdin);
- }
-
- /* listall() */
- /* lists all agents and data */
- listall()
- {
- int j;
-
- if (n < 1)
- printf("\nEmpty list.\n");
- for(j = 0; j < n; j++) {
- printf("\nRecord number %d\n", j + 1);
- printf(" Name: %s\n", agent[j].name);
- printf(" Agent number: %03d\n", agent[j].agnumb);
- printf(" Height: %4.2f\n", agent[j].height);
- }
- }
-
-
-
- AGENT2.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\LIB\R_LA4_01\AGENT2.C
-
- /* AGENT2.C - From page 309 of "Microsoft C Programming for the */
- /* IBM by Robert Lafore. This is the final program of the data- */
- /* base started on page 292. it uses linked lists. */
- /****************************************************************/
-
- <stdio.h> /*defines 'stdin'*/
- #define TRUE 1
- struct prs {
- char name[30];
- int agnumb;
- float height;
- struct prs *ptrnext; /*ptr to next structure*/
- };
- struct prs *ptrfirst, *ptrthis, *ptrnew;
-
- main()
- {
- char ch;
-
- ptrfirst = (struct prs *)NULL; /*no input yet*/
- while (TRUE) {
- printf("\nType 'e' to enter new agent");
- printf("\n 'L' to list all agents: ");
- ch = getche();
- switch (ch) {
- case 'e':
- newname();
- break;
- case 'L':
- listall();
- break;
- default:
- puts("\nEnter only selections listed");
- }
- }
- }
-
- /* newname() */ /*puts a new agent in the database*/
- newname()
- {
- ptrnew = (struct prs *) malloc(sizeof(struct prs));
- if (ptrfirst == (struct prs *)NULL) /*if none already, save addr*/
- ptrfirst = ptrthis = ptrnew;
- else { /*not first item, go to end of list*/
- ptrthis = ptrfirst; /* (start at begin ) */
- while (ptrthis->ptrnext != (struct prs *)NULL)
- ptrthis = ptrthis->ptrnext; /*find next item*/
- ptrthis->ptrnext = ptrnew; /*pt to new item*/
- ptrthis = ptrnew; /*go to new item*/
- }
- printf("\nEnter name: ");
- gets(ptrthis->name);
- printf("Enter number: ");
- scanf("%d", &ptrthis->agnumb);
- printf("Enter height: ");
- scanf("%f", &ptrthis->height);
- fflush(stdin);
- ptrthis->ptrnext = (struct prs *)NULL; /*this is end*/
- }
-
- /* listall() */ /*lists all agents and data */
- listall()
- {
- if (ptrfirst == (struct prs *)NULL) { /*if empty list*/
- printf("\nEmpty list.\n");
- return;
- }
- ptrthis = ptrfirst; /*start at first item*/
- do {
- printf("\nName: %s\n", ptrthis->name);
- printf("Number: %03d\n", ptrthis->agnumb);
- printf("Height: %4.2f\n", ptrthis->height);
- ptrthis = ptrthis->ptrnext; /*move to next item*/
- } while(ptrthis != (struct prs *)NULL); /*quit on null ptr*/
- }
-
-
-
- AGENTR.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\LIB\R_LA4_02\AGENTR.C
-
- /* AGENTR.C - From page 453 of "Microsoft C Programming for */
- /* the IBM" by Robert Lafore. This is a simple database program.*/
- /* I added 2 if statements to file in book. One is after else */
- /* statement in rfile() function. This prevents adding exist- */
- /* ing records to array (a duplication making the array twice */
- /* as large) when selecting 'r' while an array already exists. */
- /* It will then only read a file to array at program startup. */
- /* The second if statement added is in the first case statement.*/
- /* This will prevent erasing an existing database by automat- */
- /* ically writing it to disk before selecting enter a name, */
- /* otherwise selecting enter before writing will start the new */
- /* database at n == 0 after opening the disk file. */
- /****************************************************************/
-
- #include "stdio.h"
- #define TRUE 1
-
- struct personnel { /*define data structure*/
- char name [40];
- int agnumb;
- float height;
- };
- struct personnel agent[50]; /*array of 50 structures*/
- int n = 0;
-
- main()
- {
- char ch;
-
- while(TRUE) {
- printf("\n'e' Enter new agent\n'l' List all agents");
- printf("\n'w' Write file\n'r' Read file: ");
- ch = getche();
- switch(ch) {
- case 'e':
- if (n == 0)
- rfile();
- newname();
- break;
- case 'l':
- listall();
- break;
- case 'w':
- wfile();
- break;
- case 'r':
- rfile();
- break;
- default:
- puts("\nEnter only selections listed.");
- }
- }
- }
-
- /* newname */ /* puts a new agent in the database */
- newname()
- {
-
- printf("\nRecord %d.\nEnter name: ", n + 1);
- gets(agent[n].name);
- printf("\nEnter agent number (3 digits): ");
- scanf("%d", &agent[n].agnumb);
- printf("Enter height in inches: ");
- scanf("%f", &agent[n++].height);
- fflush(stdin);
- }
-
- /* listall() */ /*lists all agents and data */
- listall()
- {
- int j;
-
- if(n < 1)
- printf("\nEmpty list.\n");
- for(j = 0; j < n; j++) {
- printf("\nRecord number %d\n", j + 1);
- printf(" Name: %s\n", agent[j].name);
- printf(" Agent number: %03d\n", agent[j].agnumb);
- printf(" Height: %4.2f\n", agent[j].height);
- }
- }
-
- /* wfile */ /* writes array of structures to file */
- wfile()
- {
- FILE *fptr;
-
- if(n < 1) {
- printf("\nCan't write empty list.\n");
- return;
- }
- if((fptr = fopen("c:agents.rec", "wb")) == NULL)
- printf("\nCan't open file agents.rec\n");
- else {
- fwrite(agent, sizeof(agent[0]), n, fptr);
- fclose(fptr);
- printf("\nFile of %d records written.\n", n);
- }
- }
-
- /* rfile() */ /* reads records from file into array */
- rfile()
- {
- FILE *fptr;
-
- if((fptr = fopen("c:agents.rec", "rb")) == NULL)
- printf("\nCan't open file agents.rec\n");
- else {
- if(n == 0) /*Fill array only at start, otherwise will dup entire file*
- while(fread(&agent[n], sizeof(agent[n]), 1, fptr) == 1)
- n++;
- fclose(fptr);
- printf("\nFile read. Total agents is %d.\n", n);
- }
- }
-
-
-
- ALLDIR.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\LATTICE\ALLDIR.C
-
- /* ALLDIR.C a program to traverse DOS's tree-structured directory, looking
- for the file(s) specified. They are then displayed on the screen.
- Basically, I got damned tired of DOS not being able to tell me what's
- where.
- The basic traverse from directory to directory portion is a
- very versatile toy around which many useful utilities can (and will,
- I'm sure!) be written. Here's another one of them. I'll do more as time
- and inclination permits, but I'll turn this one loose because I think
- it's useful.
- This is written for MSDOS 2.0 or better, using the LATTICE C Compiler,
- on a Compaq. 7-20-84 jjw
- ps I know this could be shortened drastically and speeded up by
- combining some of the modules into larger functions, but this way was
- much easier to write & de-bug modularly and so I left it that way. Also,
- some of the modules might be useful in themselves to build into a
- library. This program differs from most C code I've seen before because
- 1.) it does something useful.
- 2.) it does not have pointers to pointers to arrays of pointers to functio
- returning pointers. It is easy and straight-forward, at the expense of
- some speed and length.
- 3.) it is commented. Not extensively, but fairly well. The hard parts have
- to do with the dirstak, which is not a stack but a queue (dirqueue
- looked too silly to me and d_queue made me think of peanut buster
- parfaits). If puzzled, follow it through but keep the msdos manual
- handy to see what byte is what.
- If you have any questions about this, drop me a note. I frequent almost
- every tech-oriented CPM bulletin board around Chicago, Il.
- Name is John Welch, or just jjw.
- 2397 John Smith Dr. Apt B
- Schaumburg, Il 60194 */
-
- #include "dos.h"
- #include "stdio.h"
-
- main(argc,argv)
- int argc;
- char *argv[];
- {
- char look[15],start[100],init_dir[100],drive[2],flag1,stuff[100];
- int first,last,temp,temp1,ret;
-
- printf("ALLDIR.C Ver 1.00 1-25-85 John J. Welch\n");
- printf("(for help, type ALLDIR HELP)\n\n");
-
- if (argc == 1)
- {
- /* get the filename to erase */
- printf("Filename to find -->");
- scanf("%s",look);
-
- /* get the drive we're going to do the erasing on */
- printf("Enter the drive letter -->");
- scanf("%s",stuff);
- drive[1] = stuff[0];
-
- /* get starting directory */
- printf("Directory to start in (absolute path from root) -->");
- scanf("%s",start);
-
- /* do we want to do all sub-directories, too, or just this one? */
- printf("Traverse all sub-directories under this one -->");
- scanf("%s",stuff);
- if ((stuff[0] == 'y') || (stuff[0] == 'Y'))
- flag1 = 1; /* if they specified Y, set the flag */
- else
- flag1 = 0; /* anything but Y or y means NO */
-
- }
- else
- {
- if (argc != 2)
- {
- HERE:
- printf("For prompts, just type ALLDIR.\n");
- printf("Command line syntax is ALLDIR [drive:][starting path]file.ext[/y]
- printf("where [drive:] is optional drive,\n");
- printf(" [starting path] is optional path to start at,\n");
- printf(" file.ext is the file name (wildcards ok) to look for,\n");
- printf(" [/y] is optionally if you want to do all sub-directories under
- printf(" starting directory (default value is no).\n");
- return;
- }
- else
- {
- if ((strcmp(argv[1],"HELP") == 0) || (strcmp(argv[1],"help") == 0))
- goto HERE;
-
- first = 0; /* first character of the command line */
- drive[1] = 255; /* set up to default to current drive */
- flag1 = 0; /* default it to not do sub-dirs */
- if (argv[1][1] == ':') /* if there was a drive specified, pick the letter
- { /*off and store it someplace */
- drive[1] = argv[1][0];
- first = 2; /* now, the first character in the command line is #2 */
- }
- last = strlen(argv[1]); /* get the length of the command line */
- if (argv[1][last-2] == '/') /* if they used the toggle, set it up */
- {
- if ((argv[1][last-1] == 'y') || (argv[1][last-1] == 'Y'))
- flag1 = 1; /* if they specified Y, set the flag */
- else
- flag1 = 0; /* anything but Y or y means NO */
- last -= 2; /* bump the last character down */
- argv[1][last] = 0; /* and now, null terminate the command line */
- }
-
- for (temp = last; ((argv[1][temp] != ':') && (temp >= first) && (argv[1][
-
- for (temp1 = first; temp1 < temp+1; temp1++) /* get pathname (if any) */
- {start[temp1-first] = argv[1][temp1];}
- start[temp1-first] = 0; /* null terminate it */
-
- for (temp1 = temp+1; temp1 <= last; temp1++) /* get the filename to look
- {look[temp1-(temp+1)] = argv[1][temp1];}
- look[temp1-(temp+1)] = 0; /* null terminate this */
-
- }
- }
-
- /* get the drive we started in */
- get_drive(drive);
-
- if (drive[1] == 255) /* if the default was for current drive, use it */
- drive[1] = drive[0];
- else /* otherwise, normalize whatever they typed in to start with a=0 */
- if ((drive[1] > 'A') && (drive[1] < 'Z'))
- drive[1] = drive[1] - 'A';
- else
- drive[1] = drive[1] - 'a';
-
- /* change to the starting drive */
- ret=chg_drive(drive[1]);
-
- if (ret < drive[1])
- printf("invalid drive selected...\n");
- else
- {
- /* get the directory we started in */
- init_dir[0] = '\\';
- get_dir(init_dir+1);
-
- if (start[0] == 0) /* if there was no starting path, use the current one */
- strcpy(start,init_dir);
-
- /* do the actual work */
- doit(look,start,flag1);
-
- /* change back to the initial drive */
- chg_drive(drive[0]);
-
- /* now, change back to the initial directory */
- chg_dir(init_dir);
- } /* end else */
-
- } /* end function */
-
- doit(look,start,flag1)
- char *look,*start,flag1;
-
- {
- char file[3],name[128],*dirstak,curdir[140],*getmem();
- int ret,tmp,top_ndx,bottom_ndx;
-
- dirstak = getmem(10000); /* get a hunk of memory for the directory queue */
- if (dirstak == 0) /* if the getmem returned a null, error */
- {printf("not enough memory...\n");
- return;}
-
- /* set the DTA to someplace we can use */
- put_dta(name);
-
- top_ndx = 0; /* set pointer to top of directory queue */
- bottom_ndx = 0; /* set pointer to bottom of queue */
-
- /* put the starting directory in the queue */
- for (tmp = 0; start[tmp] != 0; tmp++)
- {dirstak[bottom_ndx++] = start[tmp];}
- dirstak[bottom_ndx++] = 0;
-
- while (top_ndx != bottom_ndx)
- {
- /* check for any sub-directories */
- ret = dirscan(file,name,curdir,dirstak,&top_ndx,&bottom_ndx);
-
- if (ret != 3)
- {
- /* run through the directory, querying for each file */
- filscan(look,name);
- }
-
- /* if only do this one directory, end here */
- if (flag1 == 0)
- {
- rlsmem(dirstak,10000);
- return(1);
- }
-
- } /* end while loop */
- rlsmem(dirstak,10000);
-
- } /* end function */
-
- dirscan(file,name,curdir,dirstak,top_ptr,bot_ptr)
- char *file,*name,*curdir,*dirstak;
- int *top_ptr,*bot_ptr;
- {
- int ret,tmp,top_ndx,bottom_ndx,*p_file;
-
- bottom_ndx = *bot_ptr;
- top_ndx = *top_ptr;
-
- /* initialize the file name for the directory search */
- file[0] = '*';
- file[1] = '.';
- file[2] = 0;
-
- tmp = 0;
- for (top_ndx; dirstak[top_ndx] != 0; top_ndx++)
- { curdir[tmp++] = dirstak[top_ndx];}
- curdir[tmp] = 0;
- ++top_ndx;
- ret = chg_dir(curdir);
- if (ret != 3)
- {
- printf("\n\n %s\n",curdir);
- find_dir(name,file,curdir,dirstak,&bottom_ndx);
- }
- *bot_ptr = bottom_ndx;
- *top_ptr = top_ndx;
-
- return(ret);
- }
-
- find_dir(name,file,curdir,dirstak,bot_ndx)
- char *name,*file,*curdir,*dirstak;
- int *bot_ndx;
- {
- int ret,tmp,bottom_ndx;
- unsigned temp;
-
- bottom_ndx = *bot_ndx; /* set the local variable = the real thing. */
-
- /* search for first directory entry */
- temp = 0x0010;
- ret = srch1st(file,temp);
-
- /* while the return from search is successful, check for dir attribute
- and make sure it isn't a . or .. entry, put the whole pathname (null
- terminated) at the bottom of the queue */
-
- while (ret != 18)
- { if ((name[21] == 0x10) && (name[30] != '.'))
- {
- for (tmp = 0; curdir[tmp] != 0; tmp++)
- {dirstak[bottom_ndx] = curdir[tmp];
- ++bottom_ndx;}
- if (curdir[1] != 0)
- {dirstak[bottom_ndx++] = '\\';}
- for (tmp = 30; name[tmp] != 0; tmp++)
- {dirstak[bottom_ndx] = name[tmp];
- ++bottom_ndx;}
- dirstak[bottom_ndx++] = 0;
-
- } /* end if */
- ret = srchnext(file); /* get another directory entry */
- } /* end while */
-
- *bot_ndx = bottom_ndx; /*now restore the real value to its proper place */
-
- } /* end function */
-
- filscan(look,name)
- char *look,*name;
- {
- int ret,numb;
- char tmp,line[35],flag;
- unsigned temp;
- long make_line(),total;
-
- total = 0;
- numb = 0;
- flag = 0;
- temp = 0x0000;
- ret = srch1st(look,temp); /* start looking for files */
-
- while (ret != 18)
- {
- total += make_line(line,name);
- numb++;
- printf(line);
- if (flag == 0)
- {printf(" ");
- flag = 1;}
- else
- {printf("\n");
- flag = 0;}
-
- ret = srchnext(look); /* get another directory entry */
- } /* end while */
- if (flag == 1)
- printf("\n");
- printf(" --> %d files, total space = %8lu<--\n",numb,total);
-
- } /* end function */
-
- put_dta(p_dta)
- char *p_dta;
- {
- union REGS inreg;
- union REGS outreg;
-
- inreg.h.ah = 0x1a;
- inreg.x.dx = p_dta;
-
- intdos(&inreg,&outreg);
-
- return(0);
- }
-
- srch1st(p_file,attr)
- int *p_file;
- unsigned attr;
- {
- union REGS inreg;
- union REGS outreg;
-
- inreg.h.ah = 0x4e;
- inreg.x.cx = attr;
- inreg.x.dx = p_file;
-
- intdos(&inreg,&outreg);
-
- return(outreg.x.ax);
- }
-
- srchnext(p_file)
- int *p_file;
- {
- union REGS inreg;
- union REGS outreg;
-
- inreg.h.ah = 0x4f;
-
- intdos(&inreg,&outreg);
-
- return(outreg.x.ax);
- }
-
- chg_dir(curdir)
- char *curdir;
- {
- union REGS inreg;
- union REGS outreg;
-
- inreg.h.ah = 0x3b;
- inreg.x.dx = curdir;
-
- intdos(&inreg,&outreg);
-
- return(outreg.x.ax);
- }
-
- get_dir(temp)
- char *temp;
- {
- union REGS inreg;
- union REGS outreg;
-
- inreg.h.ah = 0x47;
- inreg.h.dl = 0; /* relative drive */
- inreg.x.si = temp; /* where to put the pathname */
-
- intdos(&inreg,&outreg);
-
- return(outreg.x.ax);
- }
-
- get_drive(where)
- char *where;
- {
- union REGS inreg;
- union REGS outreg;
-
- inreg.h.ah = 0x19;
-
- intdos(&inreg,&outreg);
-
- *where = outreg.h.al;
- }
-
- era_file(which)
- char *which;
- {
- union REGS inreg;
- union REGS outreg;
-
- inreg.h.ah = 0x41;
- inreg.x.dx = which; /* pointer to filename */
-
- intdos(&inreg,&outreg);
-
- /* there's no easy way to check for errors, so don't even do it.
- dos returns error flag in carry flag, LATTICE C can't access it without
- your own assembler routine. I have one, but it's a bit hairy. For those
- who insist on doing things right, drop me a note. jjw */
- }
-
- chg_drive(drive)
- char drive;
- {
- union REGS inreg;
- union REGS outreg;
-
- inreg.h.ah = 0x0e;
- inreg.h.dl = drive;
-
- intdos(&inreg,&outreg);
-
- return(outreg.h.al);
- }
-
-
- /************************************************************************/
- /* make_line() */
- /* make the line of directory info to be printed */
- /* */
- /************************************************************************/
-
- long make_line(dst,nam)
- char *dst,*nam;
- {
- unsigned g1,g2,g3; /* garbage variables */
- char flag,temp; /* flagged or not, temporary counter */
- char name[9],ext[5],*where; /* hold the file name & extension, which place t
- int ret; /* true if we are did not go off the bottom of the dir */
- long size,g7,t1,t2,t3; /* size of file in bytes, temp variables */
- char direct[23];
-
- t1 = 256; /* offset for high size low */
- t2 = 65536; /* offset for low size high */
- t3 = 16777216; /* offset for high size high */
-
- for (temp = 24; temp != 43; temp++) /* load the date, size and name */
- { direct[temp-21] = nam[temp]; /* put the char into the dir area */ }
-
- for (temp = 0; temp != 6; temp++) /* blank out the extension */
- { ext[temp] = 0; }
-
- for (temp = 0; temp != 10; temp++) /* blank out the file name */
- { name[temp] = 0; }
-
- where = name; /* start by putting the name in the name */
-
- for (temp = 0; temp <= 12; temp++) /* copy over the file name */
- { if (direct[9+temp] == '.') /* if we hit the seperator between name & ext,
- {
- where = ext; /*switch over to the extension */
- temp++; /* skip to next character */
- }
- if (direct[9+temp] == 0) /* if we're at the end of the string, stop */
- temp = 13; /* exit condition */
- else
- {
- *where = direct[9+temp]; /* copy the char over to the array */
- where++; /* increment pointer */
- }
- }
-
- g1 = direct[4]; /* will be the year */
- g2 = direct[4]*256+direct[3]; /* will be the month */
- g3 = direct[3]; /* will be the day */
-
- g7 = direct[5]; /* compute size in bytes */
- size = g7;
- g7 = direct[6];
- size = size + (g7*t1);
- g7 = direct[7];
- size = size + (g7*t2);
- g7 = direct[8];
- size = size + (g7*t3); /* will be the file size in bytes */
-
- /* shift things around to get rid of un-necessary bits */
- g1 >>= 1; /* right-shift month by 1 */
- g2 <<= 7; /* left-shift day by 7 */
- g2 >>= 12; /* then right-shift by 12 to drop off garbage bits */
- g3 &= 0x1f; /* mask off garbage bits to get the year */
-
- sprintf(dst,"%-8s.%-3s %02d-%02d-%02d %8lu",name,ext,g2,g3,g1+80,size);
- /* make a useful string out of the flag, name, date and size */
-
- return(size);
- }
-
-
- ALLOC.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\ZED\STEVIE\ALLOC.C
-
- /*
- * STevie - ST editor for VI enthusiasts. ...Tim Thompson...twitch!tjt...
- *
- * Extensive modifications by: Tony Andrews onecom!wldrdg!tony
- * Turbo C 1.5 port by: Denny Muscatelli 061988
- */
-
- #include "stevie.h"
-
- /*
- * This file contains various routines dealing with allocation and
- * deallocation of data structures.
- */
-
- char *
- alloc(size)
- unsigned size;
- {
- char *p; /* pointer to new storage space */
-
- p = malloc(size);
- if ( p == (char *)NULL ) { /* if there is no more room... */
- emsg("alloc() is unable to find memory!");
- }
- return(p);
- }
-
- char *
- strsave(string)
- char *string;
- {
- return(strcpy(alloc((unsigned)(strlen(string)+1)),string));
- }
-
- void
- screenalloc()
- {
- /*
- * If we're changing the size of the screen, free the old arrays
- */
- if (Realscreen != NULL)
- free(Realscreen);
- if (Nextscreen != NULL)
- free(Nextscreen);
-
- Realscreen = malloc((unsigned)(Rows*Columns));
- Nextscreen = malloc((unsigned)(Rows*Columns));
- }
-
- /*
- * Allocate and initialize a new line structure with room for
- * 'nchars' characters.
- */
- LINE *
- newline(nchars)
- int nchars;
- {
- register LINE *l;
-
- if ((l = (LINE *) alloc(sizeof(LINE))) == NULL)
- return (LINE *) NULL;
-
- l->s = alloc(nchars); /* the line is empty */
- l->s[0] = NUL;
- l->size = nchars;
-
- l->prev = (LINE *) NULL; /* should be initialized by caller */
- l->next = (LINE *) NULL;
-
- return l;
- }
-
- /*
- * filealloc() - construct an initial empty file buffer
- */
- void
- filealloc()
- {
- if ((Filemem->linep = newline(1)) == NULL) {
- fprintf(stderr,"Unable to allocate file memory!\n");
- exit(1);
- }
- if ((Fileend->linep = newline(1)) == NULL) {
- fprintf(stderr,"Unable to allocate file memory!\n");
- exit(1);
- }
- Filemem->index = 0;
- Fileend->index = 0;
-
- Filemem->linep->next = Fileend->linep;
- Fileend->linep->prev = Filemem->linep;
-
- *Curschar = *Filemem;
- *Topchar = *Filemem;
-
- Filemem->linep->num = 0;
- Fileend->linep->num = 0xffff;
-
- clrall(); /* clear all marks */
- }
-
- /*
- * freeall() - free the current buffer
- *
- * Free all lines in the current buffer.
- */
- void
- freeall()
- {
- LINE *lp, *xlp;
-
- for (lp = Filemem->linep; lp != NULL ;lp = xlp) {
- if (lp->s != NULL)
- free(lp->s);
- xlp = lp->next;
- free(lp);
- }
-
- Curschar->linep = NULL; /* clear pointers */
- Filemem->linep = NULL;
- Fileend->linep = NULL;
- }
-
- /*
- * bufempty() - return TRUE if the buffer is empty
- */
- bool_t
- bufempty()
- {
- return (buf1line() && Filemem->linep->s[0] == NUL);
- }
-
- /*
- * buf1line() - return TRUE if there is only one line
- */
- bool_t
- buf1line()
- {
- return (Filemem->linep->next == Fileend->linep);
- }
-
- /*
- * lineempty() - return TRUE if the current line is empty
- */
- bool_t
- lineempty()
- {
- return (Curschar->linep->s[0] == NUL);
- }
-
- /*
- * endofline() - return TRUE if the given position is at end of line
- *
- * This routine will probably never be called with a position resting
- * on the NUL byte, but handle it correctly in case it happens.
- */
- bool_t
- endofline(p)
- register LPTR *p;
- {
- return (p->linep->s[p->index] == NUL || p->linep->s[p->index+1] == NU
- }
- /*
- * canincrease(n) - returns TRUE if the current line can be increased 'n' byt
- *
- * This routine returns immediately if the requested space is available.
- * If not, it attempts to allocate the space and adjust the data structures
- * accordingly. If everything fails it returns FALSE.
- */
- bool_t
- canincrease(n)
- register int n;
- {
- register int nsize;
- register char *s; /* pointer to new space */
-
- nsize = strlen(Curschar->linep->s) + 1 + n; /* size required *
-
- if (nsize <= Curschar->linep->size)
- return TRUE;
-
- /*
- * Need to allocate more space for the string. Allow some extra
- * space on the assumption that we may need it soon. This avoids
- * excessive numbers of calls to malloc while entering new text.
- */
- if ((s = alloc(nsize + SLOP)) == NULL) {
- emsg("Can't add anything, file is too big!");
- State = NORMAL;
- return FALSE;
- }
-
- Curschar->linep->size = nsize + SLOP;
- strcpy(s, Curschar->linep->s);
- free(Curschar->linep->s);
- Curschar->linep->s = s;
-
- return TRUE;
- }
-
-
- ALLOT.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\LIB\JPLC2\ALLOT.C
-
- /* 1.3 02-11-86 (allot.c)
- ************************************************************************
- * Robert C. Tausworthe
- * Jet Propulsion Laboratory *
- * Pasadena, CA 91009 1985, 86 *
- ************************************************************************/
-
- #include "defs.h"
- #include "stdtyp.h"
-
- /*----------------------------------------------------------------------*/
-
- LOCAL HEADER base; /* empty list to get started.
- LOCAL HEADER *allocp = NULL; /* last allocated block. *
-
- /************************************************************************/
- char *
- allot(nbytes) /* Return pointer to block of memory nbytes in
- size, or NULL if none available. */
- /*----------------------------------------------------------------------*/
- unsigned nbytes;
- {
- HEADER *morecore(); /* Almost straight out of K & R. */
- FAST HEADER *p, *q;
- FAST unsigned ru, au; /* requested units, allotted units.
- unsigned n_units();
-
- if ((q = allocp) IS NULL)
- { base.s.ptr = allocp = q = &base;
- base.s.size = 0;
- }
- ru = n_units(nbytes); /* convert to units */
- for (p = q->s.ptr; ; q = p, p = p->s.ptr)
- { if (p->s.size >= nbytes)
- { if ((au = n_units(p->s.size)) > ru)
- { p->s.size = (au -= ru) * sizeof(HEADER);
- p += au;
- }
- else /* allot the whole block.
- q->s.ptr = p->s.ptr;
- allocp = q;
- return (char *) p;
- }
- if ((p IS allocp) AND NOT(p = morecore(ru)))
- return NULL; /* wrapped around free list and
- no memory left.
- }
- }
- /*\p*********************************************************************/
- VOID
- liberate(ap, nbytes) /* Put block of nbytes pointed to by ap into the
- available list. */
- /*----------------------------------------------------------------------*/
- char *ap;
- unsigned nbytes;
- {
- FAST HEADER *p, *q;
- unsigned n_units();
-
- if (NOT p)
- return;
-
- p = (HEADER *) ap; /* point to header *
- for (q = allocp; NOT(q < p AND p < q->s.ptr); q = q->s.ptr)
- if (q >= q->s.ptr AND (q < p OR p < q->s.ptr))
- break; /* stop if at one end or another
-
- p->s.size = nbytes; /* record the size
- if ((p + n_units(p->s.size)) IS q->s.ptr /* join to upper nghbor?*/
- AND (nbytes % sizeof(HEADER)) IS 0) /* only if no holes.
- { p->s.size += q->s.ptr->s.size;
- p->s.ptr = q->s.ptr->s.ptr;
- }
- else
- p->s.ptr = q->s.ptr;
- if (q + n_units(q->s.size) IS p) /* join to lower nbr? */
- { q->s.size += p->s.size;
- q->s.ptr = p->s.ptr;
- }
- else
- q->s.ptr = p;
- allocp = q;
- }
- /*\p*********************************************************************/
- LOCAL HEADER *
- morecore(nu) /* ask system for nu blocks of memory and put on
- the available list. Return ptr to the block. */
- /*----------------------------------------------------------------------*/
- unsigned nu;
- {
- char *sbrk();
- FAST char *cp;
- FAST HEADER *up;
- FAST unsigned rnu;
-
- rnu = NALLOC * ((nu + NALLOC - 1) / NALLOC);
- cp = sbrk(nu = rnu * sizeof(HEADER)); /* nu now no. of bytes
- if ((int) cp IS EOF) /* no space at all
- return NULL;
-
- up = (HEADER *) cp;
- liberate((char *) up, nu);
- return allocp;
- }
-
- /************************************************************************/
- unsigned
- n_units(n) /* return the number of HEADER-sized units
- required to cover n bytes.
- /*----------------------------------------------------------------------*/
- unsigned n;
- {
- return (n + sizeof(HEADER) - 1) / sizeof(HEADER);
- }
-
-
- ANAGRAM.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\LIB\R_LA4_02\ANAGRAM.C
-
- /* ANAGRAM.C - From page 584 of "Microsoft C Programming for */
- /* the IBM" by Robert Lafore. Creates all possible letter ar- */
- /* rangements in a given word. The version in the book doesn't */
- /* work correctly. The line I changed is marked in the comments */
- /* in the source code. The printf() was added because in the */
- /* recursive function rotate is called before the original */
- /* word is printed. */
- /****************************************************************/
-
- char word[40];
- int length;
- main()
- {
-
- printf("\n\nType word: ");
- gets(word);
- length = strlen(word);
- printf("%s\n", word); /*** ADDED TO SOURCE ***/
- permute(0);
- }
-
- /* permute */ /* prints all permutations of word */
- /* word begins at position startperm */
- permute(startperm)
- int startperm;
- {
- int j;
-
- if(length - startperm < 2) /* exit if one char */
- return;
- for(j = startperm; j < length - 1; j++) { /*# chars in word-1*/
- permute(startperm + 1); /*permutes all but first*/
- rotate(startperm); /*rotate all chars*/
- printf("%s\n", word);
- }
- permute(startperm + 1); /*restore word to*/
- rotate(startperm); /*form at entry*/
- }
-
- /* rotate() */ /*rotates word one char left*/
- /*word begins at char pos startrot*/
- rotate(startrot)
- int startrot;
- {
- int j;
- char ch;
-
- ch = word[startrot]; /*save first char*/
- for(j = startrot; j < length - 1; j++) /*move other chars left*/
- word[j] = word[j + 1]; /* one position */
- word[length - 1] = ch;
- }
-
-
-
- ANALYZE.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\UTIL\CC68\ANALYZE.C
-
- #include <stdio.h>
- #include "c.h"
- #include "expr.h"
- #include "gen.h"
- #include "cglbdec.h"
-
- /*
- * 68000 C compiler
- *
- * Copyright 1984, 1985, 1986 Matthew Brandt.
- * all commercial rights reserved.
- *
- * This compiler is intended as an instructive tool for personal use.
- * use for profit without the written consent of the author is prohibi
- *
- * This compiler may be distributed freely for non-commercial use as l
- * as this notice stays intact. Please forward any enhancements or que
- * to:
- *
- * Matthew Brandt
- * Box 920337
- * Norcross, Ga 30092
- */
-
- extern struct amode push[], pop[];
-
- /*
- * this module will step through the parse tree and find all
- * optimizable expressions. at present these expressions are
- * limited to expressions that are valid throughout the scope
- * of the function. the list of optimizable expressions is:
- *
- * constants
- * global and static addresses
- * auto addresses
- * contents of auto addresses.
- *
- * contents of auto addresses are valid only if the address is
- * never referred to without dereferencing.
- *
- * scan will build a list of optimizable expressions which
- * opt1 will replace during the second optimization pass.
- */
-
- static struct cse *olist; /* list of optimizable expressions */
-
- equalnode(node1, node2)
- /*
- * equalnode will return 1 if the expressions pointed to by
- * node1 and node2 are equivalent.
- */
- struct enode *node1, *node2;
- { if( node1 == 0 || node2 == 0 )
- return 0;
- if( node1->nodetype != node2->nodetype )
- return 0;
- if( (node1->nodetype == en_icon || node1->nodetype == en_labcon ||
- node1->nodetype == en_nacon || node1->nodetype == en_autocon) &&
- node1->v.i == node2->v.i )
- return 1;
- if( lvalue(node1) && equalnode(node1->v.p[0], node2->v.p[0]) )
- return 1;
- return 0;
- }
-
- struct cse *searchnode(node)
- /*
- * searchnode will search the common expression table for an entry
- * that matches the node passed and return a pointer to it.
- */
- struct enode *node;
- { struct cse *csp;
- csp = olist;
- while( csp != 0 ) {
- if( equalnode(node,csp->exp) )
- return csp;
- csp = csp->next;
- }
- return 0;
- }
-
- struct enode *copynode(node)
- /*
- * copy the node passed into a new enode so it wont get
- * corrupted during substitution.
- */
- struct enode *node;
- { struct enode *temp;
- if( node == 0 )
- return 0;
- temp = xalloc(sizeof(struct enode));
- temp->nodetype = node->nodetype;
- temp->v.p[0] = node->v.p[0];
- temp->v.p[1] = node->v.p[1];
- return temp;
- }
-
- enternode(node,duse)
- /*
- * enternode will enter a reference to an expression node into the
- * common expression table. duse is a flag indicating whether or not
- * this reference will be dereferenced.
- */
- struct enode *node;
- int duse;
- { struct cse *csp;
- if( (csp = searchnode(node)) == 0 ) { /* add to tree */
- csp = xalloc(sizeof(struct cse));
- csp->next = olist;
- csp->uses = 1;
- csp->duses = (duse != 0);
- csp->exp = copynode(node);
- csp->voidf = 0;
- olist = csp;
- return csp;
- }
- ++(csp->uses);
- if( duse )
- ++(csp->duses);
- return csp;
- }
-
- struct cse *voidauto(node)
- /*
- * voidauto will void an auto dereference node which points to
- * the same auto constant as node.
- */
- struct enode *node;
- { struct cse *csp;
- csp = olist;
- while( csp != 0 ) {
- if( lvalue(csp->exp) && equalnode(node,csp->exp->v.p[0]) ) {
- if( csp->voidf )
- return 0;
- csp->voidf = 1;
- return csp;
- }
- csp = csp->next;
- }
- return 0;
- }
-
- scanexpr(node,duse)
- /*
- * scanexpr will scan the expression pointed to by node for optimizable
- * subexpressions. when an optimizable expression is found it is entered
- * into the tree. if a reference to an autocon node is scanned the
- * corresponding auto dereferenced node will be voided. duse should be
- * set if the expression will be dereferenced.
- */
- struct enode *node;
- { struct cse *csp, *csp1;
- int n;
- if( node == 0 )
- return;
- switch( node->nodetype ) {
- case en_icon:
- case en_labcon:
- case en_nacon:
- enternode(node,duse);
- break;
- case en_autocon:
- if( (csp = voidauto(node)) != 0 ) {
- csp1 = enternode(node,duse);
- csp1->uses = (csp1->duses += csp->uses);
- }
- else
- enternode(node,duse);
- break;
- case en_b_ref:
- case en_w_ref:
- case en_l_ref:
- if( node->v.p[0]->nodetype == en_autocon ) {
- csp = enternode(node,duse);
- if( csp->voidf )
- scanexpr(node->v.p[0],1);
- }
- else
- scanexpr(node->v.p[0],1);
- break;
- case en_cbl: case en_cwl:
- case en_cbw: case en_uminus:
- case en_compl: case en_ainc:
- case en_adec: case en_not:
- scanexpr(node->v.p[0],duse);
- break;
- case en_asadd: case en_assub:
- case en_add: case en_sub:
- scanexpr(node->v.p[0],duse);
- scanexpr(node->v.p[1],duse);
- break;
- case en_mul: case en_div:
- case en_lsh: case en_rsh:
- case en_mod: case en_and:
- case en_or: case en_xor:
- case en_lor: case en_land:
- case en_eq: case en_ne:
- case en_gt: case en_ge:
- case en_lt: case en_le:
- case en_asmul: case en_asdiv:
- case en_asmod: case en_aslsh:
- case en_asrsh: case en_asand:
- case en_asor: case en_cond:
- case en_void: case en_assign:
- scanexpr(node->v.p[0],0);
- scanexpr(node->v.p[1],0);
- break;
- case en_fcall:
- scanexpr(node->v.p[0],1);
- scanexpr(node->v.p[1],0);
- break;
- }
- }
-
- scan(block)
- /*
- * scan will gather all optimizable expressions into the expression
- * list for a block of statements.
- */
- struct snode *block;
- { while( block != 0 ) {
- switch( block->stype ) {
- case st_return:
- case st_expr:
- opt4(&block->exp);
- scanexpr(block->exp,0);
- break;
- case st_while:
- case st_do:
- opt4(&block->exp);
- scanexpr(block->exp,0);
- scan(block->s1);
- break;
- case st_for:
- opt4(&block->label);
- scanexpr(block->label,0);
- opt4(&block->exp);
- scanexpr(block->exp,0);
- scan(block->s1);
- opt4(&block->s2);
- scanexpr(block->s2,0);
- break;
- case st_if:
- opt4(&block->exp);
- scanexpr(block->exp,0);
- scan(block->s1);
- scan(block->s2);
- break;
- case st_switch:
- opt4(&block->exp);
- scanexpr(block->exp,0);
- scan(block->s1);
- break;
- case st_case:
- scan(block->s1);
- break;
- }
- block = block->next;
- }
- }
-
- exchange(c1)
- /*
- * exchange will exchange the order of two expression entries
- * following c1 in the linked list.
- */
- struct cse **c1;
- { struct cse *csp1, *csp2;
- csp1 = *c1;
- csp2 = csp1->next;
- csp1->next = csp2->next;
- csp2->next = csp1;
- *c1 = csp2;
- }
-
- int desire(csp)
- /*
- * returns the desirability of optimization for a subexpression.
- */
- struct cse *csp;
- { if( csp->voidf || (csp->exp->nodetype == en_icon &&
- csp->exp->v.i < 16 && csp->exp->v.i >= 0))
- return 0;
- if( lvalue(csp->exp) )
- return 2 * csp->uses;
- return csp->uses;
- }
-
- int bsort(list)
- /*
- * bsort implements a bubble sort on the expression list.
- */
- struct cse **list;
- { struct cse *csp1, *csp2;
- int i;
- csp1 = *list;
- if( csp1 == 0 || csp1->next == 0 )
- return 0;
- i = bsort( &(csp1->next));
- csp2 = csp1->next;
- if( desire(csp1) < desire(csp2) ) {
- exchange(list);
- return 1;
- }
- return 0;
- }
-
- allocate()
- /*
- * allocate will allocate registers for the expressions that have
- * a high enough desirability.
- */
- { struct cse *csp;
- struct enode *exptr;
- int datareg, addreg, mask, rmask, i;
- struct amode *ap, *ap2;
- datareg = 3;
- addreg = 10;
- mask = 0;
- rmask = 0;
- while( bsort(&olist) ); /* sort the expression list */
- csp = olist;
- while( csp != 0 ) {
- if( desire(csp) < 3 )
- csp->reg = -1;
- else if( csp->duses > csp->uses / 4 && addreg < 14 )
- csp->reg = addreg++;
- else if( datareg < 8 )
- csp->reg = datareg++;
- else
- csp->reg = -1;
- if( csp->reg != -1 )
- {
- rmask = rmask | (1 << (15 - c
- mask = mask | (1 << csp->reg);
- }
- csp = csp->next;
- }
- if( mask != 0 )
- gen_code(op_movem,4,make_mask(rmask),push);
- save_mask = mask;
- csp = olist;
- while( csp != 0 ) {
- if( csp->reg != -1 )
- { /* see if preload needed */
- exptr = csp->exp;
- if( !lvalue(exptr) || (exptr->v.p[0]->v.i > 0) )
- {
- initstack();
- ap = gen_expr(exptr,F_ALL,4);
- if( csp->reg < 8 )
- ap2 = makedreg(csp->reg);
- else
- ap2 = makeareg(csp->reg - 8);
- gen_code(op_move,4,ap,ap2);
- freeop(ap);
- }
- }
- csp = csp->next;
- }
- }
-
- repexpr(node)
- /*
- * repexpr will replace all allocated references within an expression
- * with tempref nodes.
- */
- struct enode *node;
- { struct cse *csp;
- if( node == 0 )
- return;
- switch( node->nodetype ) {
- case en_icon:
- case en_nacon:
- case en_labcon:
- case en_autocon:
- if( (csp = searchnode(node)) != 0 )
- if( csp->reg > 0 ) {
- node->nodetype = en_tempref;
- node->v.i = csp->reg;
- }
- break;
- case en_b_ref:
- case en_w_ref:
- case en_l_ref:
- if( (csp = searchnode(node)) != 0 ) {
- if( csp->reg > 0 ) {
- node->nodetype = en_tempref;
- node->v.i = csp->reg;
- }
- else
- repexpr(node->v.p[0]);
- }
- else
- repexpr(node->v.p[0]);
- break;
- case en_cbl: case en_cbw:
- case en_cwl: case en_uminus:
- case en_not: case en_compl:
- case en_ainc: case en_adec:
- repexpr(node->v.p[0]);
- break;
- case en_add: case en_sub:
- case en_mul: case en_div:
- case en_mod: case en_lsh:
- case en_rsh: case en_and:
- case en_or: case en_xor:
- case en_land: case en_lor:
- case en_eq: case en_ne:
- case en_lt: case en_le:
- case en_gt: case en_ge:
- case en_cond: case en_void:
- case en_asadd: case en_assub:
- case en_asmul: case en_asdiv:
- case en_asor: case en_asand:
- case en_asmod: case en_aslsh:
- case en_asrsh: case en_fcall:
- case en_assign:
- repexpr(node->v.p[0]);
- repexpr(node->v.p[1]);
- break;
- }
- }
-
- repcse(block)
- /*
- * repcse will scan through a block of statements replacing the
- * optimized expressions with their temporary references.
- */
- struct snode *block;
- { while( block != 0 ) {
- switch( block->stype ) {
- case st_return:
- case st_expr:
- repexpr(block->exp);
- break;
- case st_while:
- case st_do:
- repexpr(block->exp);
- repcse(block->s1);
- break;
- case st_for:
- repexpr(block->label);
- repexpr(block->exp);
- repcse(block->s1);
- repexpr(block->s2);
- break;
- case st_if:
- repexpr(block->exp);
- repcse(block->s1);
- repcse(block->s2);
- break;
- case st_switch:
- repexpr(block->exp);
- repcse(block->s1);
- break;
- case st_case:
- repcse(block->s1);
- break;
- }
- block = block->next;
- }
- }
-
- opt1(block)
- /*
- * opt1 is the externally callable optimization routine. it will
- * collect and allocate common subexpressions and substitute the
- * tempref for all occurrances of the expression within the block.
- *
- * optimizer is currently turned off...
- */
- struct snode *block;
- {
- olist = 0;
- scan(block); /* collect expressions */
- allocate(); /* allocate registers */
- repcse(block); /* replace allocated expressions */
- }
-
-
-
- ANSI.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\DESMET_C\ANSI.C
-
- /*************************************************************************
- main function to test some of the ansi device driving functions
- which follow below. NOTE: you need your device set to ansi.sys in the
- config.sys for this to work.
-
- written by Rex Jaeschke of Rockville, MD. 1983 (301) 251-8987
- compiler used DeSmet v2.2
-
- ci () is a DeSmet compiler specific function which does direct console
- input of 1 character without echoing it. It is used in sgr_dsr and the
- testing program only. All else should run on any compiler.
- *************************************************************************/
-
- #define CTRL_C 3
- #define BELL 7
- #define NULL '\0'
- LINEMIN 1 /* Minimum screen line # */
- LINEMAX 25 /* Maximum screen line # */
- COLMMIN 1 /* Minimum screen column # */
- COLMMAX 80 /* Maximum screen column # */
- #define L_ARROW 75
- #define R_ARROW 77
- #define U_ARROW 72
- #define D_ARROW 80
- #define HOME 71
- #define END 79
- #define C_HOME 119
-
- main ()
- {
- int c;
-
- scr_ed (); /* clear screen */
- scr_cup (12,40); /* move to screen center */
- while ((c = ci()) != CTRL_C) {
- if (c == NULL) { /* do we have extended code? */
- c = ci();
- switch (c) {
- case L_ARROW:
- scr_cub (1);
- break;
- case R_ARROW:
- scr_cuf (1);
- break;
- case U_ARROW:
- scr_cuu (1);
- break;
- case D_ARROW:
- scr_cud (1);
- break;
- case C_HOME:
- scr_ed ();
- break;
- case HOME:
- scr_cup (LINEMIN,COLMMIN);
- break;
- case END:
- scr_cup (LINEMAX,COLMMAX);
- break;
- default:
- putchar (BELL);
- break;
- }
- }
- else
- putchar (BELL);
- }
- }
-
-
- ESCAPE 27 /* ASCII ESC character definition */
-
- /*************************************************************************
- SCR_CUB - Cursor Backward.
-
- Moves the cursor backward n columns. Current line remains unchanged. If # of
- columns exceeds left-of-screen, cursor is left at the left-most column.
- *************************************************************************/
-
- scr_cub (ncolms)
- int ncolms;
- {
- printf ("%c[%dD",ESCAPE,ncolms);
- }
-
- /*************************************************************************
- SCR_CUD - Cursor Down.
-
- Moves the cursor down n lines. Current column remains unchanged. If # of line
- to move down exceeds bottom-of-screen, cursor is left at the bottom.
- *************************************************************************/
-
- scr_cud (nlines)
- int nlines;
- {
- printf ("%c[%dB",ESCAPE,nlines);
- }
-
- /*************************************************************************
- SCR_CUF - Cursor Forward.
-
- Moves the cursor forward n columns. Current line remains unchanged. If # of
- columns exceeds right-of-screen, cursor is left at the right-most column.
- *************************************************************************/
-
- scr_cuf (ncolms)
- int ncolms;
- {
- printf ("%c[%dC",ESCAPE,ncolms);
- }
-
- /*************************************************************************
- SCR_CUP - Cursor Position. (same as HVP)
-
- Moves the cursor to the specified position line,colm.
- *************************************************************************/
-
- scr_cup (line,colm)
- int line,colm;
- {
- printf ("%c[%d;%dH",ESCAPE,line,colm);
- }
-
- /*************************************************************************
- SCR_CUU - Cursor Up.
-
- Moves the cursor up n lines. Current column remains unchanged. If # of lines
- to move up exceeds top-of-screen, cursor is left at the top.
- *************************************************************************/
-
- scr_cuu (nlines)
- int nlines;
- {
- printf ("%c[%dA",ESCAPE,nlines);
- }
-
- /*************************************************************************
- SCR_DSR - Device Status Report.
-
- Returns the Cursor Position Report (CPR) sequence in the form ESC[line;colmR
-
- ci () is a DeSmet compiler specific function which does direct console
- input of 1 character without echoing it.
- *************************************************************************/
-
- scr_dsr (line,colm)
- int *line,*colm;
- {
- int i = 0;
- char cpr[10];
-
- printf ("%c[6n",ESCAPE);
- while ((cpr[i++] = ci ()) != 'R')
- ;
- cpr[i] = '\0';
-
- /* format of cpr[] is ESC[rr;ccR row and colm are always two digits */
-
- *line = ((cpr[2]-'0')*10)+cpr[3]-'0';
- *colm = ((cpr[5]-'0')*10)+cpr[6]-'0';
- }
-
- /*************************************************************************
- SCR_ED - Erase in Display.
-
- Erases all of the screen leaving the cursor at home
- *************************************************************************/
-
- scr_ed ()
- {
- printf ("%c[2J",ESCAPE);
- }
-
- /*************************************************************************
- SCR_EL - Erase in Line.
-
- Erases from the cursor to the end of the line including the cursor position.
- *************************************************************************/
-
- scr_el ()
- {
- printf ("%c[2K",ESCAPE);
- }
-
- /*************************************************************************
- SCR_HVP - Horizontal and Vertical Position. (same as CUP)
-
- Moves the cursor to the specified position line,colm.
- *************************************************************************/
-
- scr_hvp (line,colm)
- int line,colm;
- {
- printf ("%c[%d;%dH",ESCAPE,line,colm);
- }
-
- /*************************************************************************
- SCR_RCP - Restore Cursor Position.
-
- Restores the cursor to the value it had when previously saved by scr_scp.
- *************************************************************************/
-
- scr_rcp ()
- {
- printf ("%c[u",ESCAPE);
- }
-
- /*************************************************************************
- SCR_SCP - Save Cursor Position.
-
- Saves the current cursor position for later restoration by scr_rcp.
- *************************************************************************/
-
- scr_scp ()
- {
- printf ("%c[s",ESCAPE);
- }
-
- /*************************************************************************
- SCR_SGR - Set Graphics Rendition.
-
- Sets the character attribute specified by the parameter.
- Attributes remain in force until reset or changed.
- *************************************************************************/
-
- scr_sgr (attrib)
- int attrib;
- {
- printf ("%c[%dm",ESCAPE,attrib);
- }
-
- /*************************************************************************
- SCR_SM - Set Mode.
-
- Sets the screen width or type specified by the parameter.
- *************************************************************************/
-
- scr_sm (param)
- int param;
- {
- printf ("%c[=%dh",ESCAPE,param);
- }
-
- /*************************************************************************
- SCR_RM - Reset Mode.
-
- Sets the screen width or type specified by the parameter.
- *************************************************************************/
-
- scr_rm (param)
- int param;
- {
- printf ("%c[=%dl",ESCAPE,param);
- }
-
-
- ANSI.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\LIB\ME39SRC2\ANSI.C
-
- /*
- * The routines in this file provide support for ANSI style terminals
- * over a serial line. The serial I/O services are provided by routines in
- * "termio.c". It compiles into nothing if not an ANSI device.
- */
-
- termdef 1 /* don't define "term" externa
-
- #include <stdio.h>
- #include "estruct.h"
- #include "edef.h"
-
- #if ANSI
-
- #if AMIGA
- NROW 23 /* Screen size. */
- NCOL 77 /* Edit if you want to. */
- #else
- NROW 25 /* Screen size. */
- NCOL 80 /* Edit if you want to. */
- #endif
- NPAUSE 100 /* # times thru update to pau
- MARGIN 8 /* size of minimim margin and
- SCRSIZ 64 /* scroll size for extended li
- BEL 0x07 /* BEL character. */
- ESC 0x1B /* ESC character. */
-
- extern int ttopen(); /* Forward references. */
- extern int ttgetc();
- extern int ttputc();
- extern int ttflush();
- extern int ttclose();
- extern int ansimove();
- extern int ansieeol();
- extern int ansieeop();
- extern int ansibeep();
- extern int ansiopen();
- extern int ansirev();
- extern int ansiclose();
- extern int ansikopen();
- extern int ansikclose();
- extern int ansicres();
-
- #if COLOR
- extern int ansifcol();
- extern int ansibcol();
-
- int cfcolor = -1; /* current forground color */
- int cbcolor = -1; /* current background color */
-
- #if AMIGA
- /* apperently the AMIGA does not follow the ANSI standards as
- regards to colors....maybe because of the default pallette
- settings?
- */
-
- int coltran[8] = {2, 3, 5, 7, 0, 4, 6, 1}; /* color translation table
- #endif
- #endif
-
- /*
- * Standard terminal interface dispatch table. Most of the fields point into
- * "termio" code.
- */
- TERM term = {
- NROW-1,
- NROW-1,
- NCOL,
- NCOL,
- MARGIN,
- SCRSIZ,
- NPAUSE,
- ansiopen,
- ansiclose,
- ansikopen,
- ansikclose,
- ttgetc,
- ttputc,
- ttflush,
- ansimove,
- ansieeol,
- ansieeop,
- ansibeep,
- ansirev,
- ansicres
- #if COLOR
- , ansifcol,
- ansibcol
- #endif
- };
-
- #if COLOR
- ansifcol(color) /* set the current output color */
-
- int color; /* color to set */
-
- {
- if (color == cfcolor)
- return;
- ttputc(ESC);
- ttputc('[');
- #if AMIGA
- ansiparm(coltran[color]+30);
- #else
- ansiparm(color+30);
- #endif
- ttputc('m');
- cfcolor = color;
- }
-
- ansibcol(color) /* set the current background color */
-
- int color; /* color to set */
-
- {
- if (color == cbcolor)
- return;
- ttputc(ESC);
- ttputc('[');
- #if AMIGA
- ansiparm(coltran[color]+40);
- #else
- ansiparm(color+40);
- #endif
- ttputc('m');
- cbcolor = color;
- }
- #endif
-
- ansimove(row, col)
- {
- ttputc(ESC);
- ttputc('[');
- ansiparm(row+1);
- ttputc(';');
- ansiparm(col+1);
- ttputc('H');
- }
-
- ansieeol()
- {
- ttputc(ESC);
- ttputc('[');
- ttputc('K');
- }
-
- ansieeop()
- {
- #if COLOR
- ansifcol(gfcolor);
- ansibcol(gbcolor);
- #endif
- ttputc(ESC);
- ttputc('[');
- ttputc('J');
- }
-
- ansirev(state) /* change reverse video state */
-
- int state; /* TRUE = reverse, FALSE = normal */
-
- {
- #if COLOR
- int ftmp, btmp; /* temporaries for colors */
- #endif
-
- ttputc(ESC);
- ttputc('[');
- ttputc(state ? '7': '0');
- ttputc('m');
- #if COLOR
- if (state == FALSE) {
- ftmp = cfcolor;
- btmp = cbcolor;
- cfcolor = -1;
- cbcolor = -1;
- ansifcol(ftmp);
- ansibcol(btmp);
- }
- #endif
- }
-
- ansicres() /* change screen resolution */
-
- {
- return(TRUE);
- }
-
- spal(dummy) /* change pallette settings */
-
- {
- /* none for now */
- }
-
- ansibeep()
- {
- ttputc(BEL);
- ttflush();
- }
-
- ansiparm(n)
- register int n;
- {
- register int q,r;
-
- q = n/10;
- if (q != 0) {
- r = q/10;
- if (r != 0) {
- ttputc((r%10)+'0');
- }
- ttputc((q%10) + '0');
- }
- ttputc((n%10) + '0');
- }
-
- ansiopen()
- {
- #if V7 | USG | BSD
- register char *cp;
- char *getenv();
-
- if ((cp = getenv("TERM")) == NULL) {
- puts("Shell variable TERM not defined!");
- exit(1);
- }
- if (strcmp(cp, "vt100") != 0) {
- puts("Terminal type not 'vt100'!");
- exit(1);
- }
- #endif
- strcpy(sres, "NORMAL");
- revexist = TRUE;
- ttopen();
- }
-
- ansiclose()
-
- {
- #if COLOR
- ansifcol(7);
- ansibcol(0);
- #endif
- ttclose();
- }
-
- ansikopen() /* open the keyboard (a noop here) */
-
- {
- }
-
- ansikclose() /* close the keyboard (a noop here) */
-
- {
- }
-
- #if FLABEL
- fnclabel(f, n) /* label a function key */
-
- int f,n; /* default flag, numeric argument [unused] */
-
- {
- /* on machines with no function keys...don't bother */
- return(TRUE);
- }
- #endif
- #else
- ansihello()
- {
- }
- #endif
-
-
- ANYFILE.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\LIB\CSOURCE\ANYFILE.C
-
- /* Chapter 10 - Program 7 */
- #include "stdio.h"
-
- main()
- {
- FILE *fp1;
- char oneword[100],filename[25];
- char *c;
-
- printf("Enter filename -> ");
- scanf("%s",filename); /* read the desired filename */
- fp1 = fopen(filename,"r");
-
- do {
- c = fgets(oneword,100,fp1); /* get one line from the file */
- if (c != NULL)
- printf("%s",oneword); /* display it on the monitor */
- } while (c != NULL); /* repeat until NULL */
-
- fclose(fp1);
- }
-
-
-
- ANYWHERE.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\UTIL\ANYWHERE\ANYWHERE.C
-
- /***************************************************************
- * *
- * WHERE *
- * *
- * Where is a program to locate files on the PC hard disk. *
- * It requires DOS 2.x or 3.x. *
- * *
- * The command line syntax is: *
- * where [starting directory]filename.ext *
- * *
- * Written by Mark S. Ackerman *
- * PROGRAM IS WRITTEN IN MARK WILLIAMS M W C 8 6 LANGUAGE *
- * Copyright 1984, 1985 by Mark S. Ackerman. Permission is *
- * granted for unlimited copies if not sold or otherwise *
- * exchanged for gain. *
- * PUBLISHED IN PC TECH JOURNAL - OCT '85 - VOL 3, NO. 10 *
- * *
- * MODIFIED FOR LATTICE C VER 2.15 BY JOHN TEICHERT NOV 85 *
- * Names shortened to 8 significant characters. *
- * Elimination of PTOREG() function *
- * flag86 defined to return flags from intdosx() *
- * Use segread to set up regs for intdosx() function. *
- * Program modified to look for drive designator with colon.*
- * DATE structure defined with bits high order to low order.*
- * intrpt.h replaced with dos.h header file *
- * rindex() function replaced with strrchr() function. *
- * *
- * MODIFIED FOR MICROSOFT V3 BY JOHN TEICHERT JAN 86. *
- * flag86 REDEFINED to dos_result for intdosx() ax reg *
- * modified to use flag in REGS structure. *
- * DATE structure defined with bits low order to high order.*
- * _stack will not produce large stack in ver 3.0 must use *
- * link option or exemod program. *
- * *
- * Added Code And Became ANYWHERE JOHN TEICHERT FEB 86 *
- * *
- * Taking advantange of V3 access to the environment *
- * string we set up the following. *
- * *
- * 1. An Environment String indicating what disk drives *
- * you want ANYWHERE to search as follows: *
- * *
- * AWDISK=d:[;d:[;d:;...d:]] *
- * *
- * where d: is the drive specifier for one or more *
- * fixed disk(s). *
- * *
- * drive specifiers are searched in the order they *
- * are entered. *
- * *
- * 2. The user can specify the environment string with *
- * the use of the set command in the autoexec.bat file.*
- * As an example: *
- * *
- * set awdisks=c:;e:;d: *
- * *
- * would be placed into the autoexec.bat file. *
- * *
- * With this modification the user has extended directory *
- * capabilities by automatically searching all disk drives*
- * listed in the environment string or isolated to a *
- * single drive by placing a drive specifier in the *
- * command line argument string. *
- * *
- * Be sure to use the /stack option on the link with *
- * Microsoft V3 C compiler or stack problems will result *
- * if many subdirectories. 8K seems to work well. *
- * *
- * *
- * Added a few little perks May 1987 - Michael L Kaufman *
- * *
- ***************************************************************/
-
-
- /***************************************************************
- * The C header files *
- * These identify library routines like printf() and int86x() *
- ***************************************************************/
-
- <stdio.h> /* standard i/o */
- <dos.h> /* functions for DOS interrupt calls */
-
- /***************************************************************
- * Structure for MS-DOS date and time fields *
- * See pages 4-6 and 4-7 of the DOS 2.1 technical *
- * reference manual for more information *
- * This structure is used in the next structure definition *
- ***************************************************************/
-
- struct msdos_date
- {
- unsigned ms_sec : 5; /* time in 2 sec. int (5 bits)*/
- unsigned ms_min : 6; /* minutes (6 bits) */
- unsigned ms_hour : 5; /* hours (5 bits) */
- unsigned ms_day : 5; /* day of month (5 bits) */
- unsigned ms_month : 4; /* month (4 bits) */
- unsigned ms_year : 7; /* year since 1980 (7 bits) */
- };
-
- /***************************************************************
- * Definition of DOS Disk Transfer Area (DTA) *
- ***************************************************************/
-
- /***************************************************************
- * Structure filled in by MS-DOS for interrupt 21 calls *
- * See page 5-46 of the DOS 2.1 technical reference *
- * manual for more information *
- ***************************************************************/
-
- struct DTA
- {
- char DTA_dosinfo[21]; /* used by DOS */
- char DTA_attr; /* file attribute byte */
- struct msdos_date DTA_date; /* date struct. as above */
- long DTA_size; /* file size */
- char DTA_filename[13]; /* file name (w/o path) */
- };
-
-
- /***************************************************************
- * Definitions of constants *
- ***************************************************************/
-
- carry_set 0x0001 /* mask for flag register */
- /* for carry bit */
- no_type 0x00 /* no bits set on file attribute byte */
- directory_type 0x10 /* directory file bit on file */
- /* info word */
-
- no_more_files 18 /* DOS return code for */
- /* no more files */
-
- end_of_string '\0' /* C uses a binary zero to */
- /* signal end of string */
-
- backslash '\\' /* the backslash character */
- colon ':' /* Drive separator JT 11/85 */
- semicolon ';' /* Environment string drive separator */
-
- char *month[] = {
- "Jan","Feb","Mar","Apr","May","Jun",
- "Jul","Aug","Sep","Oct","Nov","Dec"
- };
-
- char *time_of_day[2] = {"AM","PM"};
-
-
- /***************************************************************
- * Define the type "filename" *
- * to be a string of 65 characters -JT *
- ***************************************************************/
-
- typedef char filename[65]; /* Change to 65 -JT
-
- /***************************************************************
- * *
- * The following filename strings are used in the program: *
- * *
- * chk_str filename to be searched for *
- * filename in the command line) *
- * dir_string directory name to be searched *
- * new_dstr directory name to be searched *
- * on next recursive call *
- * cur_str temporary string for searching *
- * in a specific directory *
- ***************************************************************/
-
-
- /***************************************************************
- * Definition of any forward-referenced functions *
- ***************************************************************/
-
- char *DATE();
- char *space();
-
- /***************************************************************
- * Global variables *
- ***************************************************************/
-
- filename chk_str; /* this string "remembers" user inpu
- union REGS r8086; /* structure to allow
- /* registers for interrupts
- struct SREGS s8086; /* structure for s
- char date_str[40]; /* print output string for d
- int count=0; /* Number of matches dislplayed
- char spce[] = " ";
- int lastzero = 41;
- unsigned dos_result; /* Return code from DOS
-
- /**
- * FOLLOWING CODE COMMENTED OUT FOR V3.0 SINCE CAN'T FIND A WAY TO DO I
- * WITH A VARIABLE.
- **/
-
- /*int _stack = 8192; Insure large stack to support
- /* recursion in look routine
-
- /***************************************************************
- * MAIN() -- the beginning of the code *
- ***************************************************************/
-
- main( argc, argv, envp )
- int argc;
- char *argv[];
- char *envp[]; /* Version 3 pointer to environ *
- {
- /**
- * External function
- **/
- char *strrchr(); /* Lattice function which sear
- /* for the last occurrance of the */
- /* desired character
-
- char *strchr(); /* Lattice function which searc
- /* for the first occurrance of the */
- /* desired character
-
- filename dir_string; /* directory to be searched
-
- char *usr_file; /* address of filename in
- /* command line argument */
- /* (ie, the filename)
-
- char *last_loc; /* address of last backslash in */
- /* command line argument */
-
- char *dos_parm; /* address of
- /* command line argument */
-
- int lst_dchr; /* last character
- /* in directory string
-
- /** added for ANYWHERE JT **/
- int strcmpi(); /* Microsoft V3 function to do a
- /* string compare without regard
- /* to case.
- void strcat(); /* String concatenate function
- MAXEDRV 16 /* Set max number of drives
- char *strdup(); /* MSC string dup function
- char *getcwd(); /* MSC ver3 function to return
- /* current working directory
- char *envdup; /* pointer to duplicate of env st
- char *envdrv[MAXEDRV]; /* pointer to each drive
- /* in envdup
- filename env_dir_string; /* Environment directory string
- char **cur_envp; /* current environmnet array p
- char *env_stp; /* Current environment string po
- char *env_chp; /* environment character pointer
- static char envid[]="AWDISK="; /* Our environment stri
- char *envid_p; /* current id string ptr
- filename dos_cwd; /* buffer to hold cur working dir
- int env_cnt; /* count of number of drives
- int envd_len; /* length of the environment stri
- int wi; /* A working integer
- struct {
- unsigned drive : 1; /* drive specifier found in
- unsigned found : 1; /* environment contains AWDI
- unsigned srchcwd : 1; /* Search for current work dir
- unsigned addcwd : 1; /* Add current working dire
- } flag;
-
- /********************************************************
- * check number of incoming arguments *
- * if incorrect, write an error message *
- ********************************************************/
-
- if (argc != 2)
- {
- printf( "ERR usage is: AW [starting directory]filename.ext\n\n");
- printf( "Environment string is: AWDISK=d: [;d: [;....d:] ]\n");
- return;
- }
-
- /** Added for Lattice C Version 2.15 JT
- * Initialize the segment structure for later dos interrupt calls.
- **/
-
- segread( &s8086 ); /* initialize segments for interrupt calls
- dos_result = 0; /* init interrupt return variable MSCV3. */
-
- /**
- * dos_parm is set to the first argument in the
- * command line
- **/
-
- dos_parm = *(++argv);
-
- /**
- * If a drive specifier is found we do not want to go through overhead
- * of environment string search. AW - JT
- * If no drive specifier is found we will extract the drive of the
- * current working directory to be added to the array of environmen
- * drives.
- **/
- flag.srchcwd = 1; /* Init true until command line
- /* option added.
- if ( strchr( dos_parm, colon ) )
- {
- flag.drive = 1; /* Set drive specifier true
- flag.found = 0; /* Set environment found false
- }
- else
- {
- /**
- * Drive flag is set to zero
- * If the search current working directory flag is true then:
- * Current working directory is obtained and the drive isolated
- * from the directory string.
- **/
- flag.drive = 0;
- if ( flag.srchcwd )
- {
- getcwd(dos_cwd,sizeof(dos_cwd)-1);
- env_chp = strchr( dos_cwd, colon );
- *++env_chp = end_of_string;
- }
- }
- /**
- * We check to see if there was a drive specifier found. If so we
- + want to continue rather than check the environment string for the
- * AWDISK= parameter
- **/
- if (flag.drive)
- {
- /**
- * There was a drive specifier so we zero the env_cnt variable
- **/
- env_cnt = 0;
- }
- else
- {
- /**
- * The drive specifier was found in the DOS command argument there
- * the environment strings will be searched for the AWDISK= par
- **/
- cur_envp = envp; /* init current environ pointer */
- flag.found = 0; /* init flag found false */
- /**
- * Check each environment string to see if it is the AW
- * environment string. The envp array is terminated with
- * a NULL pointer. The search is terminated when found is
- * true or the environment pointer is NULL.
- **/
- while( *cur_envp && !flag.found )
- {
- envid_p = envid; /* init pointer to our environ id */
- env_chp = *cur_envp; /* init pointer to environ string */
- flag.found = 1; /* Set flag found = true to enter loop */
- /**
- * Compare each character in the string to AWDISK=
- **/
- for ( env_cnt=0; (env_cnt<(sizeof(envid)-1)) && flag.found; env_cnt++
- {
- if ( *envid_p++ != *env_chp++ )
- flag.found = 0;
- else
- flag.found = 1;
- }
-
- /**
- * If found true then copy string to our buffer
- * Replace ';' with 0x00
- * Count the number of drives found
- * Set addcwd true to add the current working directory
- **/
- if ( flag.found )
- {
- flag.addcwd = 1;
- /**
- * Create a duplicate of the environment string
- * If it cannot be created we will probably fail but allow
- * continuation just in case
- **/
- if (!(envdup = strdup(env_chp)))
- {
- fprintf( stderr, "Memory alloc problems\n" );
- env_cnt = 0; /* zero count cause we're goin ou
- break; /* allow current drive to conti
- }
- /**
- * Examine the environment string for a ";"
- * Replace each semicolon with a "\0" to terminate the stri
- * Increment the env_cnt variable for each drive in the sys
- * that the user wished to examine
- * Place the pointer to the beginning of drive in the envdr
- * variable.
- **/
- envd_len = strlen(envdup); /* get length of environment st
- env_cnt = 0; /* Set count of drives to zero
- env_stp = envdup; /* Set the string pointer to cu
- while ( (envd_len > 0) && (env_cnt < MAXEDRV) )
- {
- /**
- * Look for the semicolon
- **/
- if (env_chp = strchr(env_stp,semicolon))
- {
- /**
- * We have a semicolon : See if its false
- **/
- if (env_chp-env_stp)
- {
- /**
- * There is a string so put in array
- * Decrement the length field
- * Change the value of the semi colon to a end of st
- * Set up a new pointer beyond env_stp
- **/
- envdrv[env_cnt++] = env_stp;
- envd_len = envd_len-((env_chp-env_stp)+1);
- *env_chp = end_of_string;
- /**
- * Check the environment entry against the current
- * working directory. If equal set addcwd to
- * false
- **/
- if ( strcmpi( dos_cwd, env_stp ) == 0 )
- flag.addcwd = 0;
- env_stp = ++env_chp;
- }
- else
- {
- /**
- * There was no string just a semicolon
- * Decrement the length field
- * setup a new pointer beyond the semi-colon
- **/
- --envd_len;
- env_stp = ++env_chp;
- }
- }
- else
- {
- /**
- * There was no semi-colon so we are on the last dr
- * entry.
- * Place address in array and increment count
- * Set the remaining string length to zero to exit.
- * See if last entry matches current working direct
- * if so don't add it.
- **/
- envdrv[env_cnt++] = env_stp;
- envd_len = 0;
- if ( strcmpi( dos_cwd, env_stp ) == 0 )
- flag.addcwd = 0;
- if ( flag.addcwd )
- {
- if ( (env_cnt < MAXEDRV) && (flag.srchcwd) )
- envdrv[env_cnt++] = dos_cwd;
- }
- }
- }
- }
- else
- {
- /**
- * This environment string is not the one we want therefore
- * Increment current environment pointer and continue
- **/
- cur_envp++;
- }
- } /* End While */
- } /* End Else */
-
- /**
- * The dos_parm is then searched for the last
- * occurrence of a backslash to find the end of
- * the directory name.
- **/
-
- last_loc = strrchr(dos_parm,backslash);
-
-
- /********************************************************
- * If there was not a backslash (and therefore the *
- * beginning directory is the root directory) *
- * begin *
- * copy command line argument into chk_str *
- * copy root directory into dir_string *
- * end *
- * else *
- * (if there was a backslash and therefore a beginning *
- * directory specified in the command line) *
- * begin *
- * set the usr_file to the next character *
- * past the backslash *
- * copy the usr_file into chk_str *
- * copy the command line argument into *
- * dir_string *
- * terminate dir_string just after the *
- * last backslash (therefore leaving only the *
- * the directory name in the string) *
- * end *
- ********************************************************/
-
- if (last_loc == NULL)
- {
- /**
- * Since no backslash we'll still check for a drive designator LC 2.14 -JT
- **/
- last_loc = strchr(dos_parm, colon);
- if (last_loc == NULL)
- {
- strcpy(chk_str,dos_parm);
- strcpy(dir_string,"\\");
- }
- else
- {
- usr_file = last_loc + 1;
- strcpy(chk_str,usr_file);
- strcpy(dir_string,dos_parm);
- lst_dchr = usr_file - dos_parm;
- dir_string[lst_dchr++] = backslash; /* Fake path */
- dir_string[lst_dchr] = end_of_string; /* terminate directory str */
- }
- }
- else
- {
- usr_file = last_loc + 1;
- strcpy(chk_str,usr_file);
- strcpy(dir_string,dos_parm);
- lst_dchr = usr_file - dos_parm;
- dir_string[lst_dchr] = end_of_string;
- }
-
-
- /**
- * if the environment string was found concatenate environment drives
- * with the directory string that was extracted.
- * else look for just the directory string
- **/
-
- if ( flag.found)
- {
- for ( wi = 0; wi < env_cnt; wi++ )
- {
- /**
- * Search each directory in the environment array
- **/
- strcpy( env_dir_string, envdrv[ wi ] );
- strcat( env_dir_string, dir_string );
- LOOK( env_dir_string );
- }
- }
- else
- {
- /**
- * There is no environment loop so look only for directory string
- **/
- LOOK(dir_string);
- }
-
- return;
-
- }
-
- /**/
- /*********************************************************
- * LOOK is the recursive procedure in WHERE *
- * It is called once for each subdirectory *
- *********************************************************/
-
- LOOK(dir_string)
- char *dir_string;
- {
-
- struct DTA cur_DTA; /* used to return data from DOS */
-
- filename new_dstr; /* the directory to be */
- /* searched on the next */
- /* call to LOOK() */
-
- filename cur_str; /* temporary filename */
- /* string for searching for */
- /* directories */
-
-
- /**
- * Form cur_str by copying dir_string and *
- * and then concatenating "*.*" to look through all *
- * files *
- **/
-
- strcpy(cur_str,dir_string);
- strcat(cur_str,"*.*");
-
- /**
- * Set the Disk Transfer Area in DOS to the cur_DTA *
- * structure *
- * Get the first subdirectory in this directory *
- **/
-
- SET_DTA(&cur_DTA);
- GET_FIRST(cur_str,directory_type);
-
- /**
- * while there are more subdirectories in this directory *
- * begin *
- * double check for proper directories (see text) *
- * if a directory *
- * begin *
- * set up the new_dstr for the *
- * next call to LOOK (see text) *
- * call LOOK *
- * reset Disk Transfer Address (see text) *
- * end *
- * look for next directory *
- * end *
- **/
-
- while (!(r8086.x.cflag & carry_set))
- {
- if (cur_DTA.DTA_attr == directory_type &&
- cur_DTA.DTA_filename[0] != '.')
- {
- strcpy(new_dstr,dir_string);
- strcat(new_dstr,cur_DTA.DTA_filename);
- strcat(new_dstr,"\\");
- LOOK(new_dstr);
- SET_DTA(&cur_DTA);
- }
- GET_NEXT();
- }
-
- /********************************************************
- * if there are no more subdirectories in this directory *
- * look for files *
- * else *
- * print an error message *
- ********************************************************/
-
- if (r8086.x.ax == no_more_files)
- GET_FILES(dir_string,&cur_DTA);
- else
- printf("problem with looking thru %s\n",dir_string);
- return;
-
- }
-
-
- /********************************************************
- * GET_FILES *
- * is called once per directory to look for the *
- * actual files matching the search string *
- ********************************************************/
-
- GET_FILES(dir_string,cur_DTA)
- char *dir_string;
- struct DTA *cur_DTA;
- {
-
- filename cur_str;
-
- /********************************************************
- * Form cur_str by copying dir_string into *
- * it and then concatenating the chk_str onto *
- * the end *
- ********************************************************/
-
- strcpy(cur_str,dir_string);
- strcat(cur_str,chk_str);
-
- /*********************************************************
- * Get the first file that matches cur_str *
- ********************************************************/
-
- GET_FIRST(cur_str,no_type);
-
- /********************************************************
- * while there are more files that match the search *
- * string: *
- * begin *
- * print the file information *
- * get the next file *
- * end *
- ********************************************************/
-
- while (!(r8086.x.cflag & carry_set))
- {
-
- /* If we have gotten a screenful pause for a keystroke */
- if (++count==24) {
- printf("\t\t<<Hit any key to continue or Q to abort>>");
- count = getch();
- printf("\r\t\t\t\t\t\t\t\t\r");
- if ((count == 'Q') || (count == 'q'))
- exit(1);
- count = 0;
- }
-
- printf(" %10ld %s %s%s\n", (*cur_DTA).DTA_size,
- DATE(&((*cur_DTA).DTA_date)),
- dir_string, (*cur_DTA).DTA_filename);
- GET_NEXT();
- }
-
- /*********************************************************
- * if error in looking for a file *
- * print error message and return *
- ********************************************************/
-
- if (r8086.x.ax != no_more_files)
- printf("problem with looking for %s\n",cur_str);
-
- return;
-
- }
-
- /********************************************************
- * GET_NEXT does an interrupt 21h, function 4Fh *
- * Function 4fh is Get next directory entry *
- ********************************************************/
-
- GET_NEXT()
-
- {
- r8086.x.ax = 0x4f00;
-
- dos_result = int86x( 0x21, &r8086, &r8086, &s8086 );
-
- return;
- }
-
-
- /********************************************************
- * SET_DTA does an interrupt 21h, function 1Ah *
- * The DS:DX pair is set to the address of the *
- * cur_DTA data structure *
- ********************************************************/
-
- SET_DTA(cur_DTA)
- struct DTA *cur_DTA;
- {
-
- r8086.x.ax = 0x1a00;
- r8086.x.dx = (int)cur_DTA; /* set offset to disk transfer area
-
- dos_result = int86x(0x21, &r8086, &r8086, &s8086 );
-
- return;
-
- }
-
- /********************************************************
- * GET_FIRST does an interrupt 21h, function 4Eh *
- * The CX register is set to either normal or *
- * directory type (see text) *
- * The DS:DX pair is set to the address of the *
- * search string *
- ********************************************************/
-
- GET_FIRST(sea_str,filetype)
- char *sea_str;
- int filetype;
- {
-
- r8086.x.ax = 0x4e00; /* Set DOS function
- r8086.x.cx = filetype; /* Set search attribute
- r8086.x.dx = (int) sea_str; /* Set address of string */
-
- dos_result = int86x( 0x21, &r8086, &r8086, &s8086 );
-
- return;
-
- }
-
- /********************************************************
- * DATE takes the date field from the current DTA *
- * structure and returns a string containing the *
- * information in formatted ASCII *
- ********************************************************/
-
- char *DATE(dateptr)
- struct msdos_date *dateptr;
- {
-
- sprintf(date_str, "%02d-%02d-%02d %02d:%02d %s",
- dateptr->ms_month, dateptr->ms_day,
- dateptr->ms_year+80, (dateptr->ms_hour)%12,
- dateptr->ms_min, time_of_day[((dateptr->ms_hour)/12)]);
- return(date_str);
-
- }
-
- char *space(where)
- int where;
- {
- spce[lastzero] = ' ';
- spce[where] = '\0';
- return spce;
- }
-
-
- AREACODE.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\ZED\AREACODE.C
-
- /* area.c 11/26/83
- Modified 3-18-86 by Charles Ransom
- [update area codes -CR]
-
- Telephone area code search program
- (C) 1983 Martin Smith
- Compuserve 72155,1214 Source ST2259
- 310 Cinnamon Oak Lane (713) 661-1241 [Office]
- Houston, Texas 77079 (713) 464-6737 [Home]
-
- Find area codes by entering an area code or state name on the
- command line. Multiple codes, names are permitted up to 20,
- the limit set forth for C86 Computer Innovations(tm) compiler.
- Program written for IBM-PC with PC-DOS 2.0, but no machine-specific
- code is involved.
-
- The table is near the top of this file to make it easier to maintain.
- Area codes don't change much, but just this year in Houston our
- area code was broken off from the surrounding area.
- The format of the table is simple, so adding cities to the city list
- or even new states or regions won't upset the program if a few easy
- rules are followed:
-
- 1) The table format is one array of string pointers.
- 2) A state name consists of a two character postal abbreviation,
- like CA for California, and then the actual name,
- a) All data on this line is lowercase. A multiple word name,
- like New Jersey, would be entered as "njnew*jersey" , .
- This prevents argv from making two arguments out of the name.
- 3) An area code is the three digit code, followed by whatever text.
- a) As many area codes, cities as you want are ok.
- 4) All entries need to be enclosed in quotes (") and followed by a
- comma.
- */
-
- #include "stdio.h"
- areacode(s,x)
- char *s;
- int x;
- {
- unsigned strlen();
-
- static char *area[] =
- { "alalabama" , "205 All locations",
- "akalaska" , "907 All locations",
- "azarizona" , "602 All locations",
- "ararkansas" , "501 All locations",
- "cacalifornia" ,
- "805 Bakersfield" , "209 Fresno" , "213 Los Angeles" ,
- "213 Burbank" , "714 Camp Pendelton" , "415 Palo Alto",
- "916 Folsom" , "714 Fullerton" , "805 Oxnard"
- "916 Sacramento" , "619 San Diego" , "415 San Francisco" ,
- "707 Santa Rosa" , "408 San Jose" , "213 Santa Monica" ,
- "cncanada" ,
- "519 London, Ont." , "514 Montreal, Quebec" , "403 Alberta" ,
- "613 Ottawa, Ont." , "418 Quebec, Quebec" , "306 Saskatchewan" ,
- "416 Toronto, Ont." , "604 British Columbia" , "204 Manitoba" ,
- "807 East Ontario" , "705 West Ontario" , "819 NW Quebec" ,
- "709 Newfoundland" , "506 New Brunswick" ,
- "902 Nova Scotia, Prince Edward Island" ,
- "cocolorado" , "303 All locations" ,
- "ctconnecticut" , "203 All locations" ,
- "dedelaware" , "302 All locations" ,
- "dcdistrict of*columbia" , "202 Washington" ,
- "flflorida" ,
- "813 Ft. Myers, Winter Haven" , "904 Jacksonville" ,
- "305 Miami, Key West, Ft. Lauderdale" ,
- "gageorgia" ,
- "404 Atlanta, Rome" , "912 Waycross" ,
- "hihawaii" , "808 All locations" ,
- "ididaho" , "208 All locations" ,
- "ilillinois" ,
- "618 Alton, Mt. Vernon" , "312 Chicago, Aurora, Waukegan" ,
- "815 Rockford" , "217 Springfield" , "309 Peoria" ,
- "inindiana" ,
- "812 Evansville" , "219 Gary, South Bend, Warsaw" ,
- "317 Indianapolis, Kokomo" ,
- "iaiowa" ,
- "712 Council Bluffs" , "515 Des Moines" , "319 Dubuque" ,
- "kskansas" ,
- "316 Wichita, Dodge City" ,
- "913 Topeka, Lawrence, Manhattan, Salina" ,
- "kykentucky" ,
- "502 Louisville, Frankfort, Paducah, Shelbyville" , "606 Winchester"
- "lalouisiana" ,
- "504 Baton Rouge, New Orleans" , "318 Lake Charles" ,
- "memaine" , "207 All locations" ,
- "mdmaryland" , "301 All locations" ,
- "mamassachusetts" ,
- "617 Boston, New Bedford, Plymouth, Worchester" ,
- "413 Springfield" ,
- "mxmexico" ,
- "905 Mexico City" , "706 NW Mexico" ,
- "mimichigan" ,
- "313 Detroit, Ann Arbor, Flint" ,
- "616 Battle Creek, Grand Rapids, Kalamazoo" ,
- "517 Lansing" , "906 Escanaba" ,
- "mnminnesota" ,
- "218 Duluth" , "612 Minneapolis, St. Paul" , "507 Rochester" ,
- "msmississippi" , "601 All locations" ,
- "momissouri" ,
- "816 Belton, Independence, Kansas City, Marshall, St. Joseph, Sedalia
- "314 St. Louis, Cape Girardeau, Columbia, Fulton, Hannibal, \n\tJeffe
- "417 Joplin, Springfield" ,
- "mtmontana" , "406 All locations" ,
- "nenebraska" ,
- "402 Omaha, Lincoln" , "308 North Platte" ,
- "nvnevada" , "702 All locations" ,
- "nhnew*hampshire" , "603 All locations" ,
- "njnew*jersey" ,
- "609 Atlantic City, Camden, Trenton" ,
- "201 Newark, Hackensack, New Brunswick, Patterson" ,
- "nmnew*mexico" , "505 All locations" ,
- "nynew*york" ,
- "518 Albany, Schenectady" , "607 Binghamton" ,
- "716 Buffalo, Niagara Falls, Rochester" , "914 White Plains" ,
- "212 New York City" , "315 Syracuse" ,
- "ncnorth*carolina" ,
- "704 Charlotte, Salisbury" ,
- "919 Greenville, Raleigh, Winston-Salem" ,
- "ndnorth*dakota" , "701 All locations" ,
- "ohohio" ,
- "216 Akron, Cleveland, Youngstown" ,
- "513 Cincinnati, Dayton" , "614 Columbus" ,
- "419 Toledo" ,
- "okoklahoma" ,
- "918 Tulsa, Bartlesville, McAlester, Muskogee" ,
- "405 Oklahoma City, Enid, Norman, Ponca City, Stillwater" ,
- "ororegon" , "503 All locations" ,
- "papennsylvania" ,
- "215 Philadelphia, Allentown" , "814 Erie" ,
- "412 Pittsburgh" , "717 Harrisburg, Scranton" ,
- "prpuerto*rico" ,
- "809 Anguilla, Antigua, Bahamas, Barbados, Bermuda, Cayman Islands, \n\tDomin
- "rirhode*island" , "401 All locations" ,
- "scsouth*carolina" , "803 All locations" ,
- "sdsouth*dakota" , "605 All locations" ,
- "tntennessee" ,
- "615 Nashville, Chattanooga" , "901 Memphis" ,
- "txtexas" ,
- "915 Abilene, Alpine, Big Spring, El Paso, Midland, Odessa" ,
- "512 Austin, Brownsville, Corpus Christi, Del Rio, Eagle Pass, \n\tLa
- "806 Amarillo, Dalhart, Lubbock" ,
- "713 Houston, Baytown, Pasadena" ,
- "409 Bay City, Beaumont, Bryan, College Station, Galveston, Huntsvill
- "214 Dallas, Ennis, Greenville, Jefferson, Longview, Sherman, Tyler"
- "817 Fort Worth, Denton, Temple, Waco, Wichita Falls" ,
- "ututah" , "801 All locations" ,
- "vtvermont" , "802 All locations" ,
- "vivirgin*islands" , "809 All locations" ,
- "vavirginia" ,
- "804 Charlottesville, Newport News, Norfolk, Richmond" ,
- "703 Roanoke, Winchester" ,
- "wawashington" ,
- "206 Seattle, Olympia, Vancouver" , "509 Walla Walla" ,
- " wide area" , "800 All locations" ,
- "wvwest*virginia" , "304 All locations" ,
- "wiwisconsin" ,
- "414 Milwaukee, Green Bay, Racine" ,
- "608 Madison" , "715 Wausau" ,
- "wywyoming" , "307 All locations" ,
- NULL } ;
-
- int i,j,found;
- unsigned k;
- char temp[64];
- char *t;
-
- if (x==2) /* a number area code */
- {
- found=0;
- for (i=0; area[i] != NULL; i++)
- {
- if (strncmp(area[i],s,3)==0) /* test for match */
- {
- for (j=i-1; satoi(area[j]) != 0; --j) /* then go back for st
- ;
- stprint(area[j]); /* special print out for state name *
- putchar('\n');
- printf(" %s.\n\n",area[i]);
- found=-1;
- break; /* stop when found */
- }
- }
- if (found==0)
- printf("Not found, %s.\n\n",s);
-
- }
- else
- if (x==1) /* state name or two letter code is input */
- {
- for (i=0; s[i] != '\0'; i++) /* make everything lowercase */
- s[i]=tolower(s[i]);
- if (strlen(s)==2) /* two letter code assumed */
- {
- found=0;
- for (i=0; area[i] != NULL; i++)
- {
- if (strncmp(s,area[i],2)==0)
- {
- stprint(area[i]);
- putchar('\n');
- for (j=i+1; satoi(area[j]) != 0;j++)
- printf(" %s.\n",area[j]);
- found=-1;
- putchar('\n');
- break;
- }
- }
- if (found==0)
- printf("Not found, %s.\n",s);
- }
- else /* otherwise try for state name */
- {
- k=strlen(s); /* ok if partial name */
- found=0;
- for (i=0; area[i] != NULL; i++)
- {
- if (satoi(area[i])==0)
- {
- t=area[i];
- t=t+2;
- strcpy(temp,t);
- if (strncmp(temp,s,k) == 0)
- {
- stprint(area[i]);
- putchar('\n');
- for (j=i+1; satoi(area[j]) != 0;j++)
- printf(" %s.\n",area[j]);
- found=-1;
- putchar('\n');
- break;
- }
- }
- }
- if (found==0)
- printf("Not found, %s.\n",s);
- }
- }
- else /* print entire list */
- {
- for (i=0; area[i] != NULL; i++)
- {
- if (satoi(area[i])==0)
- {
- putchar('\n');
- stprint(area[i]);
- putchar('\n');
- }
- else
- printf(" %s.\n",area[i]);
- }
- }
- }
-
- /* special printout for state name */
- stprint(s)
- char s[];
- {
- int i;
- putchar(toupper(s[0]));
- putchar(toupper(s[1]));
- printf(" ");
- putchar(toupper(s[2]));
- for (i=3; s[i] != '\0'; i++)
- {
- if (s[i]=='*')
- {
- putchar(' ');
- putchar(toupper(s[++i]));
- }
- else
- putchar(s[i]);
- }
- printf(" area code(s): ");
- }
-
- main(argc,argv)
- int argc;
- char *argv[];
- {
- int i,satoi();
- printf(" ** Area Code Finder **\n");
- printf(" (C) Marty Smith 1983 \n\n");
- printf(" Modified by Charles Ransom -1986\n\n");
- if (argc==1)
- {
- printf("Program searches for telephone area codes,\n");
- printf(" as area xxx xxx xxx etc.\n");
- printf(" xxx is an Area Code or State name.\n");
- printf(" Two letter state postal codes like TX for Texas, CA for Ca
- printf(" can be used, otherwise type in the state name.\n");
- printf(" Enter two word state names like this: New*Jersey.\n");
- printf(" Enter area * for a list of all Area Codes.\n");
- }
- else
- if (*argv[1]=='*')
- areacode(argv[1],0);
- else
- {
- for (i=1; i < argc; ++i)
- {
- if (satoi(argv[i])==0)
- areacode(argv[i],1);
- else
- areacode(argv[i],2);
- }
- }
- }
-
- /* integer convert to number */
- int satoi(s)
- char s[];
- {
- int i, n, sign;
-
- for (i=0; s[i]==' ' || s[i]=='\n' || s[i]=='\t'; i++)
- ; /* skip white space */
-
- sign = 1;
- if (s[i] == '+' || s[i] == '-')
- sign = (s[i++]=='+') ? 1 : -1;
- for (n=0; s[i] >= '0' && s[i] <= '9'; i++)
- n = 10 * n + s[i] - '0';
- return(sign * n);
-
- }
-
-
-
- ASCIDUMP.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\FUNC\DUMPS\ASCIDUMP.C
-
- /****************************************************************************
- /* *
- /* ASCIDUMP.C *
- /* *
- /* This program prints the ASCII decimal codes and actual text for a file *
- /* specified as the first command line argument. It reads the file a block *
- /* at a time and prints the decimal value of each character, then prints *
- /* the translated characters at the end of the line. It translates certain *
- /* special characters like BELL, LF, FF to spaces for printing *
- /* *
- /* Written by: Jim Niederriter 12/26/83 *
- /* *
- /****************************************************************************
- /* *
- /* This program was written for the Lattice `C' Compiler, and works under *
- /* version 1.04 or 2.00. *
- /* *
- /****************************************************************************
-
- #include <stdio.h>
- #define BELL 7
- #define MAXCHR 30
- #define NULL 0
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- int loopx, linecnt;
- int x, f1, stats, flag, fmode;
- long countr;
- char buffer[MAXCHR + 1];
- FILE *f2, *fopen();
-
- /****** Looks for filename as first command line argument *******************
-
- if (argc < 2)
- {
- puts("Requires file name in command line\n");
- putch(BELL);
- exit(1);
- }
-
- /****** Opens printer as LPT1 ***********************************************
-
- if ((f2 = fopen("LPT1:", "w")) == NULL)
- {
- puts("Can't open printer file\n");
- putch(BELL);
- exit(1);
- }
- /****** Open file as read-only, and in `untranslated' mode...(does not */
- /****** convert CR/LF). *************************************************/
-
- fmode = 0; /* mode for `read-only' */
- fmode = 0x8000; /* set to read in `untranslated' or binary mode */
-
- if ((f1 = open(argv[1], fmode)) == NULL)
- {
- printf("Can't open file %s.\n", argv[1]);
- putch(BELL);
- exit(1);
- }
- /***** Printer codes are set up for EPSON FX (change to match your printer */
-
- fprintf(f2, "\x1BP\x0F"); /* set printer to PICA, CONDENSED */
-
- /**** This one sets the `skip over perforation' to 3 lines *****************/
-
- fprintf(f2, "\x1BN\x03\nCount File ");
- fprintf(f2, "dump for file name: %s \n", argv[1]);
-
- countr = loopx = linecnt = 0;
- flag = 1;
- while (flag)
- {
- flag = 0;
- setmem(buffer, MAXCHR, NULL); /* clear buffer */
- if ((stats = read(f1, buffer, MAXCHR)) > 0) /* read blk from file *
- {
- fprintf(f2, "%05ld ", countr); /* print char count */
- countr += MAXCHR;
- flag = 1;
-
- for (x=0; x <= (MAXCHR-1); x++)
- {
- fprintf(f2, "%03d", buffer[x]); /* print decimal value *
-
- /****** change any special characters to SPACE for printing *****************
-
- if (buffer[x] < 32 || buffer[x] > 128)
- buffer[x] = ' '; /* get rid of unprintables */
-
- if ((loopx +=1) == 5)
- {
- fprintf(f2, " "); /* 5 at a time */
- loopx = 0;
- }
- }
- fprintf(f2, "*"); /* print translated characters *
- for (x=0; x <= (MAXCHR-1); x++)
- fprintf(f2, "%c", buffer[x]);
- fprintf(f2, "*\n");
- if ((linecnt += 1) == 5)
- {
- fprintf(f2, "\n"); /* skip 1 after every 5 lines */
- linecnt = 0;
- }
- }
- }
- fprintf(f2, "\x1BP\x0C"); /* set back to normal & do forms feed */
- fflush(f2);
- fclose(f2);
- }
-
-
- ASIN.C
- CD-ROM Disc Path: \SAMPCODE\ALDE_C\MISC\LIB\JPLC2\ASIN.C
-
- /* 1.0 04-27-84 */
- /************************************************************************
- * Robert C. Tausworthe
- * Jet Propulsion Laboratory *
- * Pasadena, CA 91009 1984
- ************************************************************************
- * Programmmed using the algorithms given in:
- *
- * Coty, William J., Jr., and Waite, William, SOFTWARE MANUAL FOR
- * THE ELEMENTARY FUNCTIONS, Prentice-Hall Series in Computational
- * Mathematics, Prentice-Hall, Inc., Inglewood Cliffs, NJ, 1980,
- * pp. 174-193.
- *
- *----------------------------------------------------------------------*/
-
- #include "defs.h"
- #include "stdtyp.h"
- #include "errno.h"
- #include "mathtyp.h"
- #include "mathcons.h"
-
- /*----------------------------------------------------------------------*/
-
- #define P0 +1.0
- #define P1 -0.27368494524164255994e+2
- #define P2 +0.57208227877891731407e+2
- #define P3 -0.39688862997504877339e+2
- #define P4 +0.10152522233806463645e+2
- #define P5 -0.69674573447350646411
- #define P(g) ((((P5*g P4)*g P3)*g P2)*g P1)
-
- #define Q0 -0.16421096714498560795e+3
- #define Q1 +0.41714430248260412556e+3
- #define Q2 -0.38186303361750149284e+3
- #define Q3 +0.15095270841030604719e+3
- #define Q4 -0.23823859153670238830e+2
- #define Q(g) (((((g Q4)*g Q3)*g Q2)*g Q1)*g Q0)
-
- LOCAL double asincos();
-
- /************************************************************************/
- double
- asin(x) /* return the trigonometric arc-sine of x
-
- /*----------------------------------------------------------------------*/
- double x;
- {
- return asincos(x, 0);
- }
-
- /*\p*********************************************************************/
-
- double acos(x) /* return the trigonometric arc-cosine of x
-
- /*----------------------------------------------------------------------*/
- double x;
- {
- return asincos(x, 1);
- }
-
- /************************************************************************/
- LOCAL double
- asincos(x, flg) /* return arc sin or cos, depending on flg
-
- /*----------------------------------------------------------------------*/
- double x;
- {
- double y, g, r;
- FAST int i;
- LOCAL double a[2] = { 0.0, PIover4};
- LOCAL double b[2] = { PIover2, PIover4};
-
- y = ABS(x);
- i = flg;
- if (y < FADEOUT)
- r = y;
- else
- { if (y > 0.5)
- { i = 1 - i;
- if (y > 1.0)
- { errno = EDOM;
- return 0.0;
- }
- g = ldexp((0.5 - y) + 0.5, -1);
- y = -ldexp(sqrt(g), 1);
- } else
- g = y * y;
- r = y + y *
- ((P(g) * g)
- / Q(g));
-