You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Current »

More Routines And Variables

Character and String Routines

match=sameas(stg1,stg2); case-insensitive string match

int match; return code: true if strings are same

char *stg1,*stg2; strings to test for matching

sameas() returns true if the two strings are the same, ignoring letter case, for example sameas("Fred W. Jones","FRED W. JONES") == 1.

match=sameto(shorts,longs);
case-insensitive substring match

int match; true if shorts = first part of longs

char *shorts; short string: entirety must match char

char *longs; long string: may have excess on end

The sameto() function is like sameas(), but it allows the first parameter to be just a portion of the second. For example:

        sameto("good","gooder") == 1
        sameto("good","good enough") == 1
        sameto("best","best") == 1
        sameto("baddest","bad") == 0
        sameto("women","womanhood") == 0

Another variation:

        match=samend(longs,ends);

The samend() routine compares endings of strings, asking if the first string ends with the second string, ignoring case. Examples:

        samend("the end","end") == 1
        samend("dogs","s") == 1
        samend("gooder","ER") == 1
        samend("end","the end") == 0
        samend("sheep","s") == 0

We remember the parameter order for sameto() and samend() by thinking of the prefix (shorts) sitting next to the prefix side of the long string (longs), therefore to the left of it in sameto().

In samend(), we think of the suffix (ends) sitting next to the suffix side of the long string (longs), therefore to the right of it. This way sameto("beg","beginning") and samend("ending","ing") are both true.

found=samein(subs,string);
Search a string for a case-insensitive substring

int found; 1=found 0=not

char *subs; substring

char *string; string

This function searches the string for any occurrence of the substring, and returns 1 if it finds any. Examples:

        samein("good","gooder") == 1
        samein("s","UNITED STATES") == 1
        samein("can't","cannot") == 0
        samein("badder","bad") == 0

sprstg=spr(ctlstg,p1,p2,...,pn);
sprintf-like string formatter utility

char *sprstg; result string pointer (max 120 bytes)
char *ctlstg; control string (%l, etc. allowed)
TYPE p1,p2,...,pn; sprintf-type parameters (max 12 bytes)

This routine is frequently used itself as an argument to prf(), prfmsg(), catastro(), or other printf() format functions. Those functions do not support long integer or floating point conversions (%ld or %f), but spr() does. Warning: the string created by spr() must not exceed 120 bytes, including the terminating \0. Violation of this rule may have insidious results.

stzcpy(dest,source,nbytes);
Copy a string, with limit

char *dest; where to put it

char *source; the string

int nbytes; size of destination, including ‘\0’

If the source string takes up more than nbytes of space (including its nul), then a truncated version is copied to dest. If the source takes up less, then the remaining bytes of dest are filled with nuls. The dest buffer always gets at least one nul at the end (assuming nbytes > 0 — if nbytes <= 0, then stzcpy() does nothing). Exactly nbytes bytes are written to dest (if nbytes > 0).

stlcpy() is the same as stzcpy() except that it doesn't bother to pad with more than 1 nul:

        stlcpy(dest,source,maxbytes);

Use the following routines for parsing character strings of one or more words separated by whitespace characters:

pastwhite=skpwht(string); Skip past whitespace

char *pastwhite; pointer to the first nul or non-whitespace character in the string

char *string; nul-terminated character string

pastword=skpwrd(string); Skip past non-whitespace

char *pastword; pointer to the first nul or whitespace character in the string

char *string; nul-terminated character string

stg=l2as(lnum); convert a long integer to an ASCII decimal string of digits

char *stg; where to store the result

long lnum; input long integer

This function converts a 32-bit signed integer to a decimal character string. Note that:

spr("%ld",lnum) is the same as l2as(lnum)

Both spr() and l2as() use a 4-stage rotating-buffer technique to avoid the problem of multiple calls pointing to the same physical location. This means you can have up to 4 calls in a single parameter list before overlap will cause difficulties. For example:

prf("Shares traded today: %s %s %s",l2as(nyse),l2as(amex),l2as(otc));

Each of the three calls to l2as() will return the address of a different buffer — not overlap three conversions into the same buffer.

ptr=lastwd(stg); get the last word of a string

char *ptr; pointer to the last word

char *stg; the input string

lastwd() finds the last word in a string. The return value points to the last nonblank character preceded by a blank (or it points to the beginning of the string if it can’t find this).

xltctls(txtbuf); translate ASCII control characters

char *txtbuf; text buffer (input and output)

This routine translates ^-preceded letters into control characters. For example, the two-character sequence **^**G will be translated, in-place, to a single ctrl+G (ASCII bel) character.

valid=isselc(c); is c a valid menu-select character?

valid=istxvc(c); is c a valid text-variable character?

valid=isuidc(c); is c a valid User-ID character?

int valid; 1=yes 0=no

int c; character (all routines will return false for non-ASCII values of c)

These are the routines we use for checking input strings for valid characters. International characters in the extended ASCII set are supported here.

Here are some more character-handling and string-handling routines:

yes=alldgs(string); Is this string all decimal digits?

int yes; 1=yes 0=no, has other characters

char *string; nul-terminated string

oddparity=odd(somebyte); Compute odd parity

char somebyte; a byte

char oddparity; a byte with odd parity and with the same lower 7 bits as somebyte

rmvwht(string); Remove all whitespace characters

char *string; string (conversion is in-place)

nremoved=depad(string); Remove trailing blanks from string

int nremoved; number of blanks removed

char *string; nul-terminated string

bufptr=unpad(string); Remove trailing blanks from string

char *bufptr; copy of string pointer

char *string; nul-terminated string

sortstgs(strings,nstrings);
Sorts a bunch of strings by rearranging an array of pointers

char *strings[]; array of pointers to the strings

int nstrings; number of strings

See also the memory handling routines movmem(), setmem(), and repmem() on page 67.

Real-Time Routines: rtkick(), rtihdlr()

rtkick(time,rouptr); “kick off” routine after time delay

int time; number of seconds before “kickoff”

void *rouptr(); pointer to routine to be kicked off

Naturally the time delay here is not wasted. Control returns to your calling routine almost instantly, and the specified number of seconds later (plus or minus a few), the specified routine is invoked. The invocation actually takes place at the call to prcrtk() found near the bottom of the main loop in main() in MAJORBBS.C.

To make a routine get called at regular intervals, your initialization code could call rtkick() on the routine, and then the routine could call rtkick() on itself. Use time=60 for the routine to run once a minute, or time=1 for once a second.

rtihdlr(rouptr); Register a real-time routine

Applies to: v10

WGSEXP VOID rtihdlr(VOID (*rouptr)(VOID)); (MAJORBBS.H:746). MBBS10.txt section 2: "The rtihdlr() routine has been restored and is functional. This is the realtime interrupt handler that used to be limited to DOS versions of the BBS. It's been returned to the core system with native Windows routines and old modules using it can now be ported!" The prototype is the same as in WG3.2, so this is a statement about run-time behaviour. The "18 Hz" rate and the interrupt-time restrictions printed here are the DOS behaviour and are unverified for v10; dsairp()/enairp() below belong to the same DOS-era group.

void (*rouptr)(void); routine to call at 18 Hz

If you have a routine that you need to execute more often than once a second, you could register it with rtihdlr(). Once you start this, it runs the entire time the Major BBS server is up (don’t keep calling rtihdlr() on the routine like you could do with rtkick()). This routine will be running at interrupt level, so don’t try any DOS or GSBL calls except the chixxx() routines (see GSBL Guide). And be sure the routine uses as short a time as possible, or the server will lose its real-time responsiveness.

dsairp() Disable interrupts

enairp() Enable interrupts

These routines can be used to disable interrupts for very brief sequences of code. Warning: disabling interrupts for too long can cause you to lose incoming characters at high baud rates. For example, 300 microseconds is too long for 38,400 baud.

tix64k=hrtval(); Read the free-running 65KHz timer

unsigned long tix64k; upper word counts seconds,
lower word counts 1/65536 seconds

This routine reads the GSBL long integer variable btuhrt while interrupts are disabled, in order to avoid skew. You should almost always use hrtval() in place of referencing btuhrt. To measure the time between two events you can call hrtval() at each event and compute the difference between the values (later value minus earlier value). The result will be a count, in 1/65536 second units, of the time between the two events. Of course, this won’t work if more than 65536 seconds elapse between calls (about 18 hours).

Applies to: WG3.x

Header check: btuhrt (WG2 BRKTHU.H:88, volatile unsigned long) is not declared in WG3.2; the tick counter is EXPGSBLV(volatile USHORT) ticker with btuTicker() (BRKTHU.H:214-217). hrtval() is still declared (GCOMM.H:734). The 16-bit rate and width differ from the text.

Time and Date Routines

date=today(); Find out today’s date

int date; YYYYYYYMMMMDDDDD coding for today

This returns today’s date in the format that DOS uses for dates:

YYYYYYYMMMMDDDDD Where...

YYYYYYY--------- (Year-1980) * 512 Representing 1980 through 2107

-------MMMM----- Month * 32 Representing 1 through 12

-----------DDDDD Day of month Representing 1 through 31

day=daytoday(); Find out what day of the week it is

int day; 0=Sunday 6=Saturday

time=now(); Find out what time of day it is

int time; HHHHHMMMMMMSSSSS coding for time

This returns the time of day in the format that DOS uses for time:

HHHHHMMMMMMSSSSS Where...

HHHHH----------- Hour * 2048 Representing 0 through 23

-----MMMMMM----- Minute * 32 Representing 0 through 59

-----------SSSSS 2-second intervals Representing the even numbers
0 through 58

ascdat=ncdate(date); Encode date into MM/DD/YY

Applies to: WG3.x

const CHAR * vs CHAR * hazard. In WG3.2 ncdate(), nctime(), ncedat() and ncudnt() return const CHAR * (DNTAPI.H:209,217,221,229), as do the new ncdatel() (:213) and ncedatl() (:225); the date/time arguments are USHORT (:209-231). The examples here declare char *ascdat; in WG3.x declare const CHAR *ascdat;, or copy the result with stlcpy(buf,p,sizeof buf) (GCOMM.H:409) before modifying it. The result is a library-local buffer reused by the next call. dcdate() now takes const CHAR * and returns USHORT (GCINVALIDDOT if invalid, DNTAPI.H:248) and accepts four-digit years; the Date and Time API is described in chapter 27.

char *ascdat; local buffer for date

int date; YYYYYYYMMMMDDDDD coding (see above)

asctim=nctime(time); Encode time into HH:MM:SS

char *asctime; local buffer for time

int time; HHHHHMMMMMMSSSSS coding (above)

ascdat=ncedat(date); Encode date into DD-MMM-YY
(European style)

char *ascdat; local buffer for date

int date; YYYYYYYMMMMDDDDD coding

date=dcdate(ascdat); Decode date from MM/DD/YY

int date; YYYYYYYMMMMDDDDD coding
or -1=invalid date format

char *ascdat; date string

time=dctime(asctim); Decode time from HH:MM:SS

int time; HHHHHMMMMMMSSSSS coding
or -1=invalid time format

char *asctime; time string

count=cofdat(date); Count of days since 1/1/80

int count; number of days since 1/1/80

int date; YYYYYYYMMMMDDDDD coding

date=datofc(count); Compute DOS date

int date; YYYYYYYMMMMDDDDD coding

int count; number of days since 1/1/80

See also page 322 for reading and setting a file’s time and date.

Numeric Routines

smaller=min(a,b); Find the smaller of two numbers

bigger=max(a,b); Find the larger of two numbers

Since these are implemented as macros, the numbers can be all int, all unsigned, or all long.

absval=abs(signednum); Find the absolute value of a signed integer (int or long)

newcrc=calcrc(oldcrc,ch);
Iteratively calculate a 16-bit CRC

Applies to: WG3.x

Header check: calcrc() (WG2 GCOMM.H:464) is not declared in WG3.2. The checksum routines are crc16(), crc32(), c16(), c32() (GCOMM.H:1025,1030) which take const CHAR * (WG2: unsigned char *): the byte signedness changed.

int newcrc; CRC on N+1 bytes

int oldcrc; CRC on N bytes

char ch; N+1’th byte

This routine calculates a 16-bit CRC based upon the polynomial x^16+x^12+x^5+1. This is the same CRC as is computed for the XMODEM-CRC protocol.

Text File Scanning

This suite of routines can be handy for scanning one or more text files, especially if you’re looking for lines that start with some prefix string. We use these routines to scan all .MDF files for all the lines we’re interested in. For a really thorough demo of the tfsxxx() routines, see how this is done in INTEGROU.C (available with the Extended C Source Developer’s Kit).

This is not a good thing to be doing for online user processing however. For one thing, the work is unbounded (how many files? how many lines?) so it could hold up the server for an unacceptably long time. For another, you can’t have multiple text file scanning operations going on at once — they work off of global variables in TFSCAN.C (available with the Extended C Source Developer’s Kit).

But the text file scanning routines can be real handy for offline processing, for initializing things before the server comes up, or for nightly cleanup operations.

nfiles=tfsopn(filespec);
Prepare to scan 1 or more text files

char *filespec; file spec (may contain wildcards)

int nfiles; number of files matching file spec

tfs=tfsrdl(); Read next line from file(s)

int tfs; returns latest value of tfstate

int tfstate; Scanning state, with these values:

TFSBGN tfsopn() was just called, identifying 1 or more files

TFSBOF preparing to scan a file (name can be found in tfsfb.name)

TFSLIN scanning lines of a file (line is in tfsbuf)

TFSEOF done scanning a file

TFSDUN all files have been scanned

char *tfsbuf; Line read in by tfsrdl() if tfsrdl() returned TFSLIN

When you call tfsrdl(), the state value can be found either from its return value, or from the global tfstate variable. You should keep calling tfsrdl() until it returns TFSDUN. Other than that, the most interesting state/return value is TFSLIN. This means tfsrdl() has done its duty and retrieved a line of text from the file or set of files. That line is available in tfsbuf. The return values TFSBOF and TFSEOF could be useful if you needed to do know when the scanning reached file boundaries.

If you’re looking for a specific prefix, or set of prefixes, you can use tfspfx() to find it and to isolate what follows the prefix:

found=tfspfx(prefix); Is the current line prefixed with this?

char *prefix; Prefix string

int found; 1=yes, 0=no. if yes, tfspst points to what follows the prefix

char *tfspst; pointer to string following the prefix, with preceding white space removed

For example, if the line you read in was DLL=GALBLAST, then tfspfx("DLL=") would return 1 and tfspst would point to GALBLAST.

Suppose you needed to scan all .MDF files on the server and pass all module names through a routine called modnam() and all developer names through another routine called develn().

        if (tfsopn("*.MDF") > 0) {
             while (tfsrdl() != TFSDUN) {
                  switch(tfstate) {
                  case TFSLIN:
                       if (tfspfx("Module Name:")) {
                            modnam(tfspst);
                       }
                       else if (tfspfx("Developer:")) {
                            develn(tfspst);
                       }
                       break;
                  }
             }
        }

Notice how one or more spaces may follow the colons in the .MDF files, but they are skipped by tfspst.

If you have multiple levels of prefixes, this routine might be handy:

tfsdpr(); strip the prefix off of tfsbuf and prepare for sub-prefixes (the dpr stands for “deeper”)

This routine is used in INTEGROU.C (Extended C Source Developer’s Kit) to isolate all of the Language lines in the .MDF files with one tfspfx() call, and then handle them individually with more tfspfx() calls on the sub-prefixes.

If you don’t need to exhaustively scan all of the file(s) (say you’re only interested in one occurrence of line starting with a certain prefix), you can abort scanning with tfsabt():

tfsabt(); abort text file scanning

This just makes sure that if a file is opened that it gets closed, which is usually a good idea. Otherwise, you need to keep calling tfsrdl() until it returns TFSDUN.

Disk I/O

bufptr=mdfgets(buffer,size,fp);
Read a line of text from a file

char *bufptr; copy of buffer

char *buffer; where to store the line

int size; maximum size, including ‘\0’

FILE *fp; file (from fopen())

This is just like the standard fgets(), except it uses \r as a line terminator (a hard carriage return on the Major BBS), and it won’t have a line terminator on the last line if the file doesn’t have it.

got=fgetstg(buffer,size,fp);
Read a nul-terminated string from file

int got; 1=got it ok, 0=error or eof

char *buffer; where to store the line

int size; maximum size, including \0

FILE *fp; file (from fopen())

This reads a nul-terminated string from what’s obviously not strictly an ASCII text file, and stores it in the buffer. The nul is stored too, but the string will never take up more than size bytes. If it’s too big, it will be truncated with a forced nul at buffer[size-1].

nbytes=getdfre(diskno); Find out how many bytes are free on disk

Applies to: WG3.x

Header check: getdfre() (WG2 GCOMM.H:255, a macro for dskfre()) is removed. dskfre() is #define dskfre v3dskfre and takes const CHAR *path instead of a drive number (FIOAPI.H:222-225; same change for clsize, FIOAPI.H:188-191).

long nbytes; number of bytes

int diskno; disk number (0=default 1=A: 2=B:)

cntdir(path); Count a set of files

char *path; path specification (wildcards ok)

long numfils; total number of files counted

long numbyts; total number of bytes counted

long numbytp; greater number of bytes occupied by the files, considering cluster size

drive=drvnum(path); Determine drive number from the path

Applies to: WG3.x

Header check: DSKUTL.H (drvnum, getdtd, gettnd, setdtd, settnd; WG2 DSKUTL.H:52-79) is not in WGDEV/INC.

int drive; 0=current, 1=A:, 2=B:, 3=C:,...

char *path; any DOS file specification

clbyts=clsize(drive); How big are the clusters on disk?

unsigned clbyts; number of bytes per cluster

int drive; 0=current, 1=A:, 2=B:, 3=C:,...

realsiz=clfit(siz,clbyts);
Total space used by a file

long realsiz; siz rounded up to the next cluster

long siz; useful size of file

unsigned clbyts; cluster size (from clsize())

ok=setdtd(fname,time,date);
Set the time and date for a file (file must not be open at the time)

int ok; 1=ok 0=couldn’t find file

char *fname; file path

int time; HHHHHMMMMMMSSSSS coding (see page 318)
int date; YYYYYYYMMMMDDDDD coding (see page 318)
 ok=settnd(fname,gmt70); Set the time and date for a file (file must not be open at the time)

int ok; 1=ok 0=couldn’t find file

char *fname; file path

long gmt70; Number of seconds since midnight 1/1/1970, GMT

timendate=getdtd(handle);
Get a file’s time & date

long timendate; 32-bit number encoding date<<16 and time:
HHHHHMMMMMMSSSSS coding (see page 318)
YYYYYYYMMMMDDDDD coding (see page 318)

int handle; file handle from an fopen()’d file (returned by fileno(fp))

gmt70=gettnd(handle); Get a file’s time & date

long gmt70; Number of seconds since midnight 1/1/1970, GMT

int handle; file handle from an fopen()’d file (returned by fileno(fp))

root=fnroot(filnam); Extract 1-8 char file root

Applies to: WG3.x

Header check: fnroot(), fnwext(), fnext(), filnpart() and pathpart() (WG2 GCOMM.H:378-380,512-513) are not declared in WG3.2 (FIOAPI.H has the file-name routines, e.g. fnmcse, normspec).

char *root; extension and path prefix removed

char *filnam; filename or entire file path

fnam=fnwext(filnam); Extract filename with extension

char *fnam; name after the path prefix

char *filnam; filename or entire file path

rsvd=rsvnam(filnam); Check if a DOS filename is reserved

int rsvd; 1=reserved, don’t use, 0=ok to use

char *filnam; filename or complete file path

This routine checks through the DOS list of device drivers and other reserved names to make sure a proposed filename will not be misinterpreted as a device. It’s a great idea to use this routine especially if the filename is something a user typed (even if it’s the Sysop user). Did you know that writing to PRN.TXT will output to your printer? Calling rsvnam("PRN.TXT") will return 1 and catch this and other disasters.

Find First Matching File, Find Next

The following routines can be used to find out if a file exists, or to get help from DOS with breaking down a wildcard file specification (such as *.EXE) into its component files:

yes=fnd1st(&fb,filespec,attr);
Any files in this filespec?

int yes; 1=one or more, 0=none

struct fndblk fb; findblock structure

char attr; attribute mask (see below)

yes=fndnxt(&fb); Any more files in this filespec?

int yes; 1=yes 0=no more

struct fndblk fb; same structure passed to fnd1st()

The fnd1st() and fndnxt() functions make use of the following data structure, defined in DOSCALLS.H:

        struct fndblk {              /* used by fnd1st,fndnxt in datntim.c    */
             char junk[21];          /*                                       */
             char attr;              /* file attribute (see masks below)      */
             unsigned time;          /* time in HHHHHMMMMMMSSSSS format       */
             unsigned date;          /* date in YYYYYYYMMMMDDDDD format       */
             long size;              /* size in bytes                         */
             char name[12+1];        /* name of file "FFFFFFFF.EEE"           */
        };

Applies to: WG3.x

Header check: there is no DOSCALLS.H and no struct fndblk in WGDEV/INC; fnd1st()/fndnxt() use struct ffblk (ff_reserved, ff_fsize, ff_attrib, ff_ftime, ff_fdate, ff_name[256], FIOAPI.H:37-44), and the time/date members are unsigned short. See the note in chapter 5.

After either routine returns 1, you can consult the name, size, date and time fields of the fb structure for information on the file.

The attr parameter to fnd1st() restricts the search to certain types of files (or more accurately directory entries — fnd1st() and fndnxt() are really directory scanning routines). Here are the possible bit components to the attr parameter of fnd1st(), and to the attr field of the fndblk structure. These are also defined in DOSCALLS.H:

        #define FAMRON 0x01        /* File attribute:  read only              */
        #define FAMHID 0x02        /* File attribute:  hidden                 */
        #define FAMSYS 0x04        /* File attribute:  system                 */
        #define FAMVID 0x08        /* File attribute:  volume id              */
        #define FAMDIR 0x10        /* File attribute:  sub-directory          */
        #define FAMARC 0x20        /* File attribute:  archive                */

The only useful values we ever found for the attr parameter of fnd1st() are 0, meaning roughly to scan for files only, not subdirectories or volume IDs, and FAMDIR, meaning to check if a given name exists as either a directory or a file. For example, if there is a file named SRC, fnd1st(&fb,"SRC",FAMDIR) will report that it exists even though you were anticipating it finding a directory by that name. To check, look at fb.attr for the FAMDIR flag. If set, it is a directory. If not set, it may be any of the other choices (volume id, hidden, etc.).

You can refer to a DOS technical manual on interrupt 21H, function 4EH, for details on the other bits.

Everything Else

cpu=cputype(); Returns 88, 186, 286, 386

Applies to: WG3.x

Header check: cputype() (WG2 GCOMM.H:357) is not declared in WG3.2.

int cpu; depending on what type of processor you run it on (486s and above return 386)

setcrit(); Set the DOS critical error handler to a routine that pops up a window and is loads more friendly than “Abort, Retry, Fail”. For real mode only — don’t use with Phar Lap.

pascrit(); Set the DOS critical error handler to a routine that retries three times then pops up a friendly window. Must run with the GSBL (Software Breakthrough).

Boolean Values Exchanged With Client Apps

Applies to: WG2+

In VB, True is -1 and False is 0. If ok is 1, the following line will work:

If ok Then

The following line won’t, though, if ok is 1 and ok2 is 2:

If ok and ok2 Then

The above line will evaluate to False (0). This is because 1 and 2 in VB is False, given that and is a bitwise operation. It’s important to keep boolean variables, although technically Integers, only containing True (-1) or False (0) values.

In C, TRUE is 1, FALSE is 0. VBTRUE is -1, though. Be sure that your agent always uses VBTRUE when sending a boolean variable to the client (and expects VBTRUE for boolean variables from the client).

Applies to: WG2+

Header check (GCOMM.H): #define VBTRUE 0xFFFF /* Visual Basic TRUE */ (the 16-bit pattern for -1).

Applies to: WG3.x

Header check (3.2): VBTRUE is ((GBOOL)(0xFFFF)) (GCOMM.H:199) and GBOOL is typedef short (GCTYPDEF.H:105), so in WG3.2 it evaluates to -1, not 65535.


Previous: Major BBS v10: 10 Offline Utilities  |  Contents  |  Next: Major BBS v10: 12 Reliability

  • No labels