Clipper is a trademark of Computer Associates and will often be referred to as CA-Cl*pper within Harbour documents. Regardless of this variant, Clipper is recognized as Computer Associates' trademark.
Harbour is a free software compiler for the xBase superset language often referred to as Clipper (the language that is implemented by the compiler Clipper). The goal of Harbour is to produce a cross platform CA-Cl*pper compatible compiler.
The Harbour website is at https://vszakats.github.io/harbour-core/. If you have any problem with this copy of Harbour please visit our web site and ensure that you are using the latest release.
If you are reading this file as part of a source distribution of Harbour you probably want to start by reading doc/dirstruc.txt because this is your map to the Harbour source directories.
Harbour is a superset of Clipper and is backwards compatible with nearly 100% of all Clipper 5.2x or 5.3 code. Most Clipper S'87 code will also compile and run fine, but may require some modifications to run well.
-k<mode> compilation mode (type -k? for more data)
-kc clear all flags (strict Clipper mode)
-kh Harbour mode (default)
-ko allow operator optimizations
-ki enable support for HB_INLINE (default)
-kr runtime settings enabled
-ks allow indexed assignment on all types
-kx extended Xbase++ mode (default)
-ku strings in user encoding
-kd accept macros with declared symbols
-km turn off macro-text substitution
-kj turn off jump optimization in pcode
-k? this info
-l suppress line number information
The compiler does not generate the source code line numbers in the output file. The ProcLine() function will return 0 for modules compiled using this option.
-m compile module only
-n[<type>] no implicit starting procedure
type: 0=no implicit starting procedure
1=no starting procedure at all 2=add starting procedure if necessary
The compiler does not create a procedure with the same name as the compiled file. This means that any declarations placed before the first PROCEDURE or FUNCTION statement have file- wide scope and can be accessed/used in all functions/procedures defined in the compiled source file. All executable statements placed at the beginning of the file and before the first PROCEDURE/FUNCTION statement are ignored.
-o<path> object file drive and/or path
-p generate pre-processed output .ppo file
The compiler only creates the file that contains the result of pre-processing the source file.
-p+ generate pre-processor trace .ppt file
-q quiet
The compiler does not print any messages during compiling (except the copyright info).
-q0 quiet and don't display program header
-q2 disable all output messages
-ql suppress line number information
-r[<lib>] request linker to search lib (or none)
Currently not supported in Harbour.
-r=<max> sets maximum number of preprocessor iterations
This set the maximum number of preprocessor iterations during processing the source code. If this switch is not used then the preprocessor stops after 1024 iterations. This value is used to stop processing of infinite loops, for example: #command ( => (,7
-s[m] syntax check only [minimal for dependencies list]
The compiler checks the syntax only. No output file is generated.
-t<path> path for temp file creation
Currently not used in Harbour (the Harbour compiler does not create any temporary files).
-u[<file>] use command def set in file (or none)
-u+<file> add command def set from file
-undef:<id>#undef <id>
-v variables are assumed M->
All undeclared or unaliased variables are assumed MEMVAR variables (private or public variables). If this switch is not used then the scope of such variables is checked at runtime.
-w[<level>] set warning level number (0..3, default 1)
-w0 - no warnings
-w or -w1 - CA-Cl*pper compatible warnings
-w2 - some useful warnings missed in CA-Cl*pper
-w3 - warnings generated for Harbour language extensions
and also enables strong type checking but only warns against declared types, or types which may be calculated at compile time
-x[<prefix>] set symbol init function name prefix (for .c only)
Sets the prefix added to the generated symbol init function name (in C output currently). This function is generated automatically for every PRG module compiled. This additional prefix can be used to suppress problems with duplicated symbols during linking an application with some third party libraries.
-z suppress shortcutting (.AND. & .OR.)
Compilation in batch mode.
@file compile list of modules in file
Not supported yet.
Known incompatibilities between Harbour and CA-Cl*pper compilers
Note:
If you want a 100% compatible runtime libraries then you have to define HB_CLP_STRICT, using HB_USER_CFLAGS=-DHB_CLP_STRICT, then rebuild.
Passing an undeclared variable by the reference
The CA-Cl*pper compiler uses the special opcode PUSHP to pass a reference to an undeclared variable (@ operator). The type of passed variable is checked at runtime (field or memvar). However, field variables cannot be passed by reference. This means that CA-Cl*pper checks the memvar variable only and doesn't look for a field. This is the reason why the Harbour compiler uses the usual PUSHMEMVARREF opcode in such cases. Notice that the runtime behavior is the same in CA-Cl*pper and in Harbour - only the generated opcodes are different.
Handling of object messages
The HB_CLP_STRICT setting determines the way chained send messages are handled.
For example, the following code:
a:b( COUNT() ):c += 1
will be handled as:
a:b( COUNT() ):c := a:b( COUNT() ):c + 1
in strict CA-Cl*pper compatibility mode and
temp := a:b( COUNT() ), temp:c += 1
in non-strict mode.
In practice, CA-Cl*pper will call the COUNT() function two times: the first time before addition and the second one after addition. In Harbour, COUNT() will be called only once, before addition.
The Harbour (non-strict) method is:
1) faster
2) it guarantees that the same instance variable of the same object will be changed
The above code compiles fine in CA-Cl*pper, but it generates a runtime error Error/BASE 1132 Bound error: array access Called form (b)STATICS$(0)
In Harbour this code generates a compile time error: Error E0009 Illegal variable (b) initializer: 'MyLocalVar'
Both CA-Cl*pper and Harbour are handling all local variables used in a codeblock in a special way: they are detached from the local stack of function/procedure where they are declared. This allows access to these variables after the exit from a function/procedure. However, all static variables are initialized in a separate procedure (STATICS$ in CA-Cl*pper and (_INITSTATICS) in Harbour) before the main procedure and before all INIT procedures. The local variables don't exist on the eval stack when static variables are initialized, so they cannot be detached.
CA-Cl*pper only allowed creation of objects from a few standard classes.
In Harbour, you can create your own classes—complete with Methods, Instance Variables, Class Variables and Inheritance. Entire applications can be designed and coded in Object Oriented style.
* @<FunctionName>()
Returns the pointer (address) to a function.
The returned value is not useful to application-level programming, but is used at a low-level to implement object oriented coding. (Internally, a class method is a static function and there is no symbol for it, so it is accessed via its address).
The garbage collector uses the following logic: - first collect all memory allocations that can cause garbage; - next scan all variables if these memory blocks are still referenced.
Notice that only arrays, objects and codeblocks are collected because these are the only datatypes that can cause self-references a[ 1 ] := a or circular references a[ 1 ] := b; b[ 1 ] := c; c[ 1 ] := a that cannot be properly deallocated by simple reference counting.
Since all variables in Harbour are stored inside some available tables (the eval stack, memvars table and array of static variables) then checking if the reference is still alive is quite easy and doesn't require any special treatment during memory allocation. Additionally the garbage collector is scanning some internal data used by Harbour objects implementation that also stores some values that can contain memory references. These data are used to initialize class instance variables and are stored in class shared variables.
In special cases when the value of a Harbour variable is stored internally in some static area (at C or assembler level), the garbage collector will be not able to scan such values since it doesn't know their location. This could cause some memory blocks to be released prematurely. To prevent the premature deallocation of such memory blocks the static data have to store a pointer to the value created with hb_itemNew() function. Example:
static HB_ITEM s_item; /* this item can be released by the GC */
static PHB_ITEM pItem; /* this item will be maintained correctly */
pItem = hb_itemNew( hb_param( 1, IT_BLOCK ) );
However, scanning of all variables can be a time consuming operation. It requires that all allocated arrays have to be traversed through all their elements to find more arrays. Also all codeblocks are scanned for detached local variables they are referencing. For this reason, looking for unreferenced memory blocks is performed during the idle states.
The idle state is a state when there is no real application code executed. For example, the user code is stopped for 0.1 of a second during Inkey( 0.1 ) - Harbour is checking the keyboard only during this time. It leaves however quite enough time for many other background tasks. One such background task can be looking for unreferenced memory blocks.
Allocating memory
The garbage collector collects memory blocks allocated with hb_gcAlloc() function calls. Memory allocated by hb_gcAlloc() should be released with hb_gcFree() function.
The garbage collecting
During scanning of unreferenced memory the GC is using a mark & sweep algorithm. This is done in three steps:
1) mark all memory blocks allocated by the GC with unused flag;
2) sweep (scan) all known places and clear unused flag for memory blocks that are referenced there;
3) finalize collecting by deallocation of all memory blocks that are still marked as unused and that are not locked.
To speed things up, the mark step is simplified by swapping the meaning of the unused flag. After deallocation of unused blocks all still alive memory blocks are marked with the same 'used' flag so we can reverse the meaning of this flag to 'unused' state in the next collecting. All new or unlocked memory blocks are automatically marked as 'unused' using the current flag, which assures that all memory blocks are marked with the same flag before the sweep step will start. See hb_gcCollectAll() and hb_gcItemRef()
Calling the garbage collector from Harbour code
The garbage collector can be called directly from the Harbour code. This is useful in situations where there is no idle states available or the application is working in the loop with no user interaction and there is many memory allocations. See hb_gcAll() for explanation of how to call this function from your Harbour code.
The idle state is the state of the Harbour virtual machine when it waits for the user input from the keyboard or the mouse. The idle state is entered during Inkey() calls currently. All applications that don't use Inkey() function call can signal the idle states with the call of hb_idleState() function (or hb_idleState() on C level).
During idle states the virtual machine calls the garbage collector and it can call user defined actions (background tasks). It also releases the CPU time slices for some poor platforms that are not smart enough to detect it automatically.
xFuncProc = Either a string with a function/procedure name to be called or a codeblock to evaluate.
xArguments = arguments passed to a called function/procedure or to a codeblock.
Returns
xRetVal A value that was returned from called function.
Description
This function can be called either by the Harbour compiler or by user. The compiler always passes the item of HB_IT_SYMBOL type that stores the name of procedure specified in DO <proc> WITH ... statement.
If called procedure/function doesn't exist then a runtime error is generated.
This function can be used as replacement of macro operator. It is also used internally to implement DO <proc> WITH <args...> In this case xFuncProc is of type HB_SYMB.
Examples
LOCAL cFunction := "MyFunc"
? Do( cFunction, 1 ) // Old style
DO &cFunction WITH 2 // Old style with macro
? Do( {| n | MyFunc( n ) }, 3 )
? Do( @MyFunc(), 4 )
FUNCTION MyFunc( n ) /* must be a public function for old style calls */
? n
RETURN n + 1
Gets the line number of the current function on the stack.
Syntax
ProcLine( <nLevel> ) → nLine
Arguments
nLevel is the function level required.
Returns
nLine The line number of the function that it is being executed.
Description
This function looks at the top of the stack and gets the current line number of the executed function if no arguments are passed. Otherwise it returns the line number of the function or procedure at nLevel.
Gets the name of the current function on the stack
Syntax
ProcName( <nLevel> ) → cProcName
Arguments
nLevel is the function level required.
Returns
cProcName The name of the function that it is being executed.
Description
This function looks at the top of the stack and gets the current executed function if no arguments are passed. Otherwise it returns the name of the function or procedure at nLevel.
Examples
// This test will show the functions and procedures in stack.
// before executing it.
LOCAL n := 1
DO WHILE ! Empty( ProcName( n ) )
? ProcName( n++ )
ENDDO
xValue if specified xValue, xValue will be returned, otherwise this function returns a NIL value.
Description
This function dynamically increases the length of the aArray by adding one new element to the end of the array and optionally stores the value xValue to that newly created element.
xValue may be of an data type, including an array reference pointer, which in turn may be stored to an array's subscript position.
Examples
LOCAL aArray := {}, tmp
AAdd( aArray, 10 )
FOR tmp := 1 TO 10
AAdd( aArray, tmp )
NEXT
? hb_ValToExp( aArray ) // --> { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
aDuplicate A new array pointer reference complete with nested array values.
Description
This function makes a complete copy of the array expressed as aSource and return a cloned set of array values. This provides a complete set of arrays values for all dimensions within the original array aSource
Examples
LOCAL aOne := { "Harbour", " is ", "POWER" }
LOCAL aTwo := AClone( aOne )
? hb_ValToExp( aTwo ) // --> { "Harbour", " is ", "POWER" }
aOne[ 1 ] := "The Harbour Compiler"
? hb_ValToExp( aOne ) // --> { "The Harbour Compiler", " is ", "POWER" }
? hb_ValToExp( aTwo ) // --> { "Harbour", " is ", "POWER" }
Status
Ready
Compliance
CA-Cl*pper will return NIL if the parameter is not an array.
nStart is the beginning subscript position to copy from aSource
nCount the number of subscript elements to copy from aSource.
nTargetPos the starting subscript position in aTarget to copy elements to.
Returns
aTarget an array pointer reference
Description
This function copies array elements from aSource to aTarget. nStart is the beginning element to be copied from aSource; the default is 1.
nCount is the number of elements to be copied from aSource; the default is the entire array. nTargetPos is the subscript number in the target array, aTarget, to which array elements are to be copied; the default is 1.
This function will copy all data types in aSource to aTarget. If an array element in aSource is a pointer reference to another array, that array pointer will be copied to aTarget; not all subdimensions will be copied from one array to the next. This must be accomplished via the AClone() function.
Note: If array aSource is larger then aTarget, array elements will start copying at nTargetPos and continue copying until the end of array aTarget is reached. The ACopy() function doesn't append subscript positions to the target array, the size of the target array aTarget remains constant.
Examples
LOCAL nCount := 2, nStart := 1
LOCAL aOne := { "Harbour", " is ", "Power" }
LOCAL aTwo := { "Clipper", " was ", "Power" }
ACopy( aOne, aTwo, nStart, nCount )
? hb_ValToExp( aTwo ) // --> { "Harbour", " is ", "Power" }
aArray Name of array from which an element is to be removed.
nPos Subscript of the element to be removed.
Returns
aArray an array pointer reference.
Description
This function deletes the element found at nPos subscript position in the array aArray. All elements in the array aArray below the given subscript position nPos will move up one position in the array.
In other words, what was formerly the sixth subscript position will become the fifth subscript position. The length of the array aArray will remain unchanged, as the last element in the array will become a NIL data type.
Note: To completely remove an element and decrease the length of array you can use hb_ADel() that supports auto-sizing.
bBlock Is a code block to evaluate for each element processed.
nStart The beginning array element index to evaluate.
nCount The number of elements to process.
Returns
aArray an array pointer reference.
Description
This function evaluates the elements of aArray, and executes for each of them the processing that's defined with bBlock. By default, all the elements of array are being processed, starting from 1st and up to the last element.
If nStart and/or nCount parameters are given, then the processing starts from nStart element and continues for the next nCount elements (if defined) or up to the last element of the array.
The bBlock code block receives two parameters: the element value and element's index (position) into the array. i.e. {| xValue, nIndex | ... } Worth to note that elements are passed to code block 'by value', thus any change being made to this value doesn't affects the value of element in the array.
Examples
LOCAL a := { 10, 20, 30 }
AEval( a, {| e, n | QOut( e * n + 1 , a[ n ] ) } )
? a[ 1 ], a[ 2 ], a[ 3 ] // array elements unchanged
? "----"
AEval( a, {| e, n | QOut( e * n + 1, a[ n ] *= n + 1 ) }, 2, 1 )
/* Here the 2nd element been changed, because we've explicitly used
its pointer 'a[ n ] *= ...' into array */
? a[ 1 ], a[ 2 ], a[ 3 ]
This function will fill each element of an array named aArray with the value xValue. If specified, nStart denotes the beginning element to be filled and the array elements will continue to be filled for nCount positions.
If neither nStart/nCount specified, the value of nStart will be 1, and the value of nCount will be the value of Len( <aArray> ); thus, all subscript positions in the array aArray will be filled with the value of xValue.
This function will work on only a single dimension of aArray. If there are array pointer references within a subscript aArray, those values will be lost, since this function will overwrite those values with new values.
Insert a NIL value at an array subscript position.
Syntax
AIns( <aArray>, <nPos> ) → aArray
Arguments
aArray Array name.
nPos Subscript position in aArray
Returns
a reference to aArray.
Description
This function inserts a NIL value in the array named aArray at the nPosth position.
All array elements starting with the nPosth position will be shifted down one subscript position in the array list and the last item in the array will be removed completely. In other words, if an array element were to be inserted at the fifth subscript position, the element previously in the fifth position would now be located at the sixth position. The length of the array aArray will remain unchanged.
Note: To avoid loosing last element, you can use hb_AIns() which supports auto-sizing of array.
nElements is the number of elements in the specified dimension.
Returns
aArray an array of specified dimensions.
Description
This function returns an uninitialized array with the length of nElements.
Nested arrays are uninitialized within the same array pointer reference if additional parameters are specified.
Establishing a memory variable with the same name as the array may destroy the original array and release the entire contents of the array. This depends, of course, on the data storage type of either the array or the variable with the same name as the array.
CA-Cl*pper v5.x compliant except that arrays in Harbour can have an unlimited number of elements.
Examples
LOCAL aArray := Array( 10 ), tmp
FOR tmp := 1 TO Len( aArray )
aArray[ tmp ] := Array( tmp )
NEXT
? hb_ValToExp( aArray ) // --> { { NIL }, { NIL, NIL }, ... }
nStart Beginning subscript position at which to start the search.
nCount Number of elements to scan with aTarget.
Returns
nStoppedAt A numeric value of subscript position where xSearch was found, or 0 if xSearch is not found.
Description
This function scan the content of array named aArray for the value of xSearch. The return value is the position in the array aArray in which xSearch was found. If it was not found, the return value will be 0.
nStart is the position from which to start scanning. The default is 1. (1st element) nCount, if specified, is the number of array elements to be scanned. The default is all elements in the array aArray.
If xSearch is a code block, the operation of the function is slightly different. Each array subscript pointer reference is passed to the code block to be evaluated. The scanning routine will continue until the value obtained from the code block is a logical true (.T.) or until the end of the array has been reached.
nLen Numeric value representing the new size (i.e. number of elements)
of aArray
Returns
The function returns a reference to aArray.
Description
This function will dynamically increase or decrease the size of aArray by adjusting the length of the array to nLen subscript positions.
If the length of the array aArray is shortened, the redundant elements are removed from the end of array. If the length of the array is lengthened the new elements are added to the end of array and they are assigned a NIL value.
nStart The first element to start the sort from, default is 1.
nCount Number of elements starting from nStart to sort, default
is all elements.
bSort Code block for sorting order, default is ascending order {| x, y | x < y }. The code block should accept two parameters and must return .T. if the sort is in order, .F. if not.
Returns
aArray reference to the now sorted aArray or NIL if the passed aArray is not an array.
Description
ASort() sort all or part of a given array. If bSort is omitted, the function expect aArray to be one dimensional array containing single data type (one of: Character, Date, Logical, Numeric) and sort this array in ascending order: Character are sorted by their ASCII value, Dates are sorted chronologically, Logical put .F. values before .T., Numeric are sorted by their value. If bSort is specified, it is used to handle the sorting order. With each time the block is evaluate, two array elements are passed to the code block, and bSort must return a logical value that state if those elements are in order (.T.) or not (.F.). Using this block you can sort multidimensional array, descending orders or even (but why would you want to do that) sort array that contain different data type.
Codeblock calling frequency and order differs from CA-Cl*pper, since Harbour uses a different (faster) sorting algorithm (quicksort).
aArray Name of array from which an element is to be removed.
nPos Subscript of the element to be removed. Default value: 1.
lAutoSize Boolean flag specifying if the array will be resized or not.
Default value: .F. (no resize).
Returns
aArray an array pointer reference.
Description
This function deletes the element value (not the element itself!) stored in position nPos and shifts all the following values, one position up.
If lAutoSize is .T., then the last element is removed and the size of the array is decreased by one, otherwise the length of the array remains unchanged and a NIL value will be stored in the last element, just like in ADel().
aArray The array name into which the value xValue will be inserted.
nPos Subscript position in aArray. Default: 1st position
xValue Value to be inserted
lAutoSize Boolean flag to increase or not the size of aArray.
Default value: .F.
Returns
A reference to array aArray
Description
This function inserts xValue in the nPos position of the array, moving all the items one position down in the array list. If lAutoSize is .T., a new element will be added at the end of array, making room for the previous last element, which means the length of array will be increased by 1.
If lAutoSize is .F. (or is not passed) the function behaves like AIns(), that is, the size of aArray won't change and the last item of aArray will be lost.
nStart Beginning subscript position at which to start the search.
Default value: 1
nCount Number of elements to be scanned within aArray.
Default value: All elements.
lExact Boolean flag specifying if an "Exact" search will be
performed or not. Default value: .F.
Returns
nPosition A numeric value > 0 indicating the array position where xSearch was found, or 0 if nothing found.
Description
The function scans (left to right) for xSearch into aArray and returns nPosition of aArray in which xSearch was found or 0 (zero) if nothing found.
If lExact is .T., then an exact search will be performed. When xSearch is a code block, the operation of the function is slightly different. See AScan() for details.
Examples
LOCAL a := { "there", "here" }
Set( _SET_EXACT, .F. )
? AScan( a, "he" ) // --> 2
? hb_AScan( a, "he",,, .F. ) // --> 2
? hb_AScan( a, "he",,, .T. ) // --> 0
oClass := HBClass():New( "TMyClass" )
-or-
HBClass() is usually accessed by defining a class with the commands
defined in hbclass.ch:
CREATE CLASS HBGetList // Calls HBClass() to create the HBGetList class
...
ENDCLASS
Returns
An instance of the HBClass() Class. This special object's :New() method can then create the classes you define.
Description
HBClass() is a class that ... The class methods are as follows:
:New() Create a new instance of the class
Examples
LOCAL oObject := HBClass():New( "TMyClass" )
oObject:End()
Status
Ready
Compliance
Object Oriented syntax in Harbour is compatible with CA-Cl*pper.
However CA-Cl*pper only allowed creation of objects from a few standard classes, and did not let the programmer create new classes.
In Harbour, you can create your own classes—complete with Methods, Instance Variables, Class Variables and Inheritance. Entire applications can be designed and coded in Object Oriented style.
Convert signed short encoded bytes into Harbour numeric
Syntax
Bin2I( <cBuffer> ) → nNumber
Arguments
cBuffer is a character string that contains 16-bit encoded signed short integer (least significant byte first). The first two bytes are taken into account, the rest if any are ignored.
Returns
Bin2I() return numeric integer (or 0 if cBuffer is not a string).
Description
Bin2I() is one of the low-level binary conversion functions, those functions convert between Harbour numeric and a character representation of numeric value. Bin2I() take two bytes of encoded 16-bit signed short integer and convert it into standard Harbour numeric value.
You might ask what is the need for such functions, well, first of all it allow you to read/write information from/to a binary file (like extracting information from DBF header), it is also a useful way to share information from source other than Harbour (C for instance).
Convert signed long encoded bytes into Harbour numeric
Syntax
Bin2L( <cBuffer> ) → nNumber
Arguments
cBuffer is a character string that contains 32-bit encoded signed long integer (least significant byte first). The first four bytes are taken into account, the rest if any are ignored.
Returns
Bin2L() return numeric integer (or 0 if cBuffer is not a string).
Description
Bin2L() is one of the low-level binary conversion functions, those functions convert between Harbour numeric and a character representation of numeric value. Bin2L() take four bytes of encoded 32-bit signed long integer and convert it into standard Harbour numeric value.
You might ask what is the need for such functions, well, first of all it allow you to read/write information from/to a binary file (like extracting information from DBF header), it is also a useful way to share information from source other than Harbour (C for instance).
Convert unsigned short encoded bytes into Harbour numeric
Syntax
Bin2W( <cBuffer> ) → nNumber
Arguments
cBuffer is a character string that contains 16-bit encoded unsigned short integer (least significant byte first). The first two bytes are taken into account, the rest if any are ignored.
Returns
Bin2W() return numeric integer (or 0 if cBuffer is not a string).
Description
Bin2W() is one of the low-level binary conversion functions, those functions convert between Harbour numeric and a character representation of numeric value. Bin2W() take two bytes of encoded 16-bit unsigned short integer and convert it into standard Harbour numeric value.
You might ask what is the need for such functions, well, first of all it allow you to read/write information from/to a binary file (like extracting information from DBF header), it is also a useful way to share information from source other than Harbour (C for instance).
Convert Harbour numeric into signed short encoded bytes
Syntax
I2Bin( <nNumber> ) → cBuffer
Arguments
nNumber is a numeric value to convert (decimal digits are ignored).
Returns
I2Bin() return two bytes character string that contains 16-bit encoded signed short integer (least significant byte first).
Description
I2Bin() is one of the low-level binary conversion functions, those functions convert between Harbour numeric and a character representation of numeric value. I2Bin() take a numeric integer value and convert it into two bytes of encoded 16-bit signed short integer.
You might ask what is the need for such functions, well, first of all it allow you to read/write information from/to a binary file (like extracting information from DBF header), it is also a useful way to share information from source other than Harbour (C for instance).
Convert Harbour numeric into signed long encoded bytes
Syntax
L2Bin( <nNumber> ) → cBuffer
Arguments
nNumber is a numeric value to convert (decimal digits are ignored).
Returns
L2Bin() return four bytes character string that contains 32-bit encoded signed long integer (least significant byte first).
Description
L2Bin() is one of the low-level binary conversion functions, those functions convert between Harbour numeric and a character representation of numeric value. L2Bin() take a numeric integer value and convert it into four bytes of encoded 32-bit signed long integer.
You might ask what is the need for such functions, well, first of all it allow you to read/write information from/to a binary file (like extracting information from DBF header), it is also a useful way to share information from source other than Harbour (C for instance).
This function converts double values to integers to use within the CALL command
Status
Ready
Compliance
The CA-Cl*pper NG states that Word() will only work when used in CALL commands parameter list, otherwise it will return NIL, in Harbour it will work anywhere.
Create a new database based on current database structure
Syntax
__dbCopyStruct( <cFileName>, [<aFieldList>] )
Arguments
cFileName is the name of the new database file to create. .dbf is the default extension if none is given.
aFieldList is an array where each element is a field name. Names could be specified as uppercase or lowercase.
Description
__dbCopyStruct() create a new empty database file with a structure that is based on the currently open database in this work-area. If aFieldList is empty, the newly created file would have the same structure as the currently open database. Else, the new file would contain only fields that exactly match aFieldList.
__dbCopyStruct() can be use to create a sub-set of the currently open database, based on a given field list.
COPY STRUCTURE command is preprocessed into __dbCopyStruct() function during compile time.
Examples
// Create a new file that contain the same structure
USE test
__dbCopyStruct( "mycopy.dbf" )
// Create a new file that contain part of the original structure
LOCAL aList
USE test
aList := { "NAME" }
__dbCopyStruct( "onlyname.dbf", aList )
Copy current database structure into a definition file
Syntax
__dbCopyXStruct( <cFileName> ) → lSuccess
Arguments
cFileName is the name of target definition file to create. .dbf is the default extension if none is given.
Returns
__dbCopyXStruct() returns .F. if no database is used in the current work-area, .T. on success, or a run-time error if the file create operation had failed.
Description
__dbCopyXStruct() create a new database named cFileName with a pre-defined structure (also called "structure extended file"):
Field name Type Length Decimals
FIELD_NAME C 10 0
FIELD_TYPE C 1 0
FIELD_LEN N 3 0
FIELD_DEC N 3 0
Each record in the new file contains information about one field in the original file. CREATE FROM could be used to create a database from the structure extended file.
For prehistoric compatibility reasons, Character fields which are longer than 255 characters are treated in a special way by writing part of the length in the FIELD_DEC according to the following formula (this is done internally):
COPY STRUCTURE EXTENDED command is preprocessed into __dbCopyXStruct() function during compile time.
Examples
// Open a database, then copy its structure to a new file,
// Open the new file and list all its records
USE test
__dbCopyXStruct( "teststru" )
USE teststru
LIST
cFileName is the target file name to create and then open. .dbf is the default extension if none is given.
cFileFrom is an optional structure extended file name from which the target file cFileName is going to be built. If omitted, a new empty structure extended file with the name cFileName is created and opened in the current work-area.
cRDDName is RDD name to create target with. If omitted, the default RDD is used.
lNew is an optional logical expression, (.T.) opens the target file name cFileName in the next available unused work-area and makes it the current work-area. (.F.) opens the target file in the current work-area. Default value is (.F.). The value of lNew is ignored if cFileFrom is not specified.
cAlias is an optional alias to USE the target file with. If not specified, alias is based on the root name of cFileName.
Returns
__dbCreate() returns (.T.) if there is database used in the current work-area (this might be the newly selected work-area), or (.F.) if there is no database used. Note that on success a (.T.) would be returned, but on failure you probably end up with a run-time error and not a (.F.) value.
Description
__dbCreate() works in two modes depending on the value of cFileFrom:
1) If cFileFrom is empty or not specified a new empty structure extended file with the name cFileName is created and then opened in the current work-area (lNew is ignored). The new file has the following structure:
Field name Type Length Decimals
FIELD_NAME C 10 0
FIELD_TYPE C 1 0
FIELD_LEN N 3 0
FIELD_DEC N 3 0
The CREATE command is preprocessed into the __dbCopyStruct() function during compile time and uses this mode.
2) If cFileFrom is specified, it is opened and assumed to be a structure extended file where each record contains at least the following fields (in no particular order): FIELD_NAME, FIELD_TYPE, FIELD_LEN and FIELD_DEC. Any other field is ignored. From this information the file cFileName is then created and opened in the current or new work-area (according to lNew), if this is a new work-area it becomes the current.
For prehistoric compatibility reasons, structure extended file Character fields which are longer than 255 characters should be treated in a special way by writing part of the length in the FIELD_DEC according to the following formula:
lExport If set to .T., copies records to a delimited file. If set to .F., append records from a delimited file.
xcFile The name of the text file to copy to or append from. If a file extension is not specified, ".txt" is used by default.
xcDelim Either the character to use as the character field delimiter (only the first character is used). or "BLANK" (not case sensitive), which eliminates the character field delimiters and sets the field separator to a single space instead of a comma.
aFields An array of field names to limit the processing to. If not specified, or if empty, then all fields are processed.
bFor An optional code block containing a FOR expression that will reduce the number of records to be processed.
bWhile An optional code block containing a WHILE expression that will reduce the number of records to be processed.
nNext If present, but nRecord is not present, specifies to process this number of records, starting with the current record. A value of 0 means to process no records.
nRecord If present, specifies the only record to process. A value of 0 means to process no records. Overrides nNext and lRest.
lRest If lExport is .T., then if lRest is set to .T. and there are no nRecord, nNext, or bWhile arguments, processes all records from current to last.
Description
__dbDelim() copies all or selected contents of a database table to an SDF text file or appends all or selected contents of an SDF text file to a database table.
Examples
// Copy delinquent accounts into a delimited text file.
USE accounts NEW
COPY TO overdue DELIMITED FOR ! Empty( accounts->duedate ) ;
.AND. Date() - accounts->duedate > 30
// Import new customer records.
USE customer NEW
APPEND FROM customer DELIMITED
lExport If set to .T., copies records to an SDF file. If set to .F., append records from an SDF file.
xcFile The name of the text file to copy to or append from. If a file extension is not specified, ".txt" is used by default.
aFields An array of field names to limit the processing to. If not specified, or if empty, then all fields are processed.
bFor An optional code block containing a FOR expression that will reduce the number of records to be processed.
bWhile An optional code block containing a WHILE expression that will reduce the number of records to be processed.
nNext If present, but nRecord is not present, specifies to process this number of records, starting with the current record. A value of 0 means to process no records.
nRecord If present, specifies the only record to process. A value of 0 means to process no records. Overrides nNext and lRest.
lRest If lExport is .T., then if lRest is set to .T. and there are no nRecord, nNext, or bWhile arguments, processes all records from current to last.
Description
__dbSDF() copies all or selected contents of a database table to an SDF text file or appends all or selected contents of an SDF text file to a database table.
Examples
// Copy delinquent accounts into an SDF text file.
USE accounts NEW
COPY TO overdue SDF FOR ;
! Empty( accounts->duedate ) .AND. ;
Date() - accounts->duedate > 30
// Import new customer records.
USE customer NEW
APPEND FROM customer SDF
aStruct is a multidimensional array with database fields structure, which is usually the output from dbStruct(), where each array element has the following structure:
Position Description dbstruct.ch
1 cFieldName DBS_NAME
2 cFieldType DBS_TYPE
3 nFieldLength DBS_LEN
4 nDecimals DBS_DEC
aFieldList is an array where each element is a field name. Names could be specified as uppercase or lowercase.
Returns
__dbStructFilter() return a new multidimensional array where each element is in the same structure as the original aStruct, but the array is built according to the list of fields in aFieldList. If aFieldList is empty, __dbStructFilter() return reference to the original aStruct array.
Description
__dbStructFilter() can be use to create a sub-set of a database structure, based on a given field list.
Note that field names in aStructmust be specified in uppercase or else no match would be found.
__dbStructFilter() is a Harbour extension. CA-Cl*pper has an internal undocumented function named __FLedit() that does exactly the same thing. The new name gives a better description of what this function does.
aStruct is a multidimensional array with database fields structure, which is usually the output from dbStruct(), where each array element has the following structure:
Position Description dbstruct.ch
1 cFieldName DBS_NAME
2 cFieldType DBS_TYPE
3 nFieldLength DBS_LEN
4 nDecimals DBS_DEC
aFieldList is an array where each element is a field name. Names could be specified as uppercase or lowercase.
Returns
__FLedit() return a new multidimensional array where each element is in the same structure as the original aStruct, but the array is built according to the list of fields in aFieldList. If aFieldList is empty, __FLedit() return reference to the original aStruct array.
Description
__FLedit() can be use to create a sub-set of a database structure, based on a given field list.
Note that field names in aStructmust be specified in uppercase or else no match would be found.
SET EXACT has no effect on the return value.
__FLedit() is a compatibility function and it is synonym for __dbStructFilter() which does exactly the same.
CA-Cl*pper has internal undocumented function named __FLedit(), in Harbour we name it __dbStructFilter(). The new name gives a better description of what this function does. In Harbour __FLedit() simply calls __dbStructFilter() and therefor the latter is the recommended function to use.
This function is only visible if src/rdd/dbstrux.prg was compiled with the HB_CLP_UNDOC flag.
nFields Number of fields in a database or work area
Description
This function will fill a series of arrays with field names, field types, field lengths, and number of field decimal positions for the currently selected or designed database. Each array parallels the different descriptors of a file's structure. The first array will consist of the names of the fields in the current work area. All other arrays are optional and will be filled with the corresponding data. This function will return zero if no parameters are specified or if no database is available in the current work area. Otherwise, the number of fields or the length of the shortest array argument, whichever is smaller, will be returned.
AFields() is a compatibility function, it is superseded by dbStruct() which returns one multidimensional array.
NOTE: The destination arrays must be initialized to a given size,
This function determines if the beginning of the file marker has been reached. If so, the function will return a logical true (.T.); otherwise, a logical false (.F.) will be returned. By default, Bof() will apply to the currently selected database unless the function is preceded by an alias
Examples
USE test NEW
? "Is Bof()", Bof()
dbGoTop()
DO WHILE ! Bof()
dbSkip( -1 )
ENDDO
? "Is Bof()", Bof()
This function add a new record to the end of the database in the selected or aliased work area. All fields in that database will be given empty data values - character fields will be filled with blank spaces, date fields with hb_SToD(), numeric fields with 0, logical fields with .F., and memo fields with NULL bytes. The header of the database is not updated until the record is flushed from the buffer and the contents are written to the disk.
Under a networking environment, dbAppend() performs an additional operation: It attempts to lock the newly added record. If the database file is currently locked or if a locking assignment is made to LastRec() + 1, NetErr() will return a logical true (.T.) immediately after the dbAppend() function. This function does not unlock the locked records.
If lLock is passed a logical true (.T.) value, it will release the record locks, which allows the application to maintain multiple record locks during an appending operation. The default for this parameter is a logical false (.F.).
Examples
LOCAL cName := "Harbour", nAge := 15
USE test
test->( dbAppend() )
test->first := cName
test->age := nAge
This function close all open databases and all associated indexes. In addition, it closes all format files and moves the work area pointer to the first position
Examples
USE test NEW
dbEdit()
USE test1 NEW
dbEdit()
dbCloseAll()
Updates all index and database buffers for a given work area
Syntax
dbCommit()
Description
This function updates all of the information for a give, selected, or active work area. This operation includes all database and index buffers for that work area only. This function does not update all open work areas.
Examples
LOCAL GetList := {}
LOCAL cName := Space( 40 )
LOCAL nAge := 0
USE test EXCLUSIVE NEW
@ 10, 10 GET cName
@ 11, 10 GET nAge
READ
IF Updated()
dbAppend()
test->first := cName
test->age := nAge
dbCommit()
ENDIF
Flushes the memory buffer and performs a hard-disk write
Syntax
dbCommit()
Description
This function performs a hard-disk write for all work areas. Before the disk write is performed, all buffers are flushed. open work areas.
Examples
// FIXME
LOCAL GetList := {}
LOCAL cName := Space( 40 )
LOCAL nId := 0
USE test EXCLUSIVE NEW
USE testid NEW INDEX testid
@ 10, 10 GET cName
@ 11, 10 GET nId
READ
IF Updated()
dbAppend()
test->first := cName
test->Id := nId
IF ! testid->( dbSeek( nId ) )
testid->( dbAppend() )
testid->Id := nId
ENDIF
ENDIF
dbCommitAll()
aStruct Name of a multidimensional array that contains the
database structure
cRDD Name of the RDD
lKeepOpen 3-way toggle to Open the file in New or Current work area:
NIL The file is not opened.
True It is opened in a New area.
False It is opened in the current area.
cAlias Name of database Alias
Description
This function creates the database file specified as cDatabase from the multidimensional array aStruct. If no file extension is use with cDatabase the .dbf extension is assumed. The array specified in aStruct must follow a few guidelines when being built prior to a call to dbCreate():
- All subscripts values in the second dimension must be set to proper values
- The fourth subscript value in the second dimension - which contains
the decimal value-must he specified. even 1kw non-numeric fields.
- The second subscript value in the second dimension-which contains
the field data type-must contain a proper value: C, D, L, M or N It is possible to use additional letters for clarity (e.g., 'Numeric' for 'N'): however, the first letter of this array element must be a proper value.
The dbCreate() function does not use the decimal field to calculate the length of a character held longer than 256. Values up to the maximum length of a character field (which is 65519 bytes) are stored directly in the database in the length attribute if that database was created via this function. However, a file containing fields longer than 256 bytes is not compatible with any interpreter.
The cRDD parameter specifies the name of the Replaceable Database Driver to use to create the database. If it is not specified, then the Replaceable Database Driver in the current work area is used.
The lKeepOpen parameter specifies if the already created database is to be opened, and where. If NIL, the file is not opened. If True, it is opened in a New area, and if False it is opened in the current area (closing any file already occupying that area). The cAlias parameter specifies the alias name for the new opened database.
This function marks a record for deletion in the selected or aliased work area. If the DELETED setting is on, the record will still be visible until the record pointer in that work area is moved to another record.
In a networking situation, this function requires that the record be locked prior to issuing the dbDelete() function.
Examples
LOCAL nAge := 50
USE test NEW
INDEX ON field->age TO test
IF dbSeek( nAge ) .AND. RLock()
dbDelete()
ENDIF
This function return the expression of the SET FILTER TO command for the current or designated work area. If no filter condition is present, a null string will be returned.
Examples
USE test INDEX test NEW
SET FILTER TO field->first = "Harbour"
USE testid INDEX testid NEW
SET FILTER TO field->age == 25
SELECT test
? dbFilter()
? testid->( dbFilter() )
Moves the record pointer to the bottom of the database.
Syntax
dbGoBottom()
Description
This function moves the record pointer in the selected or aliased work area to the end of the file. The position of the record pointer is affected by the values in the index key or by an active FILTER condition. Otherwise, if no index is active or if no filter condition is present, the value of the record pointer will be LastRec().
Examples
USE test
dbGoTop()
? RecNo()
dbGoBottom()
? RecNo()
Position the record pointer to a specific location.
Syntax
dbGoto( <xRecordNumber> )
Arguments
xRecordNumber Record number or unique identity
Description
This function places the record pointer, if working with a .dbf file, in selected or aliased work area at the record number specified by xRecordNumber. The position is not affected by an active index or by any environmental SET condition.
The parameter xRecordNumber may be something other than a record number. In some data formats, for example, the value of xRecordNumber is a unique primary key while in other formats, xRecordNumber could be an array offset if the data set was an array.
Issuing a dbGoto( RecNo() ) call in a network environment will refresh the database and index buffers. This is the same as a dbSkip( 0 ) call.
Examples
// The following example uses dbGoto() to iteratively process
// every fourth record:
dbUseArea( .T., "DBFNTX", "sales", "sales", .T. )
// toggle every fourth record
DO WHILE ! Eof()
dbGoto( RecNo() + 4 )
sales->Group := "Bear"
ENDDO
Moves the record pointer to the top of the database.
Syntax
dbGoTop()
Description
This function moves the record pointer in the selected or aliased work area to the top of the file. The position of the record pointer is affected by the values in the index key or by an active FILTER condition. Otherwise, if no index is active or if no filter condition is present, the value of RecNo() will be 1.
Examples
USE test
dbGoTop()
? RecNo()
dbGoBottom()
? RecNo()
This function unmarks those records marked for deletion and reactivates them in the aliased or selected work area. If a record is DELETED and the DELETED setting is on, the record will still be visible for a dbRecall() provided that the database record pointer has not been skipped. Once a record marked for deletion with the DELETE setting ON has been skipped, it no longer can be brought back with dbRecall().
Examples
USE test NEW
dbGoto( 10 )
dbDelete()
? Deleted()
dbRecall()
? Deleted()
dbRLock() returns a logical true (.T.) if lock was successful
Description
This function attempts to lock a record which is identified by xIdentity in the active data set. If the lock is successful the function will return a logical true (.T.) value; otherwise a logical false (.F.) will be returned. If xIdentity is not passed it will be assumed to lock the current active record/data item.
Examples
LOCAL nRecNo
USE test NEW
FOR nRecNo := 1 TO LastRec()
IF ! dbRLock()
dbUnlock()
ENDIF
NEXT
This function return a list of locked records in the database work area
Syntax
dbRLockList() → aRecordLocks
Returns
aRecordList is an array of lock records
Description
This function will return an array of locked records in a given and active work area. If the return array is an empty array (meaning no elements in it), then there are no locked records in that work area.
Examples
LOCAL nRecNo
USE test NEW
dbGoto( 10 )
? RLock()
dbGoto( 100 )
? RLock()
FOR EACH nRecNo IN dbRLockList()
? nRecNo
NEXT
xIdentity Record identifier, typically a record number
Description
This function will attempt to unlock the record specified as xIdentity, which in a .dbf format is the record number. If not specified, them the current active record/data item will be unlocked
Examples
USE test NEW
dbGoto( 10 )
IF RLock()
? test->age
dbRUnlock()
ENDIF
lFindLast is an optional logical value that set the current record position to the last record if successful
Returns
dbSeek() returns logical true (.T.) if found, otherwise false
Description
This function searches for the first record in a database file whose index key matches expKey. If the item is found, the function will return a logical true (.T.), the value of Found() will be a logical true (.T.), and the value of Eof() will be a logical false (.F.). If no item is found. then the function will return a logical false, the value of Found() will be a logical false (.F.), and the value of Eof() will be a logical true (.T.).
This function always "rewinds" the database pointer and starts the search from the top of the file.
If the SOFTSEEK flag is on or if lSoftSeek is set to a logical true (.T.) the value of Found() will be a logical false and Eof() will be false if there is an item in the index key with a greater value than the key expression expKey; at this point the record pointer will position itself on that record. However, if there is no greater key in the index, Eof() will return a logical true (.T.) value. If lSoftSeek is not passed, the function will look to the internal status of SOFTSEEK before performing the operation. The default of lSoftSeek is a logical false (.F.)
Examples
PROCEDURE Main()
LOCAL nAge
USE test NEW
INDEX ON field->age TO test
dbGoto( 10 )
nAge := test->age
dbGoTop()
IF dbSeek( nAge )
? test->first
ENDIF
RETURN
STATIC PROCEDURE EmployeeLookup()
LOCAL cName
ACCEPT "Employee name: " TO cName
IF Employee->( dbSeek( cName ) )
Employee->( ViewRecord() )
ELSE
? "Not found"
ENDIF
RETURN
STATIC PROCEDURE ViewRecord()
? field->name
RETURN
This function moves the Harbour internal primary focus to the work area designated by xArea. If xArea is numeric, then it will select the numeric work area; if xArea is character, then it will select the work area with the alias name.
dbSelectArea( 0 ) will select the next available and unused work area. Up to 65534 work areas are supported. Each work area has its own alias and record pointer, as well as its own Found(), dbFilter(), dbRSelect() and dbRelation() function values.
Examples
LOCAL nAge
USE test NEW
COPY TO test1
USE test1 NEW
INDEX ON field->age TO test1
dbSelectArea( "test" )
dbGoto( 100 )
? nAge := field->age
dbSelectArea( "test1" )
IF dbSeek( nAge )
? field->first
ENDIF
Establishes the RDD name for the selected work area
Syntax
dbSetDriver( [<cDriver>] ) → cCurrentDriver
Arguments
cDriver Optional database driver name
Returns
dbSetDriver() returns the name of active driver
Description
This function returns the name of the current database driver for the selected work area. The default will be "DBFNTX". If specified, cDriver contains the name of the database driver that should be used to activate and manage the work area. If the specified driver is not available, this function will have no effect.
bCondition Code block expression for filtered evaluation.
cCondition Optional character expression of code block.
Description
This function masks a database so that only those records that meet the condition prescribed by the expression in the code block bCondition and literally expressed as cCondition are visible. If cCondition is not passed to this function, then the dbFilter() function will return an empty string showing no filter in that work area which in fact, would be not correct.
Examples
USE test NEW
dbSetFilter( {|| test->age > 30 }, "test->age > 30" )
dbGoTop()
? RecNo()
Moves the record pointer in the selected work area.
Syntax
dbSkip( [<nRecords>] )
Arguments
nRecords Numbers of records to move record pointer.
Description
This function moves the record pointer nRecords in the selected or aliased work area. The default value for nRecords will be 1. A dbSkip( 0 ) will flush and refresh the internal database buffer and make any changes made to the record visible without moving the record pointer in either direction.
Examples
USE test NEW
dbGoTop()
DO WHILE ! Eof()
? test->age, test->first
dbSkip()
ENDDO
Creates a multidimensional array of a database structure.
Syntax
dbStruct() → aStruct
Returns
dbStruct() returns an array pointer to database structure
Description
This function returns a multidimensional array. This array has array pointers to other arrays, each of which contains the characteristic of a field in the active work area. The length of this array is based in the number of fields in that particular work area. In other words, Len( dbStruct() ) is equal to the value obtained from FCount(). Each subscript position
Examples
#include "dbstruct.ch"
LOCAL field
USE test NEW
FOR EACH field IN dbStruct()
? field[ DBS_NAME ]
NEXT
This function releases the file or record lock in the currently selected or aliased work area. It will not unlock an associated lock in a related databases.
Examples
LOCAL nAge := 30
USE test NEW
INDEX ON field->age TO test
IF test->( dbSeek( nAge ) )
IF test->( RLock() )
dbDelete()
ELSE
dbUnlock()
ENDIF
ENDIF
Unlocks all records and releases all file locks in all work areas.
Syntax
dbUnlockAll()
Description
This function will remove all file and record locks in all work area.
Examples
LOCAL nAge := 50
USE test NEW
INDEX ON field->age TO test
IF test->( dbSeek( nAge ) )
IF test->( RLock() )
dbDelete()
ELSE
dbUnlock()
ENDIF
ELSE
dbUnlockAll()
ENDIF
lNewArea A optional logical expression for the new work area
cDriver Database driver name
cName File Name
xcAlias Alias name
lShared Shared/exclusive status flag
lReadonly Read-write status flag.
Description
This function opens an existing database named cName in the current work area. If lNewArea is set to a logical true (.T.) value, then the database cName will be opened in the next available and unused work area. The default value of lNewArea is a logical false (.F.). If used, cDriver is the name of the database driver associated with the file cName that is opened. The default for this will be the value of dbSetDriver().
If used, xcAlias contains the alias name for that work area, If not specified, the root name of the database specified in cName will be used.
If lShared is set to a logical true (.T.) value, the database that is specified in cName will be opened by the user exclusively. Thus locking it from all other nodes or users on the network. If lShared is set to a logical false (.F.) value, then the database will be in SHARED mode. If lShared is not passed, then the function will turn to the internal setting of SET EXCLUSIVE to determine a setting.
If lReadOnly is specified, the file will be set to read only mode. If it is not specified, the file will he opened in normal read-write mode.
Deleted() return a logical true (.T.) or false (.F.).
Description
This function returns a logical true (.T.) if the current record in the selected or designated work area has been marked for deletion. If not, the function will return a logical false (.F.).
Examples
USE test NEW
dbGoto( 10 )
dbDelete()
? "Is Record Deleted", test->( Deleted() )
dbRecall()
This function determines if the end-of-file marker has been reached. If it has, the function will return a logical true (.T.); otherwise a logical false (.F.) will be returned
Examples
USE test NEW
dbGoTop()
? "Is Eof()", Eof()
dbGoBottom()
DO WHILE ! Eof()
dbSkip()
ENDDO
? "Is Eof()", Eof()
Counts the number of fields in an active database.
Syntax
FCount() → nFields
Returns
nFields Return the number of fields
Description
This function returns the number of fields in the current or designated work area. If no database is open in this work area, the function will return 0.
Examples
USE test NEW
? "This database has", hb_ntos( test->( FCount() ) ), "field(s)"
This function returns the value of the field at the nFieldth location in the selected or designed work area. If the value in nField does not correspond to n available field position in this work area, the function will return a NIL data type.
Return the name of a field at a numeric field location.
Syntax
FieldName()/Field( <nPosition> ) → cFieldName
Arguments
nPosition Field order in the database.
Returns
cFieldName returns the field name.
Description
This function return the name of the field at the nPositionth position. If the numeric value passed to this function does not correspond to an existing field in the designated or selected work area, this function will return a NULL byte.
Examples
LOCAL nField
USE test NEW
FOR nField := 1 TO test->( FCount() )
? "Field Name:", FieldName( nField )
NEXT
This function return the ordinal position of the specified field cField in the current or aliased work area. If there isn't field under the name of cField or of no database is open in the selected work area, the function will return a 0.
expAssign Expression to be assigned to the specified field
Returns
ValueAssigned Any expression
Description
This function assigns the value in expAssing to the nFieldth field in the current or designated work area. If the operation is successful, the return value of the function will be the same value assigned to the specified field. If the operation is not successful, the function will return a NIL data type
lSuccess A true (.T.) value, if the lock was successful; otherwise false (.F.)
Description
This function returns a logical true (.T.) if a file lock is attempted and is successfully placed on the current or designated database. This function will also unlock all records locks placed by the same network station.
Examples
LOCAL nSum
USE test NEW
IF FLock()
SUM test->age TO nSum
? nSum
ENDIF
Determine the success of a previous search operation.
Syntax
Found() → lSuccess
Arguments
(This function has no arguments)
Returns
lSuccess A logical true (.T.) is successful; otherwise, false (.F.)
Description
This function is used to test if the previous SEEK, LOCATE, CONTINUE, or FIND operation was successful. Each work area has its own Found() flag, so that a Found() condition may be tested in unselected work areas by using an alias.
Examples
LOCAL nAge := 40
USE test NEW
INDEX ON field->age TO test
SEEK nAge
IF Found()
? test->first
ENDIF
nBytes The numeric size of a database file header in bytes
Description
This function returns the number of bytes in the header of the selected database of the database in the designated work area.
If used in conjunction with the LastRec(), RecSize() and DiskSpace() functions, this functions is capable of implementing a backup and restore routine.
Returns the file extension of the index module used in an application
Syntax
IndexExt() → cExtension
Arguments
None.
Returns
cExtension Current driver file extension
Description
This function returns a string that tells what indexes are to be used or will be created in the compiled application. The default value is .ntx. This is controlled by the particular database driver that is linked with the application.
Examples
IF IndexExt() == ".ntx"
? "Current driver being used is DBFNTX"
ENDIF
Yields the key expression of a specified index file.
Syntax
IndexKey( <nOrder> ) → cIndexKey
Arguments
nOrder Index order number
Returns
cIndexKey The index key
Description
This function returns a character string stored in the header of the index file
The index key is displayed for an index file that is designated by nOrder, its position in the USE...INDEX or SET INDEX TO command in the currently selected or designated work area. If there is no corresnponding index key at the specified order position, a NULL byte will be returned.
Examples
USE test NEW
INDEX ON field->first TO test
? IndexKey( 1 )
Returns the numeric position of the controlling index.
Syntax
IndexOrd() → nPosition
Arguments
None.
Returns
nPosition Ordinal position of a controling index
Description
The IndexOrd() function returns the numeric position of the current controlling index in the selected or designated work area. A returned value of 0 indicated that no active index is controlling the database, which therefore is in the natural order.
Examples
USE test NEW
INDEX ON field->first TO test
IF IndexOrd() > 0
? "Current order is", hb_ntos( IndexOrd() )
ENDIF
Returns the number of records in an active work area or database.
Syntax
LastRec() | RecCount()* → nRecords
Returns
nRecords The number of records
Description
This function returns the number of records present in the database in the selected or designated work area. If no records are present the value of this function will be 0. Additionally, if no database is in use in the selected or designated work area, this function will return a 0 value as well.
This function returns the date recorded by the OS when the selected or designated database was last written to disk. This function will only work for those database files in USE.
lError A value based on the success of a network operation or function.
Description
This function return a logical true (.T.) is a USE, dbAppend(), or a USE...EXCLUSIVE command is issue and fails in a network environment. In the case of USE and USE...EXCLUSIVE commands, a NetErr() value of .T. would be returned if another node of the network has the exclusive use of a file. And the case of the dbAppend() command, NetErr() will return a logical true (.T.) if the file or record is locked by another node or the value of LastRec() has been advanced The value of NetErr() may be changed via the value of lNewError. This allow the run-time error-handling system to control the way certain errors are handled.
Examples
USE test NEW
IF ! NetErr()
INDEX ON field->first TO test
SET INDEX TO test
test->first := "Harbour"
IF dbSeek( "Harbour" )
? test->first
ENDIF
ENDIF
nOrder A numeric value representing the Order bag number.
cOrderName The character name of the Order Bag.
Returns
ordBagName() returns the Order bag name
Description
This function returns the name of the order bag for the specified work area. If nOrder is specidied, it will represent the position in the order list of the target order. If cOrderName is specified, it will represent the name of the target order. In essence, it will tell the name of the database (if That RDD is in use) for a given index name or index order number. If cOrderName is not specified or nOrder is 0, the Current active order will be used.
Examples
USE test VIA "DBFCDX" NEW
SET INDEX TO test
? ordBagName( "TeName" ) // --> "Customer"
? ordBagName( "TeLast" ) // --> "Customer"
? ordBagName( "teZip" ) // --> "Customer"
ordSetFocus( "TeName" )
? ordBagName() // --> "Custumer"
cForCondition is a string that specifies the FOR condition for the order.
bForCondition is a code block that defines a FOR condition that each record within the scope must meet in order to be processed. If a record does not meet the specified condition, it is ignored and the next record is processed. Duplicate keys values are not added to the index file when a FOR condition is Used.
cOrderBagName Name of the file that contains one or more Orders.
cOrderName Name of the order to be created.
cExpKey Key value for order for each record in the current work area
bExpKey Code block that evaluates to a key for the order for each record in the work area.
lUnique Toggle the unique status of the index.
Description
This function creates an order for the current work area. It is similar to the dbCreateIndex() except that this function allows different orders based on the RDD in effect. The name of the file cOrderBagName or the name of the order cOrderName are technically both considered to be "optional" except that at least one of two must exist in order to create the order.
The parameter cExpKey is the index key expression; typically in a .dbf driver, the maximum length of the key is 255 characters.
If bExpKey is not specified, then the code block is create by macro expanding the value of cExpKey.
If lUnique is not specified, then the current internal setting of SET UNIQUE ON or OFF will be observed.
The active RDD driver determines the capacity in the order for a specific order bag.
If the name cOrderBagName is found in the order bag can contain a single order, the the name cOrderBagName is erased and a new order is added to the order list in the current or specified work area.On the other hand, if it can contain multiples tags and if cOrderBagName does not already exist in the order list, then it is added. It is does exist, then the cOrderBagName replaces the former name in the order list in the current or specified work area.
Examples
USE test VIA "DBFNTX"
? ordCreate( "FNAME",, "field->first" )
USE test VIA "DBFCDX"
? ordCreate( , "LNAME", "field->last" )
cOrderBagName Name of the order bag from which order id to be removed
Description
This function attempts to remove the order named cOrderName from the file containing the order bag name cOrderBagName. If cOrderBagName is not specified, then the name of the file will be based on the value of the ordName() function. If the extension is not included with the name of the order file, then the extension will be obtained from the default extension of the current and active RDD.
The DBFNTX driver do not support multiple order bags; therefore, there cannot be an order to "destroy" from a bag. This function only works for those drivers with support multiple orders bags (e.q. DBFCDX and RDDADS drivers).
Examples
USE test VIA "DBFCDX" NEW
? ordDestroy( "lName", "test" )
xOrder It the name of the target order, or the numeric position of the order.
cOrderBagName Name of the order bag.
Returns
ordFor() returns a expression containing the FOR condition for an order.
Description
This function returns a character string that is the expression for the FOR condition for the specified order. The order may be specified if xOrder is the name of the order. However, xOrder may be an numeric which represent the position in the order list of the desired Order.
Examples
USE test NEW VIA "DBFCDX"
INDEX ON field->first TO test FOR field->age > 50
? ordFor( "test" ) // --> "field->age > 50"
Status
Started
Compliance
This function is CA-Cl*pper compliant with one exception: If the xOrder paramter is not specified or xOrder is 0, the current active order is used.
xOrder It the name of the target order, or the numeric position of the order.
cOrderBagName Name of the order bag.
Returns
cExpKey Returns a character string, cExpKey.
Examples
USE test NEW VIA "DBFCDX"
INDEX ON field->first TO test FOR field->first > "CK"
INDEX ON field->age TO testage
? ordKey( "test" ) // --> "field->first"
ordSetFocus( 2 )
? ordKey() // --> "field->age"
Status
Started
Compliance
This function is CA-Cl*pper compliant with one exception: If the xOrder paramter is not specified or xOrder is 0, the current active order is used.
nRecords The number of records CRIPTION$* This function returns the number of records present in the database in the selected or designated work area. If no records are present the value of this function will be 0. Additionally, if no database is in use in the selected or designated work area, this function will return a 0 value as well.
Returns the size of a single record in an active database.
Syntax
RecSize() → nBytes
Arguments
(This function has no arguments)
Returns
nBytes The record size.
Description
This function returns the number of bytes used by a single record in the currently selected or designated database file. If no database is in use in this work area, the return value from this function will be 0.
Examples
USE test NEW
dbGoTop()
? RecSize() // --> 1
dbGoto( 50 )
? RecSize()
RLock() True (.T.) if record lock is successful; otherwise, it returns false (.F.).
Description
This function returns a logical true (.T.) if an attempt to lock a specific record in a selected or designated work area is successful. It will yield a false (.F.) if either the file or the desired record is currently locked. A record that is locked remains locked until another RLock() is issued or until an UNLOCK command is executed. On a Network environment the follow command need that the record is locked:
@...GET
DELETE (single record)
RECALL (single record)
REPLACE (single record)
Examples
LOCAL nAge := 50
USE test NEW
INDEX ON field->age TO test
IF dbSeek( nAge ) .AND. RLock()
dbDelete()
ENDIF
Returns the work area number for a specified alias.
Syntax
Select( [<cAlias>] ) → nWorkArea
Arguments
cAlias is the target work area alias name.
Returns
Select() returns the work area number.
Description
This function returns the work area number for the specified alias name cAlias. If no parameter is specified, the current work area will be the return value of the function.
Examples
LOCAL cOldArea
USE test NEW
USE names NEW
cOldArea := Select( "names" )
SELECT test
LIST
SELECT cOldArea
Checks whether a database is in use in a work area
Syntax
Used() → lDbfOpen
Arguments
(This function has no arguments)
Returns
lDbfOpen True is a database is Used;otherwise False
Description
This function returns a logical true (.T.) if a database file is in USE in the current or designated work area. If no alias is specified along with this function , it will default to the currently selected work area.
Examples
USE test NEW
USE names NEW
? Used() // --> .T.
? test->( Used() ) // --> .T.
dbCloseArea()
? Used() // --> .F.
SELECT test
? Used() // --> .T.
This function returns a character string of the day of the week, from a date expression dDate passed to it. If a NULL date is passed to the function, the value of the function will be a NULL byte.
Examples
? CDoW( Date() )
IF CDoW( Date() + 10 ) == "Sunday"
? "This is a sunny day."
ENDIF
This function returns the name of the month (January, February, etc.) from a date expression dDate passed to it. If a NULL date is passed to the function, the value of the function will be a NULL byte.
Examples
? CMonth( Date() )
IF CMonth( Date() + 10 ) == "March"
? "Have you done your system backup?"
ENDIF
This function converts a date that has been entered as a character expression to a date expression. The character expression will be in the form MM/DD/YY (based on the default value in SET DATE) or in the appropriate format specified by the SET DATE TO command. If an improper character string is passed to the function, an empty date value will be returned.
This function returns the number representing the day of the week for the date expressed as dDate. Returned value range is from 1 (Sunday) to 7 (Saturday).
This function converts any date expression (a field or variable) expressed as dDateString to a character expression in the default format MM/DD/YY. The date format expressed by this function is controlled in part by the date format specified in the SET DATE command
This function returns the value of dDateString as a character string in the format of YYYYMMDD. If the value of dDateString is an empty date, this function will return eight blank spaces.
cStartTime Start in time as a string format cEndTime End time as a string format
Returns
cDifference Difference between the times
Description
This function returns a string that shows the difference between the starting time represented as cStartTime and the ending time as cEndTime. If the stating time is greater then the ending time, the function will assume that the date changed once.
Examples
STATIC s_cStartTime
INIT PROCEDURE Startup()
s_cStartTime := Time()
RETURN
EXIT PROCEDURE StartExit()
? "You used this program by", ElapTime( s_cStartTime, Time() )
RETURN
Optional: cTime|nSeconds representing a time of the day value. cTime is a string in a valid time format: "hh:mm:ss.nnn". nSeconds is a numeric value in seconds in the range from 0 to 86399.999~ ( 60 secs * 60 mins * 24 hours - 1 millisecond )
Returns
tDateTime a dateTime value
Description
This function returns a tDateTime value from a dDate value. Optionally, a second parameter with the time of the day value can be provided which can be represented by either of a string time value or a numeric value in seconds.
Examples
? hb_DToT( Date() ) // a dateTime with a empty time part
? hb_DToT( Date(), "14:30:00.500" ) // a dateTime with time part 14:30pm with 500 milliseconds
? hb_DToT( Date(), 3600 ) // a dateTime with time part 1:00am (one hour)
nYear Optional parameter to hold the year of the given date.
nDayOfWeek Optional parameter to hold the day number of week.
Returns
nWeekNumber The ordinal week number of the year into which falls
the given dDate.
Description
This function returns the week number of year for the given dDate. The returned value is an ISO 8601 compliant week number. Optionally, can also be obtained the year and/or the day number of the week of the given dDate, if the nYear and/or nDayOfWeek parameters have been passed by reference. If dDate is an empty date expression, the function returns zero(s). Note: new function available after 2017-02-08 19:36 UTC+0100 commit,
nMonth Corresponding number of the month in the year, ranging from
0 to 12
Description
This function returns a number that represents the month of a given date expression dDate. If a NULL date (hb_SToD()) is passed to the function, the value of the function will be 0.
Returns the number of elapsed seconds past midnight.
Syntax
Seconds() → nSeconds
Arguments
None
Returns
nSeconds Number of seconds since midnight
Description
This function returns a numeric value representing the number of elapsed seconds based on the current system time. The system time is considered to start at 0 (midnight); it continues up to 86399 seconds. The value of the return expression is displayed in both seconds and hundredths of seconds.
Extracts the year designator of a given date as a numeric value
Syntax
Year( <dDate> ) → nYear
Arguments
dDate Any valid date expression
Returns
nYear The year portion of the date.
Description
This function returns the numeric value for the year in dDate. The returned value is not affected by the SET CENTURY and SET DATE settings and will always be a four-digit year number, unless the dDate is an empty date expression, in which case it will be zero.
This command runs an external program. Ensure that you have enough free memory to be able to run the external program. Do not use it to run 'Terminate and Stay Resident' programs (in case of MS-DOS) since that causes several problems.
Note: This function is what the RUN command preprocesses into.
It is considered bad form to use this function directly. Use the RUN command instead.
Examples
__Run( "edit " + cMyTextFile ) // Runs an external editor
__Run( "command" ) // Gives a OS shell
Returns the newline character(s) to use with the current OS
Syntax
hb_eol() → cString
Returns
cString A character string containing the character or characters required to move the screen cursor or print head to the start of a new line.
Description
Returns a character string containing the character or characters required to move the screen cursor or print head to the start of a new line for the operating system that the program is running on (or thinks it is running on, if an OS emulator is being used).
Under HB_OS_UNIX operating system the return value is the Line-Feed character (0x0a, Chr( 10 ) ); with other operating systems (like DOS) the return value is the Carriage-Return plus Line-Feed characters (0x0d 0x0a, Chr( 13 ) + Chr( 10 )).
Examples
// Get the newline character(s) for the current OS.
OutStd( "Hello World!" + hb_eol() )
? HB_ISSTRING( hb_eol() )
? Len( hb_eol() ) <= 2
This command runs an external program. Please make sure that you have enough free memory to be able to run the external program. Do not use it to run Terminate and Stay Resident programs (in case of DOS) since that causes several problems.
Examples
RUN ( "edit " + cMyTextFile ) // Runs an external editor
RUN command // Gives a OS shell
xNewSetting Any expression to assign a value to the setting
xOption Logical expression
nSetxNewSettingxOption
_SET_ALTERNATElFlag | cOnOff
If enabled, QOut() and QQOut() write to the screen and to a file, provided that a file has been opened or created with _SET_ALTFILE. If disabled, which is the default, QOut() and QQOut() only write to the screen (and/or to the PRINTFILE). Defaults to disabled.
_SET_ALTFILEcFileNamelAdditive
When set, creates or opens file to write QOut() and QQOut() output to. If lAdditive is TRUE and the file already exists, the file is opened and positioned at end of file. Otherwise, the file is created. If a file is already opened, it is closed before the new file is opened or created (even if it is the same file). The default file extension is .txt. There is no default file name. Call with an empty string to close the file.
_SET_AUTOPENlFlag | cOnOff
TODO: Document
_SET_AUTORDERlFlag | cOnOff
TODO: Document
_SET_AUTOSHARElFlag | cOnOff
TODO: Document
_SET_BELLlFlag | cOnOff
When enabled, the bell sounds when the last position of a GET is reached and/or when a GET validation fails. Disabled by default.
_SET_CANCELlFlag | cOnOff
When enabled, which is the default, pressing Alt+C or Ctrl+Break terminates the program. When disabled, both keystrokes can be read by Inkey(). Note: SET KEY has precedence over SET CANCEL.
_SET_COLORcColorSet
Sets the current color scheme, using color pairs in the sequence "<standard>, <enhanced>, <border>, <background>, <unselected>". Each color pair uses the format "<foreground>/<background>". The color codes are space or "N" for black, "B" for blue, "G" for green, "BG" for Cyan, "R" for red, "RB" for magenta, "GR" for brown, "W" for white, "N+" for gray, "B+" for bright blue, "G+" for bright green, "BG+" for bright cyan, "R+" for bright red, "RB+" for bright magenta, "GR+" for yellow, and "W+" for bright white. Special codes are "I" for inverse video, "U" for underline on a monochrome monitor (blue on a color monitor), and "X" for blank. The default color is "W/N,N/W,N,N,N/W".
_SET_CONFIRMlFlag | cOnOff
If enabled, an exit key must be pressed to leave a GET. If disabled, which is the default, typing past the end will leave a GET.
_SET_CONSOLElFlag | cOnOff
If enabled, which is the default, all screen output goes to the screen. When disabled, screen output is suppressed (Note: This setting does not affect OutStd() or OutErr()).
_SET_CURSORnCursorType
If enabled, which is the default, the cursor is displayed on screen. If disabled, the screen cursor is hidden.
_SET_DATEFORMATcDateFormat
Sets the default date format for display, date input, and date conversion. Defaults to American mm/dd/yy. Other formats include ANSI yy.mm.dd, British dd/mm/yy, French dd/mm/yy, German dd.mm.yy, Italian dd-mm-yy, Japan yy/mm/dd, and USA mm-dd-yy. SET CENTURY modifies the date format. SET CENTURY ON replaces the ys with YYYY. SET CENTURY OFF replaces the ys with YY.
_SET_DEBUGlStatus
When set to .T., pressing Alt+D activates the debugger. When set to .F., which is the default, Alt+D can be read by Inkey(). (Also affected by AltD( 1 ) and AltD( 0 ))
_SET_DECIMALSnNumberOfDecimals
Sets the number of decimal digits to use when displaying printing numeric values when SET FIXED is ON. Defaults to 2. If SET FIXED is OFF, then SET DECIMALS is only used to determine the number of decimal digits to use after using Exp(), Log(), Sqrt(), or division. Other math operations may adjust the number of decimal digits that the result will display. Note: This never affects the precision of a number. Only the display format is affected.
_SET_DEFAULTcDefaultDirectory
Sets the default directory in which to open, create and check for files. Defaults to current directory (blank).
_SET_DELETEDlFlag | cOnOff
If enabled, deleted records will be processed. If disabled, which is the default, deleted records will be ignored.
_SET_DELIMCHARScDelimiters
Sets the GET delimiter characters. Defaults to "::".
_SET_DELIMITERSlFlag | cOnOff
If enabled, GETs are delimited on screen. If disabled, which is the default, no GET delimiters are used.
_SET_DEVICEcDeviceName
Selects the output device for DevOut(). When set to "PRINTER", all output is sent to the printer device or file set by _SET_PRINTFILE. When set to anything else, all output is sent to the screen. Defaults to "SCREEN".
_SET_EOFlFlag | cOnOff
Defaults to FALSE on *nix, but defaults to TRUE on everything else. If set to FALSE, then Chr( 26 ) does not get written when using COPY TO DELIMITED, COPY TO SDF, or when closing any of the various text files that are created using various SET values. [This is a Harbour extension]
_SET_EPOCHnYear
Determines how to handle the conversion of 2-digit years to 4 digit years. When a 2-digit year is greater than or equal to the year part of the epoch, the century part of the epoch is added to the year. When a 2-digit year is less than the year part of the epoch, the century part of the epoch is incremented and added to the year. The default epoch is 1900, which converts all 2-digit years to 19xx. Example: If the epoch is set to 1950, 2-digit years in the range from 50 to 99 get converted to 19xx and 2-digit years in the range 00 to 49 get converted to 20xx.
_SET_ESCAPElFlag | cOnOff
When enabled, which is the default, pressing Esc will exit a READ. When disabled, pressing Esc during a READ is ignored, unless the Esc key has been assigned to a function using SET KEY.
_SET_EVENTMASKnEventCodes
Determines which events Inkey() will respond to. INKEY_MOVE allows mouse movement events. INKEY_LDOWN allows the left mouse button down click. INKEY_LUP allows the left mouse button up click. INKEY_RDOWN allows the right mouse button down click. INKEY_RUP allows the right mouse button up clock. INKEY_KEYBOARD allows keyboard keystrokes. INKEY_ALL allows all of the preceding events. Events may be combined (e.g., using INKEY_LDOWN + INKEY_RUP will allow left mouse button down clicks and right mouse button up clicks). The default is INKEY_KEYBOARD.
_SET_EXACTlFlag | cOnOff
When enabled, all string comparisons other than == exclude trailing spaces when checking for equality. When disabled, which is the default, all string comparisons other than == treat two strings as equal if the right hand string is "" or if the right hand string is shorter than or the same length as the left hand string and all of the characters in the right hand string match the corresponding characters in the left hand string.
_SET_EXCLUSIVElFlag | cOnOff
When enabled, which is the default, all database files are opened in exclusive mode. When disabled, all database files are opened in shared mode. Note: The EXCLUSIVE and SHARED clauses of the USE command can be used to override this setting.
_SET_EXITlFlag | cOnOff
Toggles the use of Up and Down as READ exit keys. Specifying true (.T.) enables them as exit keys, and false (.F.) disables them. Used internally by the ReadExit() function.
_SET_EXTRAlFlag | cOnOff
QUESTION: What is this for? It does not affect _SET_EXTRAFILE in CA-Cl*pper!
_SET_EXTRAFILEcFileNamelAdditive
When set, creates or opens file to write QOut() and QQOut() output to. If lAdditive is TRUE and the file already exists, the file is opened and positioned at end of file. Otherwise, the file is created. If a file is already opened, it is closed before the new file is opened or created (even if it is the same file). The default file extension is .prn. There is no default file name. Call with an empty string to close the file.
_SET_FIXEDlFlag | cOnOff
When enabled, all numeric values will be displayed and printed with the number of decimal digits set by SET DECIMALS, unless a PICTURE clause is used. When disabled, which is the default, the number of decimal digits that are displayed depends upon a variety of factors. See _SET_DECIMALS for more.
_SET_INSERTlFlag | cOnOff
When enabled, characters typed in a GET or MemoEdit() are inserted. When disabled, which is the default, characters typed in a GET or MemoEdit() overwrite. Note: This setting can also be toggled between on and off by pressing the Insert key during a GET or MemoEdit().
_SET_INTENSITYlFlag | cOnOff
When enabled, which is the default, GETs and PROMPTs are displayed using the enhanced color setting. When disabled, GETs and PROMPTs are displayed using the standard color setting.
_SET_LANGUAGEcLanguageID
Specifies the language to be used for Harbour messages. [This is a Harbour extension]
_SET_MARGINnColumns
Sets the left margin for all printed output. The default value is 0. Note: PCol() reflects the printer's column position including the margin (e.g., SET MARGIN TO 5 followed by DevPos( 5, 10 ) makes PCol() return 15).
_SET_MBLOCKSIZEnMemoBlockSize
TODO: Document
_SET_MCENTERlFlag | cOnOff
If enabled, display PROMPTs centered on the MESSAGE row. If disabled, which is the default, display PROMPTS at column position 0 on the MESSAGE row.
_SET_MESSAGEnRow
If set to 0, which is the default, PROMPTs are always suppressed. Otherwise, PROMPTs are displayed on the set row. Note: It is not possible to display prompts on the top-most screen row, because row 0 is reserved for the SCOREBOARD, if enabled.
_SET_MFILEEXTcMemoFileExt
TODO: Document
_SET_OPTIMIZElFlag | cOnOff
TODO: Document
_SET_PATHcDirectories
Specifies a path of directories to search through to locate a file that cannot be located in the DEFAULT directory. Defaults to no path "". Directories must be separated by a semicolon (e.g., /hb/bin;/hb/tests).
_SET_PRINTERlFlag | cOnOff
If enabled, QOut() and QQOut() write to the screen and to a file, provided that a file has been opened or created with _SET_ALTFILE. If disabled, which is the default, QOut() and QQOut() only write to the screen (and/or to the ALTFILE).
_SET_PRINTFILEcFileNamelAdditive
When set, creates or opens file to write QOut(), QQOut() and DevOut() output to. If lAdditive is TRUE and the file already exists, the file is opened and positioned at end of file. Otherwise, the file is created. If a file is already opened, it is closed before the new file is opened or created (even if it is the same file). The default file extension is .prn. The default file name is PRN, which maps to the default printer device. Call with an empty string to close the file.
_SET_SCOREBOARDlFlag | cOnOff
When enabled, which is the default, READ and MemoEdit() display status messages on screen row 0. When disabled, READ and MemoEdit() status messages are suppressed.
_SET_SCROLLBREAKlFlag | cOnOff
QUESTION: What is this flag for?
_SET_SOFTSEEKlFlag | cOnOff
When enabled, a SEEK that fails will position the record pointer to the first key that is higher than the sought after key or to LastRec() + 1 if there is no higher key. When disabled, which is the default, a SEEK that fails will position the record pointer to LastRec() + 1.
_SET_STRICTREADlFlag | cOnOff
TODO: Document
_SET_TYPEAHEADnKeyStrokes
Sets the size of the keyboard typeahead buffer. Defaults to 50. The minimum is 16 and the maximum is 4096.
_SET_UNIQUElFlag | cOnOff
When enabled, indexes are not allowed to have duplicate keys. When disabled, indexes are allowed duplicate keys.
_SET_VIDEOMODEnValue
TODO: Document
_SET_WRAPlFlag | cOnOff
When enabled, lightbar menus can be navigated from the last position to the first and from the first position to the last. When disabled, which is the default, there is a hard stop at the first and last positions.
Change the video mode to a specified number of rows and columns
Syntax
SetMode( <nRows>, <nCols> ) → lSuccess
Arguments
nRows is the number of rows for the video mode to set.
nCols is the number of columns for the video mode to set.
Returns
SetMode() returns true if the video mode change was successful; otherwise, it returns false.
Description
SetMode() is a function that change the video mode depend on the video card and monitor combination, to match the number of rows and columns specified. Note that there are only a real few combination or rows/cols pairs that produce the video mode change. The followings are available for GTDOS:
12 rows x 40 columns 12 rows x 80 columns
25 rows x 40 columns 25 rows x 80 columns
28 rows x 40 columns 28 rows x 80 columns
50 rows x 40 columns 43 rows x 80 columns
50 rows x 80 columns
The follow modes are available to Windows
25 rows x 40 columns 25 rows x 80 columns
50 rows x 40 columns 43 rows x 80 columns
50 rows x 80 columns
Some modes only are available for color and/or VGA monitors. Any change produced on the screen size is updated in the values returned by MaxRow() and MaxCol().
Examples
// The first example change to a 12 lines of display mode:
IF SetMode( 12, 40 )
? "Hey man are you blind?"
ELSE
? "Mom, bring me my glasses!"
ENDIF
// Next example change to a 50 lines mode:
IF SetMode( 50, 80 )
? "This wonderful mode was successfully set"
ELSE
? "Wait. this monitor is not made of rubber!"
ENDIF
Status
Ready
Compliance
Some of these modes are not available in CA-Cl*pper
Sound a tone with a specified frequency and duration.
Syntax
Tone( <nFrequency>, <nDuration> ) → NIL
Arguments
nFrequency A non-negative numeric value that specifies the frequency of the tone in hertz.
nDuration A positive numeric value which specifies the duration of the tone in 1/18 of a second units.
Returns
Tone() always returns NIL.
Description
Tone() is a sound function that could be used to irritate the end user, his or her dog, and the surrounding neighborhood. The frequency is limited to the range 0 to 32767 Hz.
Examples
// Good sound
Tone( 500, 1 )
Tone( 4000, 1 )
Tone( 2500, 1 )
// Bad sound
Tone( 300, 1 )
Tone( 499, 5 )
Tone( 700, 5 )
Tone( 800, 1 ) // same as hb_BChar( 7 )
Tone( 32000, 200 ) // any dogs around yet?
Tone( 130.80, 1 ) // musical note - C
Tone( 400, 0 ) // short beep
Tone( 700 ) // short beep
Tone( 10, 18.2 ) // 1 second delay
Tone( -1 ) // 1/18.2 second delay
Tone() // 1/18.2 second delay
ErrorSys() is called upon startup by Harbour and installs the default error handler. Normally you should not call this function directly, instead use ErrorBlock() to install your own error handler.
nFunctionKey is a number in the range 1..40 that represent the function key to be assigned.
cString is a character string to set. If cString is not specified, the function key is going to be set to NIL releasing by that any previous __SetFunction() or SetKey() for that function.
Returns
__SetFunction() always return NIL.
Description
__SetFunction() assign a character string with a function key, when this function key is pressed, the keyboard is stuffed with this character string. __SetFunction() has the effect of clearing any SetKey() previously set to the same function number and vice versa.
nFunctionKey Key to be set
1 .. 12 <F1> .. <F12>
13 .. 20 <Shift+F3> .. <Shift+F10>
21 .. 30 <Ctrl+F1> .. <Ctrl+F10>
31 .. 40 <Alt+F1> .. <Alt+F10>
SET FUNCTION command is preprocessed into __SetFunction() function during compile time.
Examples
#include "inkey.ch"
LOCAL cTest, GetList := {}
// Associate <F1> with a string
__SetFunction( 1, "I Am Lazy" + Chr( K_ENTER ) )
CLS
cTest := Space( 20 )
@ 10, 0 SAY "type something or <F1> for lazy mode" GET cTest
READ
? cTest
Status
Ready
Compliance
Harbour use 11 and 12 to represent F11 and F12, while CA-Cl*pper use 11 and 12 to represent Shift+F1 and Shift+F2.
nKey is a numeric key value to be tested code-block, if executed
p1..p3 are optional parameters that will be passed to the code-block
Returns
True if there is a hot-key associated with nKey and it was executed; otherwise False If there is a hot-key association (before checking any condition): - if there is a condition-block, it is passed one parameter - nKey - when the hot-key code-block is called, it is passed 1 to 4 parameters, depending on the parameters passed to hb_SetKeyCheck(). Any parameters so passed are directly passed to the code-block, with an additional parameter being nKey
Description
hb_SetKeyCheck() is intended as a common interface to the SetKey() functionality for such functions as AChoice(), dbEdit(), MemoEdit(), ACCEPT, INPUT, READ, and WAIT
Examples
// FIXME
#include "inkey.ch"
// within ReadModal()
IF hb_SetKeyCheck( K_ALT_X, GetActive() )
// some other processing ...
ENDIF
// within TBrowse handler
CASE hb_SetKeyCheck( nInkey, oTBrowse )
RETURN
CASE nInKey == K_ESC
// some other processing ...
Returns a copy of internal set-key list, optionally overwriting
Syntax
hb_SetKeySave( [ <OldKeys> ] )
Arguments
OldKeys is an optional set-key list from a previous call to hb_SetKeySave(), or NIL to clear current set-key list
Returns
Current set-key list
Description
hb_SetKeySave() is designed to act like the Set() function which returns the current state of an environment setting, and optionally assigning a new value. In this case, the "environment setting" is the internal set-key list, and the optional new value is either a value returned from a previous call to hb_SetKeySave() - to restore that list, or the value of NIL to clear the current list.
Examples
LOCAL aKeys := hb_SetKeySave( NIL ) // removes all current set=keys
// some other processing ...
hb_SetKeySave( aKeys )
anKey is either a numeric key value, or an array of such values
bAction is an optional code-block to be assigned
bCondition is an optional condition code-block
Returns
Current assigned action-block
Description
The SetKey() function returns the current code-block assigned to a key when called with only the key value. If the action block (and optionally the condition block) are passed, the current block is returned, and the new code block and condition block are stored. A group of keys may be assigned the same code block/condition block by using an array of key values in place on the first parameter.
Examples
#include "getexit.ch"
#include "inkey.ch"
LOCAL bOldF10 := SetKey( K_F10, {|| Yahoo() } )
LOCAL bBlock
// some other processing ...
SetKey( K_F10, bOldF10 )
// some other processing ...
bBlock := SetKey( K_SPACE )
IF bBlock != NIL // ...
// make <F10> exit current get, but only if in a get - ignores other
// wait states such as menus, achoices, etc...
SetKey( K_F10, {|| GetActive():State := GE_WRITE }, ;
{|| GetActive() != NIL } )
ENDIF
Status
Ready
Compliance
SetKey() is mostly CA-Cl*pper compliant. The only difference is the addition of the condition code-block parameter, allowing set-keys to be conditionally turned off or on. This condition-block cannot be returned once set - see hb_SetKeyGet()
xVal Argument to be passed to the code block expression
xVal... Argument list to be passed to the code block expression
Returns
xExpression The result of the evaluated code block
Description
This function evaluates the code bloc expressed as bBlock and returns its evaluated value. If their are multiple expressions within the code block, the last expression will be value of this function.
If the code block requires parameters to be passed to it, they are specified in the parameter list xVal and following. Each parameter is separated by a comma within the expression list.
cFileMask File mask to include in the function return. It could contain path and standard wildcard characters as supported by your OS (like * and ?). If cFileMask contains no path, then SET DEFAULT path is used to display files in the mask.
Returns
__Dir() always returns NIL.
Description
If no cFileMask is given, __Dir() displays information about all *.dbf in the SET DEFAULT path. This information contains: file name, number of records, last update date and the size of each file.
If cFileMask is given, __Dir() list all files that match the mask with the following details: Name, Extension, Size, Date.
DIR command is preprocessed into __Dir() function during compile time.
__Dir() is a compatibility function, it is superseded by Directory() which return all the information in a multidimensional array.
If long file names are available Harbour will use/display the first 15 characters else Harbour will use/display a 8.3 file name consistent with CA-Cl*pper.
Examples
__Dir() // information for all DBF files in current directory
__Dir( "*.dbf" ) // list all DBF file in current directory
// list all PRG files in Harbour Run-Time library
// for MS-DOS compatible operating systems
__Dir( hb_DirSepToOS( "src/rtl/*.prg" ) )
// list all files in the public section on a Unix like machine
__Dir( hb_DirSepToOS( "/pub" ) )
cFileMask File mask to include in the function return. It could contain path and standard wildcard characters as supported by your OS (like * and ?). If you omit cFileMask or if cFileMask contains no path, then the path from SET DEFAULT is used.
aName Array to fill with file name of files that meet cFileMask. Each element is a Character string and include the file name and extension without the path. The name is the long file name as reported by the OS and not necessarily the 8.3 uppercase name.
aSize Array to fill with file size of files that meet cFileMask. Each element is a Numeric integer for the file size in Bytes. Directories are always zero in size.
aDate Array to fill with file last modification date of files that meet cFileMask. Each element is of type Date.
aTime Array to fill with file last modification time of files that meet cFileMask. Each element is a Character string in the format HH:mm:ss.
aAttr Array to fill with attribute of files that meet cFileMask. Each element is a Character string, see Directory() for information about attribute values. If you pass array to aAttr, the function is going to return files with normal, hidden, system and directory attributes. If aAttr is not specified or with type other than Array, only files with normal attribute would return.
Returns
ADir() return the number of file entries that meet cFileMask
Description
ADir() return the number of files and/or directories that match a specified skeleton, it also fill a series of given arrays with the name, size, date, time and attribute of those files. The passed arrays should pre-initialized to the proper size, see example below. In order to include hidden, system or directories aAttr must be specified.
ADir() is a compatibility function, it is superseded by Directory() which returns all the information in a multidimensional array.
Examples
LOCAL aName, aSize, aDate, aTime, aAttr, tmp
LOCAL nLen := ADir( "*.dbf" ) // Number of JPG files in this directory
IF nLen > 0
aName := Array( nLen ) // make room to store the information
aSize := Array( nLen )
aDate := Array( nLen )
aTime := Array( nLen )
aAttr := Array( nLen )
ADir( "*.prg", aName, aSize, aDate, aTime, aAttr )
FOR tmp := 1 TO nLen
? ;
aName[ tmp ], ;
aSize[ tmp ], ;
aDate[ tmp ], ;
aTime[ tmp ], ;
aAttr[ tmp ]
NEXT
ELSE
? "This directory is clean from smut"
ENDIF
Status
Ready
Compliance
aName is going to be filled with long file name and not necessarily the 8.3 uppercase name.
cDirectory The name of the directory you want do change into.
Returns
nError 0 if directory was successfully changed, otherwise the number of the last error.
Description
This function attempt to change the current directory to the one specified in cDirectory. If this function fails, it will return the last OS error code number. See FError() function for the description of the error.
Examples
IF DirChange( hb_DirSepToOS( "./mydir" ) ) == 0
? "Change to directory was successful"
ENDIF
Status
Ready
Compliance
CA-Cl*pper v5.3 function available in builds with HB_COMPAT_C53 option enabled (default)
cDirectory The name of the directory you want to remove.
Returns
nError 0 if directory was successfully removed, otherwise the number of the last error.
Description
This function attempt to remove the specified directory in cDirectory If this function fails, it will return the last OS error code number. See FError() function for the description of the error.
Examples
LOCAL cDir
IF DirRemove( cDir := hb_DirSepToOS( "./mydir" ) ) == 0
? "Removing directory", cDir, "was successful"
ENDIF
Status
Ready
Compliance
CA-Cl*pper v5.3 function available in builds with HB_COMPAT_C53 option enabled (default)
nDrive The number of the drive you are requesting info on where 1 = A, 2 = B, etc. For 0 or no parameter, DiskSpace will operate on the current drive. The default is 0
Returns
nDiskBytes The number of bytes on the requested disk that match the requested type.
Description
By default, this function will return the number of bytes of free space on the current drive that is available to the user requesting the information.
If information is requested on a disk that is not available, a runtime error 2018 will be raised.
Examples
? "You can use:", hb_ntos( DiskSpace() ), "bytes"
// See tests/diskspac.prg for another example
This function closes an open file with a file handle of nHandle and writes the associated buffers to the disk. The nHandle value is derived from the FCreate() or FOpen() function.
nHandle Numeric file handle to be used in other operations.
Description
This function creates a new file with a file name of cFile. The default value of nAttribute is 0 and is used to set the attribute byte for the file being created by this function. The return value will be a file handle that is associated with the new file. This number will be between zero to 65535, inclusive. If an error occurs, the return value of this function will be F_ERROR.
If the file cFile already exists, the existing file will be truncated to a file length of 0 bytes.
If specified, the following table shows the value for nAttribute and their related meaning to the file cFile being created by this function.
This function deletes the file specified in cFile from the disk. No extensions are assumed. The drive and path my be included in cFile; neither the SET DEFAULT not the SET PATH command controls the performance of this function. If the drive or path is not used, the function will look for the file only on the currently selected directory on the logged drive.
If the function is able to successfully delete the file from the disk, the value of the function will be 0; otherwise a -1 will be returned. If not successful, additional information may be obtained by calling the FError() function.
Note: Any file to be removed by FErase() must still be closed.
Examples
#include "fileio.ch"
IF FErase( "test.txt" ) != F_ERROR
? "File successfully erased"
ELSE
? "File cannot be deleted"
ENDIF
Reports the error status of low-level file functions
Syntax
FError() → nErrorCode
Returns
nErrorCode Value of the OS error last encountered by a low-level file function.
FError() Return Values
Error Meaning
0 Successful
2 File not found
3 Path not found
4 Too many files open
5 Access denied
6 Invalid handle
8 Insufficient memory
15 Invalid drive specified
19 Attempted to write to a write-protected disk
21 Drive not ready
23 Data CRC error
29 Write fault
30 Read fault
32 Sharing violation
33 Lock Violation
Description
After every low-level file function, this function will return a value that provides additional information on the status of the last low-level file function's performance. If the FError() function returns a 0, no error was detected. Below is a table of possibles values returned by the FError() function.
Examples
IF ( nHandle := FCreate( "test.txt" ) ) == F_ERROR
? "Cannot create file, OS error", FError()
ENDIF
cFileSpec File name skeleton or file name to find.
Returns
lExists a logical true (.T.) if the file exists or logical false (.F.).
Description
This function return a logical true (.T.) if the given file name cFileSpec exist.
File name skeletons symbols may be used in the file name in cFileSpec, as may the drive and/or path name. If a path is not explicitly specified, File() will look for the file in the SET DEFAULT path, then in each SET PATH path, until the file is found or there are no more paths to search. The PATH environment variable is never searched and the current drive/directory is only searched if SET DEFAULT is blank.
This function opens a file expressed as cFile and returns a file handle to be used with other low-level file functions. The value of nMode represents the status of the file to be opened; the default value is 0. The file open modes are as follows:
nMode Meaning
FO_READ Read only
FO_WRITE Write only
FO_READWRITE Read/write
FO_EXCLUSIVE Exclusive read only
FO_DENYWRITE Prevent others from writing
FO_DENYREAD Deny read only
FO_DENYNONE Not deny, Let to others Read / Write
FO_SHARED same as FO_DENYNONE
If there is an error in opening a file, a F_ERROR will be returned by the function. Files handles may be in the range of 0 to 65535. The status of the SET DEFAULT TO and SET PATH TO commands has no effect on this function. Directory names and paths must be specified along with the file that is to be opened.
If an error has occurred, see the returns values from FError() for possible reasons for the error.
nBytes the number of bytes successfully read from the file. nHandle
Description
This function reads the characters from a file whose file handle is nHandle into a character memory variable expressed as cBuffer. The function returns the number of bytes successfully read into cBuffer.
The value of nHandle is obtained from either a call to the FOpen() or the FCreate() function.
The cBuffer expression is passed by reference and must be defined before this function is called. It also must be at least the same length as nBytes.
nBytes is the number of bytes to read, starting at the current file pointer position. If this function is successful in reading the characters from the file, the length of cBuffer or the number of bytes specified in nBytes will be the value returned. The current file pointer advances the number of bytes read with each successive read. The return value is the number of bytes successfully read from the file. If a 0 is returned, or if the number of bytes read matches neither the length of cBuffer nor the specified value in nBytes an end-of-file condition has been reached.
This function returns a character string of nBytes bytes from a file whose file handle is nHandle.
The value of the file handle nHandle is obtained from either the FOpen() or FCreate() functions.
The value of nBytes is the number of bytes to read from the file. The returned string will be the number of characters specified in nBytes or the number of bytes read before a zero byte is found.
nSuccess If successful, a 0 will be returned otherwise, a -1 will be returned.
Description
This function renames the specified file cOldFile to cNewFile. A file name and/or directory name may be specified for either para- meter. However, if a path is supplied as part of cNewFile and this path is different from either the path specified in cOldFile or (if none is used) the current drive and directory, the function will not execute successfully.
Neither parameter is subject to the control of the SET PATH TO or SET DEFAULT TO commands. In attempting to locate the file to be renamed, this function will search the default drive and directory or the drive and path specified in cOldFile. It will not search directories named by the SET PATH TO and SET DEFAULT TO commands or by the PATH environment variable.
If the file specified in cNewFile exists or the file is open, the function will be unable to rename the file. If the function is unable to complete its operation, it will return a value of -1. If it is able to rename the file, the return value for the function will be 0. A call to FError() function will give additional information about any error found.
Examples
#include "fileio.ch"
nResult := FRename( "test.txt", "test1.txt" )
IF nResult != 0
? "File could not be renamed"
ENDIF
nPosition the current position relative to begin-of-file
Description
This function sets the file pointer in the file whose file handle is nHandle and moves the file pointer by expN2 bytes from the file position designated by nOrigin. The returned value is the relative position of the file pointer to the beginning-of-file marker once the operation has been completed.
nHandle is the file handle number. It is obtained from the FOpen() or FCreate() function.
The value of nOffSet is the number of bytes to move the file pointer from the position determined by nOrigin. The value of nOffset may be a negative number, suggesting backward movement.
The value of nOrigin designates the starting point from which the file pointer should he moved, as shown in the following table:
<nOrigin> File position
FS_SET Beginning of file
FS_RELATIVE Current file pointer position
FS_END End of file
If a value is not provided for nOrigin, it defaults to 0 and moves the file pointer from the beginning of the file.
Examples
// here is a function that read one text line from an open file
// nH = file handle obtained from FOpen()
// cB = a string buffer passed-by-reference to hold the result
// nMaxLine = maximum number of bytes to read
STATIC FUNCTION FReadLn( nH, cB, nMaxLine )
LOCAL cLine, nSavePos, nEol, nNumRead
cLine := Space( nMaxLine )
cB := ""
nSavePos := FSeek( nH, 0, FS_RELATIVE )
nNumRead := FRead( nH, @cLine, nMaxLine )
IF ( nEol := hb_BAt( hb_eol(), hb_BLeft( cLine, nNumRead ) ) ) == 0
cB := cLine
ELSE
cB := hb_BLeft( cLine, nEol - 1 )
FSeek( nH, nSavePos + nEol + 1, FS_SET )
ENDIF
RETURN nNumRead != 0
nBytesWritten the number of bytes successfully written.
Description
This function writes the contents of cBuffer to the file designated by its file handle nHandle. If used, nBytes is the number of bytes in cBuffer to write.
The returned value is the number of bytes successfully written to the file. If the returned value is 0, an error has occurred (unless this is intended). A successful write occurs when the number returned by FWrite() is equal to either Len( cBuffer ) or nBytes.
The value of cBuffer is the string or variable to be written to the open file nHandle.
The value of nBytes is the number of bytes to write out to the file. The disk write begins with the current file position in nHandle. If this variable is not used, the entire contents of cBuffer is written to the file. To truncate a file, a call of FWrite( nHandle, "", 0 ) is needed.
Examples
nHandle := FCreate( "test.txt" )
FOR x := 1 TO 10
FWrite( nHandle, hb_ntos( x ) )
NEXT
FClose( nHandle )
cDrive The drive letter you are requesting info on. The default is A:
nType The type of space being requested. The default is HB_DISK_AVAIL.
Returns
nDiskBytes The number of bytes on the requested disk that match the requested type.
Description
By default, this function will return the number of bytes of free space on the current drive that is available to the user requesting the information.
There are 4 types of information available:
HB_DISK_AVAIL The amount of space available to the user making the
request. This value could be less than HB_FS_FREE if disk quotas are supported by the O/S in use at runtime, and disk quotas are in effect. Otherwise, the value will be equal to that returned for HB_FS_FREE.
HB_DISK_FREE The actual amount of free disk space on the drive.
HB_DISK_USED The number of bytes in use on the disk.
HB_DISK_TOTAL The total amount of space allocated for the user if
disk quotas are in effect, otherwise, the actual size of the drive.
If information is requested on a disk that is not available, a runtime error 2018 will be raised.
Examples
#include "fileio.ch"
? "You can use:", hb_ntos( hb_DiskSpace() ), "bytes"
? "Out of a total of:", hb_ntos( hb_DiskSpace( , HB_DISK_TOTAL ) )
// See tests/diskspac.prg for another example
lIsEof.T. if the file handle is at end-of-file, otherwise .F.
Description
This function checks an open file handle to see if it is at EOF.
If the file handle is missing, not numeric, or not open, then this function returns .T. and sets the value returned by FError() to -1 (F_ERROR) or a C-compiler dependent errno value (EBADF or EINVAL).
set> Offset of the first byte of the region to be locked.
nBytes Number of bytes to be locked.
e> The type (read or write) of lock requested.
Returns
lSuccess.T. if the lock was obtained, else .F.
Description
This function attempts to lock a region of the file whose file handle is nHandle. This is a low-level file function. To lock Harbour data files use either the FLock() or RLock() function.
The value of nHandle is obtained from either a call to the FOpen() or the FCreate() function.
nOffset is the offset (from the beginning of the file) to the first of the region to be locked. (Offsets from the current position nd of file are not currently supported.)
nBytes is the length of the region to be locked in bytes.
nType is the type of lock requested. There are two types of locks: exclusive write locks ( nType = 0x0000 ) - the default, and shared read locks ( nType = 0x0100 ). Additionally you can specify a blocking version of this function (that is it won't return until either an error has occurred or the lock has been obtained) by adding 0x0200 to the above values.
set> Offset of the first byte of the region to be locked.
nBytes Number of bytes to be locked.
Returns
lSuccess.T. if the lock was removed, else .F.
Description
This function attempts to unlock a region of the file whose file handle is nHandle. This is a low-level file function. To unlock Harbour data files use the dbUnlock() function.
The value of nHandle is obtained from either a call to the FOpen() or the FCreate() function.
nOffset is the offset (from the beginning of the file) to the first of the region to be unlocked. (Offsets from the current position nd of file are not currently supported.)
nBytes is the length of the region to be unlocked in bytes.
This function attempts to access a drive. If the access to the drive was successful, it will return true (.T.), otherwise false (.F.). This function is useful for backup function, so you can determine if the drive that will receive the backup data is ready or not.
Examples
IF IsDisk( "A" )
? "Drive is ready"
ENDIF
Status
Ready
Compliance
CA-Cl*pper v5.3 function available in builds with HB_COMPAT_C53 option enabled (default)
cDirectory The name of the directory you want to create.
Returns
nError 0 if directory was successfully created, otherwise the number of the last error.
Description
This function attempt to create a new directory with the name contained in cDirectory. If this function fails, it will return the last OS error code number. See FError() function for the description of the error
Examples
LOCAL cDir
IF MakeDir( cDir := hb_DirSepToOS( "./mydir" ) ) == 0
? "Directory", cDir, "successfully created"
ENDIF
Status
Ready
Compliance
CA-Cl*pper v5.3 function available in builds with HB_COMPAT_C53 option enabled (default)
pCleanupFunc Pointer to HB_GARBAGE_FUNC function that will be called directly before releasing the garbage memory block or NULL. This function should release all other memory allocated and stored inside the memory block. For example, it releases all items stored inside the array. The functions receives a single parameter: the pointer to memory allocated by hb_gcAlloc().
Returns
The pointer to allocated memory or it generates an internal unrecoverable error.
Description
hb_gcAlloc() is used to allocate the memory that will be tracked by the garbage collector. It allows to properly release memory in case of self-referencing or cross-referencing Harbour level variables. Memory allocated with this function should be released with hb_gcFree() function or it will be automatically deallocated by the GC if it is not locked or if it is not referenced by some Harbour level variable.
Scans all memory blocks and releases the garbage memory.
Syntax
void hb_gcCollectAll( void );
Arguments
None.
Returns
Nothing.
Description
This function scans the eval stack, the memvars table, the array of static variables and table of created classes for referenced memory blocks. After scanning all unused memory blocks and blocks that are not locked are released.
Marks the memory to prevent deallocation by the garbage collector.
Syntax
void hb_gcItemRef( PHB_ITEM pItem );
Arguments
pItem The pointer to item structure that will be scanned. The passed item can be of any datatype although arrays, objects and codeblocks are scanned only. Other datatypes don't require locking so they are simply ignored.
Returns
Nothing.
Description
The garbage collector uses hb_gcItemRef() function during scanning of referenced memory pointers. This function checks the type of passed item and scans recursively all other memory blocks referenced by this item if it is an array, an object or a codeblock.
NOTE: This function is reserved for the garbage collector only. It
cannot be called from the user code - calling it can cause unpredicted results (memory blocks referenced by the passed item can be released prematurely during the closest garbage collection).
lFlag a logical value indicating to turn on or off the 'auto add' flag of the hash table
Returns
The previous value of the 'auto add' flag
Description
This function is equivalent to hb_HAutoAdd() but it returns the old flag value rather than the hash table
Examples
LOCAL hsTable, lFlag
hsTable := { "one" => 1, "two" => 2 }
// turn 'auto add' on for a new hash table, storing old flag
lFlag := hb_HAutoAdd( hsTable, .T. )
lFlag a logical value indicating to turn on or off the 'binary' flag of the hash table
Returns
The previous value of the 'binary' flag
Description
This function is equivalent to hb_HBinary() but it returns the old flag value rather than the hash table
Examples
LOCAL hsTable, lFlag
hsTable := { "one" => 1, "two" => 2 }
// turn 'binary' on for a new hash table, storing old flag
lFlag := hb_HBinary( hsTable, .T. )
lFlag a logical value indicating to turn on or off the 'case match' flag of the hash table
Returns
The previous value of the 'case match' flag
Description
This function returns the old flag value
Examples
LOCAL hsTable, lFlag
hsTable := { "one" => 1, "two" => 2 }
// turn 'case match' on for a new hash table, storing old flag
lFlag := hb_HCaseMatch( hsTable, .T. )
bBlock a code block that will be evaluated for each entry within the source hash table; the code block will be passed the entry key, value and position; if the code block returns a true value, the entry will be added to the destination hash table
nPosition the position of an entry within the source hash table that will be appended to the destination hash table
TODO: the source code passes either a number or HB_HASH_UNION; research this
Returns
The destination hash table with the contents of the source hash table merged
bAction is a codeblock that will be executed during idle states. There are no arguments passed to this codeblock during evaluation.
Returns
nHandle The handle (an integer value) that identifies the task. This handle can be used for deleting the task.
Description
hb_idleAdd() adds a passed codeblock to the list of background tasks that will be evaluated during the idle states. There is no limit for the number of tasks.
Examples
nTask := hb_idleAdd( {|| SayTime() } )
Status
Ready
Compliance
Harbour extension similar to ft_OnTick() function available in NanForum library.
Removes the background task from the list of tasks.
Syntax
hb_idleDel( <nHandle> ) → bAction
Arguments
nHandle is the identifier of the task returned by the hb_idleAdd() function.
Returns
bActionNIL if invalid handle is passed or a codeblock that was passed to hb_idleAdd() function
Description
hb_idleDel() removes the action associated with passed identifier from the list of background tasks. The identifier should be the value returned by the previous call of hb_idleAdd() function.
If specified task is defined then the codeblock is returned otherwise the NIL value is returned.
Evaluates a single background task and calls the garbage collector.
Syntax
hb_idleState()
Arguments
None
Description
hb_idleState() requests the garbage collection and executes a single background task defined by the codeblock passed with hb_idleAdd() function. Every call to this function evaluates a different task in the order of task creation. There are no arguments passed during a codeblock evaluation.
This function can be safely called even if there are no background tasks defined.
nPosition = the position of asked variable on the list of variables with specified scope - it should start from position 1 cVarName = the value is filled with a variable name if passed by reference and nPosition is specified
Returns
The return value depends on the number of arguments passed
Description
This function retrieves the information about memvar variables. It returns either the number of variables with given scope (when the first argument is passed only) or a value of variable identified by its position in the variables' list (when second argument is passed). It also returns the name of a variable if optional third argument is passed by reference.
If requested variable doesn't exist (requested position is greater then the number of defined variables) then NIL value is returned and variable name is set to ?.
The dynamic symbols table is used to find a PUBLIC variable then the PUBLIC variables are always sorted alphabetically. The PRIVATE variables are sorted in the creation order.
Note:
Due to dynamic nature of memvar variables there is no guarantee that successive calls to retrieve the value of Nth PUBLIC variable will return the value of the same variable.
Redirect console output to printer or file and save old settings
Syntax
__TextSave( <cFile> )
Arguments
cFile is either "PRINTER" (note the uppercase) in which console output is SET to PRINTER, or a name of a text file with a default .txt extension, that is used to redirect console output.
Description
__TextSave() is used in the preprocessing of the TEXT TO command to redirect the console output while saving old settings that can be restored later by __TextRestore().
Status
Ready
Compliance
Undocumented CA-Cl*pper v5.x function available in builds with HB_CLP_UNDOC option enabled (default)
Determines whether a HELP() user defined function exists.
Syntax
__XHelp() → xValue
Arguments
None
Returns
This function returns aleatory values.
Description
This is an internal undocumented CA-Cl*pper function, which will try to call the user defined function HELP() if it is defined in the current application. This is the default SetKey() handler for the F1 key.
Status
Ready
Compliance
Undocumented CA-Cl*pper v5.x function available in builds with HB_CLP_UNDOC option enabled (default)
CLIPINIT() is one of the pre-defined INIT PROCEDURE and is executed at program startup. It declare an empty MEMVAR PUBLIC array called GetList that is going to be used by the Get system. It activates the default error handler, and (at least for the moment) calls the function that sets the default help key.
Status
Ready
Compliance
It is said that CLIPINIT() should not call the function that sets the default help key since CA-Cl*pper does it in some other place.
Waits until a connection is available on a socket created with hb_inetServer(), returns a socket that can be used to communicate with the incoming client.
On error, NIL is returned and error code sets in the passed SOCKET.
Returns a string representing the remote server address in quad dot notation, e.g. "127.0.0.1", or the local server address if the socket is server side.
TODO: have a version that returns a vector of 4 numbers.
Returns 0 on success or -1 on error; on error, the error code is set; (actually, on success the socket error code is set to 1 — socket closed )
Description
Closes the socket, notifying both ends of the communication pipe that the connection is over.
If you have threads waiting for data to be read from this socket, this method will make them stop waiting and return an error (socket closed) to their callers.
The method does not destroy the socket, which can be used by subordinate threads to check that the socket is closed, and so they should stop as soon as they can. Don't destroy the socket unless you are sure that no other thread is using it.
Connects to a remote server described by cAddress, that can be in quad dot notation (e.g. "127.0.0.1") or in DNS name (e.g. "example.org"), using the desired port.
hb_inetConnect() uses "gethostbyname" C system call to find the network address of the specified server; this means that this call is an hybrid function doing both a DNS scan and a TCP/IP connection. hb_inetConnect() is not thread safe, and the program must take care that two hb_inetConnect() functions are never called at the same moment from two different threads (or that hb_inetGetHosts() is not called in the same moment as an hb_inetConnect()).
The second version of this function accepts a pre-built socket as a parameter. This allows to kill asynchronously a thread waiting for hb_inetConnect() to connect, and then cleaning up the leftover socket data. Also, it is possible to give timeout to the given SOCKET, but this timeout will be used only in the connection phase, after that the network address resolution is completed. Use hb_inetGetHosts() and hb_inetConnectIP() for a finer timeout control. On error, the error of the returned socket is set. The error could be due to unavailable name resolving service, host name not valid, host address not reachable and host reachable but port not open.
Connects to a remote server described by cAddress, that can be specified only in quad dot IPv4 notation (e.g. "127.0.0.1"), using the desired port. This version of hb_inetConnect() does not use gethostbyname(), and thus is thread safe and can be used in combination with hb_inetGetHosts() to have a finer timeout control while connecting to a server, and a finer error control.
The second version of this function accepts a pre-built socket as a parameter. This allows to kill asynchronously a thread waiting for hb_inetConnectIP() to connect, and then cleaning up the leftover socket data. Also, it is possible to give timeout at the given SOCKET.
On error, the error of the returned socket is set.
nTimeout Socket timeout (optional) TODO: what is the scale (seconds, milliseconds?)
Returns
An INET socket
Description
Creates the raw data of the socket, that can be passed to a asynchronous connection function (hb_inetConnect() or hb_inetConnectIP()). This will prevent the connection function from allocating some data that could be never used in certain cases, i.e. an asynchronously detected timeout.
If there is data available 1 (one) is returned, 0 (zero) if there is no data and -1 if there is an error.
Description
Verifies if some data is available to be read in the socket without blocking execution of the caller.
If nMillisecs is not given, the function returns immediately 1 if there is some data to be read, 0 if there isn't any data and -1 in case of error.
If nMillisecs is given, the function will wait up to that amount of milliseconds for data to be available; if some data arrives in the meanwhile, the wait is immediately interrupted.
The next hb_inetRecv() function will read all the available data (up to the required length) without blocking.
Creates a datagram-oriented socket that will be able to send data and eventually receive data. Since the socket is not bound, the program cannot retrieve the address at which this socket appears to be, but a second socket receiving a message sent from this one would be able to reply correctly with a datagram that can be read from a non-bound socket.
If lBroadcast is set to .T., the routine creates a broadcast capable socket: it will be able to receive and send broadcast messages. On most systems this requires special user privileges.
Returns the socket, and if an error occurs, the socket error message and code are set.
Creates a datagram-oriented socket and binds it to a particular port, and eventually to a certain interface if cAddress is given and not NIL.
If lBroadcast is set to .T., the routine creates a broadcast capable socket: it will be able to receive and send broadcast messages. On most systems this requires special user privileges.
Returns the socket
If an error occurs, the socket error message and code are set.
cBuffer is the target buffer and must be passed by reference
nSize
Returns
Returns number of bytes read, or -1 on error
Description
Reads at maximum nSize bytes incoming from a UDP socket, if nSize is given, or reads at maximum cBuffer length if nSize is not given.
There isn't any guarantee that all the data required to be read is really sent from the kernel to the application: the kernel should just return the last complete datagram that has been received, up to nSize bytes.
Sends a datagram (a fixed length data) to a determined IP address (cAddress, to be specified in quad-dot notation) and port.
If nSize is not specified, all the data in cBuffer will be sent; if nSize is specified, only the first nSize bytes of cBuffer will be sent.
There isn't any guarantee that all the data required to be written is really sent to the socket: the calling program should check for the numeric return and send iteratively the unsent data to complete the message.
Anyway, the raw datagram is sent and received as once, and any data less than the system datagram size will be sent and received as a single item.
If the socket is created in broadcast mode, the cAddress element can be a broadcast address.
Returns -1 on error, or the number of bytes actually sent on success.
Returns a string describing the last error that occurred in the socket; the string is system dependent, and should be used only for debugging purposes.
Returns an array containing all the IP addresses associated with a given host name. The IP addresses returned by this function are strings in quad dot notations, e.g. "127.0.0.1", and can be directly used into hb_inetConnectIP().
cName can be any string: valid DNS names (e.g. "example.org"), locally available names (e.g. "localhost" or windows Network Neighborhood names), or even IP addresses in quad dot notation.
NOTE: This function is not thread safe (by design), and programmers must be sure not to use it at the same time in two different threads, or not to use it together with a hb_inetConnect(). If this kind of situation should ever arise, you are advised to use a thread MUTEX.
On error, and if the server cannot be found, the function returns NIL.
Returns .T. or .F. whether the internal INET system was successfully initialized
Description
Activates inet support; mainly used for winsock start up at the moment, but could be used in the future for many other purpose. Put it at the beginning of every program using INET functions.
cResult is the target buffer and must be passed by reference
nAmount is the upper limit of characters to be read from the socket. If not passed this defaults to the length of cResult
Returns
The number of the characters read from the socket.
Description
Reads from the socket into a buffer.
The parameter cString must be preallocated so that it has enough space to receive the data. The routine will block the thread until some bytes are read from the socket, the socket is closed (either from the receiver or the sender side) or a network error occurs, whichever comes first. In the latter cases, an error is set, and only the characters received until premature end of communications are returned.
Notice that there is no guarantee that all the available bytes will be read before the function returns, in fact, hb_inetRecv() returns as soon it is able to fill cString with one or more bytes. To block the current process until the whole cString is filled (or nAmount bytes are read), use the hb_inetRecvAll().
cResult is the target buffer and must be passed by reference
nAmount is the upper limit of characters to be read from the socket. If not passed this defaults to the length of cResult
Returns
The number of the characters read from the socket. Might be less than nAmount on premature socket closing or on network error.
Description
This function works exactly as hb_inetRecv() except that it blocks until nAmount bytes are read, if nAmount is given, or cString is filled for its whole length.
This function operates exactly the same way as hb_inetRecvLine(), but the "record termination" is customizable through the cBlock parameter. If not given, this parameter defaults to the CRLF sequence.
Blocks the calling thread until a sequence CRLF is read from the socket. Incremental allocation and end-of-line checking are done in an efficient way.
If an error occurs, or if the stream is closed before a CRLF is read, the function returns nothing and sets the socket error.
The returned string does not contain the trailing CRLF sequence, so an empty line is effectively returned as an empty string.
If the nBytesRead parameter is given, it will contain the number of bytes read from the socket, including the CRLF sequence, so that in normal conditions, nResult will report a count equal to the length of the returned string plus 2. nBytesRead will be 0 if stream is closed before a CRLF sequence is read, and will be -1 on error.
An optional nMaxLength parameter can be given to allow a maximum character count before the data is returned anyway. If this number is reached before a CRLF sequence is encountered, nBytesRead will contain the value one.
Finally, a nBufSize parameter can be given. If not, memory allocation will be increased by discrete amounts of 80 bytes. The programmer can provide here a different allocation strategy (e.g. setting nBufSize equal to nMaxLength, memory for reading the line will be allocated only once, at the beginning of the function).
The amount of data written, 0 (zero) if the socket is closed, or -1 on an error
Description
Send data being stored in a string over the socket.
The nLength parameter can be given to allow writing only a part of the string.
There is no guarantee that all of cBuffer will be sent, as this is a decision that is up to the OS; this function does not take care to ensure that the data is really sent; check the returned number and send the part that has not been sent.
To ensure that all the data is sent before the function returns, use the hb_inetSendAll() function.
nListenLimit is an internal parameter and rarely needs to be passed, defaults to 10
Returns
An INET socket
Description
Creates a server that can accept connections from client on a certain port.
If the computer on which hb_inetServer() is called has more than one logical interface (e.g. one network card, one loopback and one PPP address), cBindAddr can be specified to select only one of these interfaces to accept connections for this process. This is useful when a server is present on two networks, and the service is to be available only in one of them. Also, the same port on other addresses is left free to be used, so you can have different server programs running for different networks but managing the same service. For example, an FTP server available to the internal network could be radically different from an FTP server available for the internet.
nListenLimit is the number of incoming connections accepted by kernel before the kernel has the chance to report them to the application program. If the sockets receive nListenLimit connections before accepting them all, the nListenLimit + 1 connection will be notified to be "busy" by the kernel. The default value of 10 is enough for even a heavy duty server.
On error, sets error description in the newly returned socket.
cNewLang The optional ID of the language module. Possible values for cNewLang are below as defined in the Codepage library, sorted by language.
Language Codepage <cNewLang>
Bulgarian 866 BG866
Bulgarian ISO-8859-5 BGISO
Bulgarian MIK BGMIK
Bulgarian Windows-1251 BGWIN
Croatian 437 HR437
Croatian 852 HR852
Croatian Windows-1250 HRWIN
Czech 852 CS852
Czech ISO-8859-2 CSISO
Czech KAM CSKAM
Czech Windoes-1250 CSWIN
English 437 EN
French 850 FR850
German 850 DE850
German ISO-8859-1 DEWIN
Greek 737 EL737
Greek Windows-1253 ELWIN
Hungarian (ntxhu852) 852 HU852C
Hungarian (sixhu852) 852 HU852
Hungarian (sixhu852) CWI-2 HUCWI
Hungarian ISO-8859-2 HUISO
Hungarian Windows-1250 HUWIN
Italian 437 IT437
Italian 850 IT850
Italian ISO-8859-1b ITISB
Italian ISO-8859-1 ITISO
Lithuanian Windows-1257 LTWIN
Polish 852 PL852
Polish ISO-8859-2 PLISO
Polish Mazowia PLMAZ
Polish Windows-1250 PLWIN
Portuguese 850 PT850
Portuguese ISO-8859-1 PTISO
Russian 866 RU866
Russian KOI-8 RUKOI8
Russian Windows-1251 RU1251
Serbian Windows-1251 SRWIN
Slovak 852 SK852
Slovak ISO-8859-2 SKISO
Slovak Kamenicky SKKAM
Slovak Windows-1250 SKWIN
Slovenian 437 SL437
Slovenian 852 SL852
Slovenian ISO-8859-2 SLISO
Slovenian Windows-1250 SLWIN
Spanish 850 ES850
Spanish ISO-8859-1 ESWIN
Spanish Modern ISO-8859-1 ESMWIN
Swedish 850 SV850
Swedish (Clipper) 437 SV437C
Swedish ISO-8859-1 SVWIN
Turkish 857 TR857
Turkish Windows-1254 TRWIN
Ukrainian 866 UA866
Ukrainian KOI-8U UAKOI8
Ukrainian Windows-1251 UA1251
Returns
cOldLang The old language identifier
Description
hb_cdpSelect() set the active code page use by Harbour for sorting and comparing strings. The default code page use ASCII order (cLang == "EN").
NOTE: You must REQUEST every code page module you intend to use. For example: to use the French 850 code page you must add the following to your program: REQUEST HB_CODEPAGE_FR850
Examples
REQUEST HB_CODEPAGE_FR850
hb_cdpSelect( "EN" )
? hb_cdpSelect()
? hb_UTF8ToStr( "É < G is" ), hb_BChar( 144 ) < "G" // --> É < G is .F.
hb_cdpSelect( "FR850" )
? hb_cdpSelect()
? hb_UTF8ToStr( "É < G is" ), hb_BChar( 144 ) < "G" // --> É < G is .T.
nMsg is the message number to get. cLangID is an optional language module ID. Uses the currently
selected language module, if not specified.
Returns
hb_langMessage() return the text associated with the code nMsg.
Description
hb_langMessage() is similar to NationMsg() but give access to the whole list of language messages: Day and month names, generic error messages, internal errors, and others...
Use the header file hblang.ch for a list of base values for nMsg.
cNewLang The optional ID of the language module. Possible values for cNewLang are below as defined in the Lang library, sorted by language. cCodepage Optional codepage ID into which the language module strings are automatically converted by Harbour.
Language <cNewLang>
Basque eu
Belorussian be
Bulgarian bg
Catalan ca
Chinese Traditional zh
Chinese Simplified zh_sim
Croatian hr
Czech cs
Dutch nl
Esperanto eo
French fr
Galician gl
German de
Greek el
Hebrew he
Hungarian hu
Icelandic is
Indonesian id
Italian it
Korean ko
Lithuanian lt
Polish pl
Portuguese pt
Romanian ro
Russian ru
Serbian (cyrillic) sr_cyr
Serbian (latin) sr_lat
Slovak sk
Slovenian sl
Spanish es
Swedish sv
Turkish tr
Ukrainian uk
Returns
cOldLang The old language identifier
Description
This function set a default language module for date/month names, internal warnings, NatMsg messages and internal errors. When a Lang ID is selected all messages will be output with the current language selected until another one is selected or the program ends. The default language is English (cLang == "EN").
NOTE: You must REQUEST every language module you intend to use. For example: to use the Portuguese language you must add the following to your program: REQUEST HB_LANG_PT
Examples
REQUEST HB_LANG_PT
REQUEST HB_LANG_RO
REQUEST HB_LANG_ES
hb_langSelect( "pt" ) // Default language is now Portuguese
? CDoW( Date() ) // --> Segunda-feira
? "Old language id selected is", hb_langSelect() // --> pt
hb_langSelect( "ro" ) // Default language is now Romanian
? CMonth( Date() ) // --> Mai
? "Old language id selected is", hb_langSelect() // --> ro
hb_langSelect( "es" ) // Default language is now Spanish
? CMonth( Date() ) // --> Mayo
? CDoW( Date() ) // --> Lunes
cPageFrom Is the optional character code page ID of the source string. If not specified, the default code page is used.
cPageTo Is the optional character code page ID of the destination string. If not specified, the default code page is used.
Returns
hb_Translate() return destination string converted from the source string.
Description
hb_Translate() try to convert a source string from one code page into the other. If a code page ID is not recognized, or not linked in, the default code page is used. hb_Translate() is used usually to convert between the MS-DOS and the Windows code pages of the same language.
NOTE: If the source code page and target code page does not have the same number of characters, a translation cannot be done and the destination string is a copy of the source string.
NOTE: You must REQUEST every code page module you intend to use. For example: to use the CP-850 code page you must add the following to your program: #include "hbextcdp.ch"
cMessage if nMsg is a valid message selector, returns the message. If nMsg is NIL, it returns "Invalid Argument", and if nMsg is any other type it returns an empty string.
Description
NationMsg() returns international message descriptions.
Examples
// Displays "Sure Y/N: " and waits until user enters Y
// Y/N is the string for NationMsg( 12 ) with default natmsg module.
DO WHILE ! IsAffirm( cYesNo )
ACCEPT "Sure " + NationMsg( 12 ) + ": " TO cYesNo
ENDDO
nOption One of the HB_SM_* constants defined in set.ch.
lOnOff.T. to enable or .F. to disable a feature
Returns
hb_SetMacro() return the old state of requested feature.
Description
This function enables or disables some features of the macro compiler. The Harbour is extending the macro features compared to an original set available in CA-Cl*pper. Enabling/disabling some of them allows to keep strict CA-Cl*pper compatibility.
Available features are:
HB_SM_HARBOUR - enables Harbour extensions:
operators: ++, --, +=, -=, *=, /=, ^= objects: assignments to an instance variable
HB_SM_XBASE - enables other Xbase++ dialects extensions:
expanding of expressions lists
HB_SM_SHORTCUTS - enables optimized evaluation of
logical operators (.AND., .OR.)
HB_SM_PREPROC - enables preprocessing of commands
This is meaningful if Harbour is compiled with HB_MACRO_STATEMENTS flag
nIntNumber The integer portion of the numeric value.
Description
This function converts a numeric expression to an integer. All decimal digits are truncated. This function does not round a value upward or downward; it merely truncates a number at the decimal point.
This function returns the natural logarithm of the number nNumber. If nNumber is 0 or less than 0, a numeric overflow occurs, which is depicted on the display device as a series of asterisks. This function is the inverse of Exp().
xValue1 Any date or numeric value (same type as xValue).
Returns
xMax The larger numeric (or later date) value.
Description
This function returns the larger of the two passed expressions. If xValue and xValue1 are numeric data types, the value returned by this function will be a numeric data type as well and will be the larger of the two numbers passed to it. If xValue and xValue1 are date data types, the return value will be a date data type as well. It will be the later of the two dates passed to it.
This function returns the smaller of the two passed expressions. xValue and xValue1 must be the same data type. If numeric, the smaller number is returned. If dates, the earlier date is returned.
This function rounds off the value of nNumber to the number of decimal places specified by nPlace. If the value of nPlace is a negative number, the function will attempt to round nNumber in whole numbers. Numbers from 5 through 9 will be rounded up, all others will be rounded down.
This function returns the square root of nNumber. The precision of this evaluation is based solely on the setting of _SET_DECIMALS. Any negative number passed as nNumber will always return a 0.
cDataName is the symbol name of the new VAR to add.
Returns
__objAddData() return a reference to oObject.
Description
__objAddData() is a low-level class support function that add a new VAR to an object. oObject is unchanged if a symbol with the name cDataName already exist in oObject.
Examples
// create a new THappy class and add a lHappy VAR
LOCAL oHappy := HBClass():New( "THappy" )
__objAddData( oHappy, "lHappy" )
oHappy:lHappy := .T.
IF oHappy:lHappy
? "Happy, Happy, Joy, Joy !!!"
ELSE
? ":(..."
ENDIF
cInlineName is the symbol name of the new INLINE to add.
bInline is a code block to associate with the INLINE method.
Returns
__objAddInline() return a reference to oObject.
Description
__objAddInline() is a low-level class support function that add a new INLINE method to an object. oObject is unchanged if a symbol with the name cInlineName already exist in oObject.
Examples
// create a new THappy class and add a Smile INLINE method
LOCAL oHappy := HBClass():New( "THappy" )
LOCAL bInline := {| Self, nType | HB_SYMBOL_UNUSED( Self ), ;
{ ":)", ";)", "*SMILE*" }[ nType ] }
__objAddInline( oHappy, "Smile", bInline )
? oHappy:Smile( 1 ) // --> :)
? oHappy:Smile( 2 ) // --> ;)
? oHappy:Smile( 3 ) // --> *SMILE*
cMethodName is the symbol name of the new METHOD to add.
nFuncPtr is a pointer to a function to associate with the method.
Returns
__objAddMethod() return a reference to oObject.
Description
__objAddMethod() is a low-level class support function that add a new METHOD to an object. oObject is unchanged if a symbol with the name cMethodName already exist in oObject.
Note that nFuncPtr is a special pointer to a function that was created using the @ operator, see example below.
Examples
// create a new THappy class and add a Smile method
LOCAL oHappy := HBClass():New( "THappy" )
__objAddMethod( oHappy, "Smile", @MySmile() )
? oHappy:Smile( 1 ) // --> :)
? oHappy:Smile( 2 ) // --> ;)
? oHappy:Smile( 3 ) // --> *SMILE*
STATIC FUNCTION MySmile( nType )
IF HB_ISNUMERIC( nType )
SWITCH nType
CASE 1 ; RETURN ":)"
CASE 2 ; RETURN ";)"
CASE 3 ; RETURN "*SMILE*"
ENDSWITCH
ENDIF
RETURN NIL
cDataName is the symbol name of VAR to be deleted (removed) from the object.
Returns
__objDelData() return a reference to oObject.
Description
__objDelData() is a low-level class support function that delete (remove) a VAR from an object. oObject is unchanged if a symbol with the name cDataName does not exist in oObject.
Examples
// create a new THappy class and add a lHappy VAR
LOCAL oHappy := HBClass():New( "THappy" )
__objAddData( oHappy, "lHappy" )
? __objHasData( oHappy, "lHappy" ) // --> .T.
// remove lHappy VAR
__objDelData( oHappy, "lHappy" )
? __objHasData( oHappy, "lHappy" ) // --> .F.
cSymbol is the symbol name of METHOD or INLINE method to be deleted (removed) from the object.
Returns
__objDelInline() return a reference to oObject.
Description
__objDelInline() is a low-level class support function that delete (remove) a METHOD or an INLINE method from an object. oObject is unchanged if a symbol with the name cSymbol does not exist in oObject.
Examples
// create a new THappy class and add a Smile method
LOCAL oHappy := HBClass():New( "THappy" )
__objAddMethod( oHappy, "Smile", @MySmile() )
? __objHasMethod( oHappy, "Smile" ) // --> .T.
// remove Smile method
__objDelInline( oHappy, "Smile" )
? __objHasMethod( oHappy, "Smile" ) // --> .F.
STATIC FUNCTION MySmile( nType )
DO CASE
CASE nType == 1
RETURN ":)"
CASE nType == 2
RETURN ";)"
ENDCASE
RETURN NIL
cSymbol is the symbol name of METHOD or INLINE method to be deleted (removed) from the object.
Returns
__objDelMethod() return a reference to oObject.
Description
__objDelMethod() is a low-level class support function that deletes (removes) a METHOD or an INLINE method from an object. oObject is unchanged if a symbol with the name cSymbol does not exist in oObject.
xSuper is the object that may be a parent. xSuper can be either an Object or a Character string with the class name.
Returns
__objDerivedFrom() return a logical TRUE (.T.) if oObject is derived from xSuper.
Description
__objDerivedFrom() is a low-level class support function that check is one class is a super class of the other, or in other words, does class oObject a child or descendant of xSuper.
Examples
// Create three classes and check their relations
#include "hbclass.ch"
PROCEDURE Main()
LOCAL oSuper := TMood():New()
LOCAL oObject := THappy():New()
LOCAL oDress := TShirt():New()
? __objDerivedFrom( oObject, oSuper ) // --> .T.
? __objDerivedFrom( oSuper, oObject ) // --> .F.
? __objDerivedFrom( oObject, oDress ) // --> .F.
RETURN
CREATE CLASS TMood
METHOD New() INLINE Self
ENDCLASS
CREATE CLASS THappy INHERIT TMood
METHOD Smile() INLINE QOut( "*smile*" )
ENDCLASS
CREATE CLASS TShirt
VAR Color
VAR Size
METHOD New() INLINE Self
ENDCLASS
__objGetMethodList() return an array of character stings with all METHOD names for a given object. __objGetMethodList() would return an empty array {} if the given object does not contain any METHOD.
Description
__objGetMethodList() is a low-level class support function that let you find all class functions names for a given object. It is equivalent to __objGetMsgList( oObject, .F. ).
Examples
// show information about TBrowse class
LOCAL oB := TBrowseNew( 0, 0, 24, 79 ), tmp
FOR EACH tmp IN __objGetMethodList( oB )
? "METHOD name:", tmp
NEXT
lData is an optional logical value that specifies the information to return. A value of .T. instruct the function to return list of all VAR names, .F. return list of all METHOD names. Default value is .T.
nClassType is on optional numeric code for selecting which class type to return. Default value is HB_MSGLISTALL, returning the whole list.
Returns
__objGetMsgList() return an array of character stings with all VAR names or all METHOD names for a given object. __objGetMsgList() would return an empty array {} if the given object does not contain the requested information.
Description
__objGetMsgList() is a low-level class support function that let you find all instance variable or method names for a given object.
If specified, the following table shows the values for nClassType that allow you to distinguish between VAR and CLASS VAR:
hboo.ch Meaning
HB_MSGLISTALL All types
HB_MSGLISTCLASS CLASS VAR only
HB_MSGLISTPURE VAR only
VAR are instance variable usable within each object from a class, where each object has its own VARs.
CLASS VAR are shared by all objects from a Class, so the changed value within Object1 will be reflected when accessing the CLASS VAR from Object2.
Examples
#include "hboo.ch"
// show information about TBrowse class
LOCAL oB := TBrowseNew( 0, 0, 24, 79 ), tmp
FOR EACH tmp IN __objGetMsgList( oB, .T. )
? "VAR name:", tmp
NEXT
FOR EACH tmp IN __objGetMsgList( oB, .T., HB_MSGLISTCLASS )
? "CLASS VAR name:", tmp
NEXT
FOR EACH tmp IN __objGetMsgList( oB, .F. )
? "METHOD name:", tmp
NEXT
aExcept is an optional array with VAR names you want to exclude from the scan.
Returns
__objGetValueList() return a 2D array that contain pairs of a VAR symbol name and the value of VAR. __objGetValueList() would return an empty array {} if the given object does not contain the requested information.
Description
__objGetValueList() is a low-level class support function that return an array with VAR names and value, each array element is a pair of: aData[ i ][ HB_OO_DATA_SYMBOL ] contain the symbol name
aData[ i ][ HB_OO_DATA_VALUE ] contain the value of VAR
Examples
// FIXME
// show information about TBrowse class
#include "hboo.ch"
LOCAL oB := TBrowseNew( 0, 0, 24, 79 ), tmp
FOR EACH tmp IN __objGetValueList( oB )
? ;
"VAR name:", tmp[ HB_OO_DATA_SYMBOL ], ;
" value=", tmp[ HB_OO_DATA_VALUE ]
NEXT
cInlineName is the symbol name of the INLINE method to modify.
bInline is a new code block to associate with the INLINE method.
Returns
__objModInline() return a reference to oObject.
Description
__objModInline() is a low-level class support function that modify an INLINE method in an object and replace it with a new code block. oObject is unchanged if a symbol with the name cInlineName does not exist in oObject. __objModInline() is used in inheritance mechanism.
Examples
// create a new THappy class and add a Smile INLINE method
LOCAL oHappy := HBClass():New( "THappy" )
LOCAL bMyInline := {| Self, nType | HB_SYMBOL_UNUSED( Self ), ;
{ ":)", ";)" }[ nType ] }
LOCAL bYourInline := {| Self, nType | HB_SYMBOL_UNUSED( Self ), ;
{ "*SMILE*", "*WINK*" }[ nType ] }
__objAddInline( oHappy, "Smile", bMyInline )
? oHappy:Smile( 1 ) // --> :)
? oHappy:Smile( 2 ) // --> ;)
// replace Smile inline method with a new code block
__objModInline( oHappy, "Smile", bYourInline )
? oHappy:Smile( 1 ) // --> *SMILE*
? oHappy:Smile( 2 ) // --> *WINK*
cMethodName is the symbol name of the METHOD to modify.
nFuncPtr is a pointer to a new function to associate with the method.
Returns
__objModMethod() return a reference to oObject.
Description
__objModMethod() is a low-level class support function that modify a METHOD in an object and replace it with a new function. oObject is unchanged if a symbol with the name cMethodName does not exist in oObject. __objModMethod() is used in inheritance mechanism.
Note that nFuncPtr is a special pointer to a function that was created using the @ operator, see example below.
Examples
// create a new THappy class and add a Smile method
LOCAL oHappy := HBClass():New( "THappy" )
__objAddMethod( oHappy, "Smile", @MySmile() )
? oHappy:Smile( 1 ) // --> :)
? oHappy:Smile( 2 ) // --> ;)
// replace Smile method with a new function
__objAddMethod( oHappy, "Smile", @YourSmile() )
? oHappy:Smile( 1 ) // --> *SMILE*
? oHappy:Smile( 2 ) // --> *WINK*
STATIC FUNCTION MySmile( nType )
DO CASE
CASE nType == 1
RETURN ":)"
CASE nType == 2
RETURN ";)"
ENDCASE
RETURN NIL
STATIC FUNCTION YourSmile( nType )
DO CASE
CASE nType == 1
RETURN "*SMILE*"
CASE nType == 2
RETURN "*WINK*"
ENDCASE
RETURN NIL
aData is a 2D array with a pair of instance variables and values for setting those variable.
Returns
__objSetValueList() return a reference to oObject.
Description
__objSetValueList() is a low-level class support function that let you set a group of instance variables with values. each array element in aData is a pair of: aData[ i ][ HB_OO_DATA_SYMBOL ] which contain the variable name to set aData[ i ][ HB_OO_DATA_VALUE ] contain the new variable value.
Return a code block that sets/gets a value for a given field
Syntax
FieldBlock( <cFieldName> ) → bFieldBlock
Arguments
cFieldName is a string that contain the field name.
Returns
FieldBlock() return a code block that when evaluate could retrieve a field value or assigning a new value to the field. If cFieldName is not specified or from type other than character, FieldBlock() return NIL.
Description
FieldBlock() return a code block that sets/gets the value of field. When this code block is evaluated without any parameters passed then it returns the current value of the given field. If the code block is evaluated with a parameter, than its value is used to set a new value to the field, this value is also return by the block. If the block is evaluate and there is no field with the name cFieldName in the current work area, the code block return NIL.
Note that FieldBlock() works on the current work area, if you need a specific work area code block use FieldWBlock() instead.
Examples
// open a file named test.dbf that have a field named "first"
LOCAL bField
USE test
bField := FieldBlock( "first" )
? "Original value of field 'first':", Eval( bField )
Eval( bField, "Mr X new name" )
? "New value for the field 'first':", Eval( bField )
Status
Ready
Compliance
If the block is evaluate and there is no field with the name cFieldName in the current work area, the code block return NIL.
CA-Cl*pper would raise BASE/1003 error if the field does not exist.
cFieldName is a string that contain the field name.
nWorkArea is the work area number in which cFieldName exist.
Returns
FieldWBlock() return a code block that when evaluate could retrieve field value or assigning a new value for a field in a given work area. If cFieldName is not specified or from type other than character, or if nWorkArea is not specified or is not numeric FieldWBlock() return NIL.
Description
FieldWBlock() return a code block that sets/gets the value of field from a given work area. When this code block is evaluated without any parameters passed then it returns the current value of the given field. If the code block is evaluated with a parameter, than its value is used to set a new value to the field, this value is also return by the block. If the block is evaluate and there is no field with the name cFieldName in work area number nWorkArea, the code block return NIL.
Examples
LOCAL bField
// open a file named 'one' in work area 1 that has a field named "first"
SELECT 1
USE one
// open a file named 'two' in work area 2 that also has a field named "first"
SELECT 2
USE two
SELECT 1
// this block works on the field "first" that exists on work area 2
bField := FieldWBlock( "first", 2 )
? "Original 'first' values:", one->first, two->first
? "'first' value for file 'two':", Eval( bField )
Eval( bField, "'two' has updated 'first'" )
? "and now:", one->first, two->first
Status
Ready
Compliance
If the block is evaluate and there is no field with the name cFieldName in the given work area, the code block return NIL.
CA-Cl*pper would raise BASE/1003 error if the field does not exist.
Locates the position of a substring in a main string.
Syntax
At( <cSearch>, <cString> ) → nPos
Arguments
cSearch Substring to search for
cString Main string
Returns
At() return the starting position of the first occurrence of the substring in the main string
Description
This function searches the string cString for the characters in the first string cSearch. If the substring is not contained within the second expression, the function will return 0.
This function returns the ASCII character code for nAsciiNum. The number expressed must be an integer value within the range of 0 to 255 inclusive. The Chr() function will send the character returned to whatever device is presently set.
The Chr() function may be used for printing special codes as well as normal and graphics character codes.
nStart First position to search in cString, by default 1
nEnd End position to search, by default cString length
Returns
hb_At() return the starting position of the first occurrence of the substring in the main string
Description
This function searches the string cString for the characters in the first string cSearch. If the substring is not contained within the second expression, the function will return 0. The third and fourth parameters lets you indicate a starting and end offset to search in.
hb_AtI() returns the position (if any), into main string, where first time the substring appears.
Description
This function has same functionality as hb_At() with the significant difference that it's case Insensitive.
Optionally, with nStart can be defined the position into main string from where the search of cSearch must begin and with nEnd the position where it must stop. If neither of them is defined, nStart is 1st position and nEnd the ending of cString.
cDelim|`lEOL Character(s) used as delimiter of separate tokens.
If lEOL flag defined instead of cDelim, then end of line marker(s) will be used as delimiter.
lSkipStrings Boolean flag indicating if quoted substrings
will be tokenized or not.
lDoubleQuoteOnly Boolean flag indicating that only double-quoted
substrings will be tokenized.
Returns
aTokens A character array, filled with the individual tokens found.
Description
This function analyses the complex string cString and splits it into separate sub-strings (tokens) that are delimited by cDelim or by space character, if no cDelim delimiter is passed, or by EOL marker if lEOL instead of cDelim is specified.
The located tokens, are stored in an array which is returned by the function.
If lSkipStrings is .T. (default: .F.), the quoted sub-strings (if any) within cString are not tokenized. If lDoubleQuoteOnly is .T. only the double quote " is recognized as a quote sign. This argument is meaningful only when lSkipStrings is .T.
Notes
1) the tokenization process is case sensitive, in the (rare) case
where cDelim is an alphabetic character.
2) The delimiters are removed (trimmed) from tokens.
Examples
LOCAL cString := "Harbour is proven to be stable, robust and efficient."
LOCAL aTokens := hb_ATokens( cString )
AEval( aTokens, {| token, n | QOut( hb_ntos(n), token ) } )
?
aTokens := hb_ATokens( cString, "," )
AEval( aTokens, {| token, n | QOut( hb_ntos(n), token ) } )
Checks if a sub-string matches to leftmost part of a string.
Syntax
hb_LeftEq( <cString>, <cSubString> ) → lMatch
Arguments
cString Main string of comparison.
cSubString Sub-string compared to leftmost part of cString
Returns
lMatch Boolean flag indicating if the matching was successful
Description
This function checks if all characters (one by one and with the given order) of cSubString match to leftmost (same length) part of cString or in other words, checks if cString starts with cSubString, in which case returns .T., otherwise .F.
Basically it's equivalent to the expression: Left( <cString>, Len( <cSubString> ) ) == <cSubString> but faster and shorter.
Return the text file's contents as a character string
Syntax
hb_MemoRead( <cFileName> ) → cString
Arguments
cFileName is the file name to read from disk.
It must include the file extension. If file to be read lives in another directory, you must include the path.
Returns
Returns the contents of a text file as a character string.
If cFileName cannot be found or read hb_MemoRead() returns an empty string ("").
Description
hb_MemoRead() is a function that reads the content of a text file (till now) from disk (floppy, HDD, CD-ROM, etc.) into a memory string. In that way you can manipulate as any character string or assigned to a memo field to be saved in a database.
hb_MemoRead() function is used together with MemoEdit() and hb_MemoWrit() to get from disk text from several sources that would be edited, searched, replaced, displayed, etc.
It is used to import data from other sources to our database.
Note: hb_MemoRead() does not use the settings SET DEFAULT or SET PATH to search for cFileName. It searches for cFileName in the current directory.
Over a network, hb_MemoRead() attempts to open cFileName in read-only mode and shared. If the file is used in mode exclusive by another process, the function will returns a null string ("").
hb_MemoRead() vs MemoRead(): hb_MemoRead() is identical to MemoRead() except it won't truncate the last byte (on non-Unix compatible systems) if it's a EOF char.
Examples
// This example uses hb_MemoRead() to assign the contents of a text
// file to a character variable for later search
LOCAL cFile := "account.prg"
LOCAL cString := hb_MemoRead( cFile )
LOCAL cCopyright := "Melina"
IF ! cCopyright $ cString // check for copyright
? hb_MemoWrit( cFile, cCopyright + cString ) // if not, add it!
ENDIF
Write a memo field or character string to a text file on disk
Syntax
hb_MemoWrit( <cFileName>, <cString> ) → lSuccess
Arguments
cFileName is the file name to be written to disk.
It must include the file extension. If file to be read lives in another directory, you must include the path.
cString Is the memo field or character string, to be write to
cFile.
Returns
Function returns true (.T.) if the writing operation was successful; otherwise, it returns false (.F.).
Description
This a function that writes a memo field or character string to a text file on disk (floppy, HDD, CD-ROM, etc.) If you not specified a path, hb_MemoWrit() writes cFileName to the current directory. If cFileName exists, it is overwritten.
hb_MemoWrit() function is used together with hb_MemoRead() and MemoEdit() to save to disk text from several sources that was edited, searched, replaced, displayed, etc.
Note that hb_MemoWrit() do not use the directory settings SET DEFAULT.
hb_MemoWrit() vs MemoWrit(): hb_MemoWrit() never writes the obsolete EOF char at the end of the file.
Examples
// This example uses hb_MemoWrit() to write the contents of a character
// variable to a text file.
LOCAL cFile := "account.prg"
LOCAL cString := hb_MemoRead( cFile )
LOCAL cCopyright := "Melina"
IF ! cCopyright $ cString // check for copyright
? hb_MemoWrit( cFile, cCopyright + cString ) // if not, add it!
ENDIF
This function converts the given nValue numeric value to a string value, while (trying to) keep all or at least nDecs significant digits in double numbers, unless <nDecs> is lesser than actual decimal digits of nValue, in which case the result will be rounded.
SET DECIMAL setting has no effect on the returned value (ignored), which means that, unlike e.g. Str(), all non-significant digits (e.g.: trailing decimal zeros) will be removed. Likewise, all leading empty spaces will be trimmed.
Returns stringified value of <nValue>, preserving all (or at least <nDecs>) significant digits, if any. Interestingly, if <nValue> is NIL or not numeric, this function will return a null string and, unlike Str(), will NOT cause an RTE. NOTE: new function, available after 2016-06-20 21:59 UTC+0200 commit,
(it is not available in earlier versions).
Examples
LOCAL n := ( 5 / 2 ) + 0.009
? hb_ntoc( n ) // --> 2.509
? Str( n ) // --> 2.51
? hb_ntoc( n, 2 ) // --> 2.51
? Str( n, 5, 2 ) // --> 2.51
? hb_ntos( n ) // --> 2.51
? "--- decimals set to 7 ----"
SET DECIMALS TO 7
? Str( n ) // --> 2.51
? hb_ntoc( n ) // --> 2.509
? Str( n, 10, 7 ) // --> 2.5090000
? hb_ntoc( n, 7 ) // --> 2.509
? "--- pass non numeric / NIL value ----"
? Str( "42" ) // --> RTE
This function converts any numeric value to a string, trimming all the leading empty spaces. If <nValue> is NIL or not numeric, this function will return a null string.
Essentially, hb_ntos() function is equivalent to LTrim( Str( <nValue> ) ) but quite simpler and faster.
Examples
LOCAL n := ( 5 / 2 ) + 0.009
? Str( n ) // --> 2.51
? hb_ntos( n ) // --> 2.51
nStart First position to search in cString, by default 1.
nEnd End position to search, by default cString length
Returns
hb_RAt() return the location of beginning position of last occurrence a substring of a string.
Description
This function searches for last occurrence a cSearch in cString. If the function is unable to find any occurrence of cSearch in cString, the return value is 0. 3rd and 4th parameters define inclusive range for 2nd parameter on which operation is performed. If 3rd and 4th parameters is not specified, then hb_RAt() is equal to RAt().
Examples
LOCAL cString := "acdefcdeedcb"
LOCAL cSearch := "cde"
LOCAL i, y, r
LOCAL nLen := Len( cString )
FOR y := 1 TO nLen
FOR i := 1 TO nLen
IF ( r := hb_RAt( cSearch, cString, y, i ) ) > 0
? 'hb_RAt( "' + cSearch + '", "' + cString + '",', hb_ntos( y ) + ",", hb_ntos( i ), ") =", ;
hb_ntos( r )
ENDIF
NEXT
NEXT
? hb_RAt( cSearch, "abcdefgfedcba" ) // --> 3
Checks if leftmost character in a string is an alphabetic character
Syntax
IsAlpha( <cString> ) → lAlpha
Arguments
cString Any character string
Returns
lAlpha Logical true (.T.) or false (.F.).
Description
This function return a logical true (.T.) if the first character in cString is an alphabetic character. If not, the function will return a logical false (.F.).
This function takes the character string cString and checks to see if the leftmost character is a digit, from 1 to 9. If so, the function will return a logical true (.T.); otherwise, it will return a logical false (.F.).
Checks if leftmost character is an lowercased letter.
Syntax
IsLower( <cString> ) → lLower
Arguments
cString Any character string
Returns
lLower Logical true (.T.) or false (.F.).
Description
This function takes the character string cString and checks to see if the leftmost character is a lowercased letter. If so, the function will return a logical true (.T.); otherwise, it will return a logical false (.F.).
Checks if leftmost character is an uppercased letter.
Syntax
IsUpper( <cString> ) → lUpper
Arguments
cString Any character string
Returns
lUpper Logical true (.T.) or false (.F.).
Description
This function checks to see if the leftmost character if cString is a uppercased letter. If so, the function will return a logical true (.T.); otherwise, it will return a logical false (.F.).
Universally lowercases a character string expression.
Syntax
Lower( <cString> ) → cLowerString
Arguments
cString Any character expression.
Returns
cLowerString Lowercased value of cString
Description
This function converts any character expression passes as cString to its lowercased representation. Any non alphabetic character withing cString will remain unchanged.
Return the text file's contents as a character string
Syntax
MemoRead( <cFileName> ) → cString
Arguments
cFileName is the file name to read from disk.
It must include the file extension. If file to be read lives in another directory, you must include the path.
Returns
Returns the contents of a text file as a character string.
If cFileName cannot be found or read MemoRead() returns an empty string ("").
Description
MemoRead() is a function that reads the content of a text file (till now) from disk (floppy, HDD, CD-ROM, etc.) into a memory string. In that way you can manipulate as any character string or assigned to a memo field to be saved in a database.
MemoRead() function is used together with MemoEdit() and MemoWrit() to get from disk text from several sources that would be edited, searched, replaced, displayed, etc.
It is used to import data from other sources to our database.
Note: MemoRead() does not use the settings SET DEFAULT or SET PATH to search for cFileName. It searches for cFileName in the current directory.
Over a network, MemoRead() attempts to open cFileName in read-only mode and shared. If the file is used in mode exclusive by another process, the function will returns a null string ("").
Examples
// This example uses MemoRead() to assign the contents of a text
// file to a character variable for later search
LOCAL cFile := "account.prg"
LOCAL cString := MemoRead( cFile )
LOCAL cCopyright := "Melina"
IF ! cCopyright $ cString // check for copyright
? MemoWrit( cFile, cCopyright + cString ) // if not, add it!
ENDIF
Write a memo field or character string to a text file on disk
Syntax
MemoWrit( <cFileName>, <cString> ) → lSuccess
Arguments
cFileName is the file name to be written to disk.
It must include the file extension. If file to be read lives in another directory, you must include the path.
cString Is the memo field or character string, to be write to
cFile.
Returns
Function returns true (.T.) if the writing operation was successful; otherwise, it returns false (.F.).
Description
This a function that writes a memo field or character string to a text file on disk (floppy, HDD, CD-ROM, etc.) If you not specified a path, MemoWrit() writes cFileName to the current directory. If cFileName exists, it is overwritten.
MemoWrit() function is used together with MemoRead() and MemoEdit() to save to disk text from several sources that was edited, searched, replaced, displayed, etc.
Note that MemoWrit() do not use the directory settings SET DEFAULT.
Examples
// This example uses MemoWrit() to write the contents of a character
// variable to a text file.
LOCAL cFile := "account.prg"
LOCAL cString := MemoRead( cFile )
LOCAL cCopyright := "Melina"
IF ! cCopyright $ cString // check for copyright
? MemoWrit( cFile, cCopyright + cString ) // if not, add it!
ENDIF
This function takes an date, number or character expression xVal and attempt to center the expression within a string of a given width expressed as nWidth. The default character used to pad either side of xVal will be a blank space. This character may be explicitly specified the value of cFill.
If the length of xVal is longer then nWidth, this function will truncate the string xVal from the leftmost side to the length of nWidth.
This function takes an date, number, or character expression xVal and attempt to left-justify it within a string of a given width expressed as nWidth. The default character used to pad left side of xVal will be an blank space; however, this character may be explicitly specified the value of cFill.
If the length of xVal is longer then nWidth, this function will truncate the string xVal from the leftmost side to the length of nWidth.
This function takes an date, number, or character expression xVal and attempt to right-justify it within a string of a given width expressed as nWidth. The default character used to pad right side of xVal will be an blank space; however, this character may be explicitly specified the value of cFill.
If the length of xVal is longer then nWidth, this function will truncate the string xVal from the leftmost side to the length of nWidth.
Searches for last occurrence a substring of a string.
Syntax
RAt( <cSearch>, <cString> ) → nPos
Arguments
cSearch Substring to search for
cString Main string
Returns
RAt() return the location of beginning position of last occurrence a substring of a string.
Description
This function searches for last occurrence a cSearch in cString. If the function is unable to find any occurrence of cSearch in cString, the return value is 0.
cReplicateString A character expression contain the cString fill character.
Description
This function returns a string composed of nSize repetitions of cString. The length of the character string returned by this function is limited to the memory available.
nNumber is the numeric expression to be converted to a character string.
nLength is the length of the character string to return, including decimal digits, decimal point, and sign.
nDecimals is the number of decimal places to return.
Returns
Str() returns nNumber formatted as a character string. If the optional length and decimal arguments are not specified, Str() returns the character string according to the following rules:
Results of Str() with No Optional Arguments
Expression Return Value Length
Field Variable Field length plus decimals
Expressions/constants Minimum of 10 digits plus decimals
Val() Minimum of 3 digits
Month()/Day() 3 digits
Year() 5 digits
RecNo() 7 digits
Description
Str() is a numeric conversion function that converts numeric values to character strings. It is commonly used to concatenate numeric values to character strings. Str() has applications displaying numbers, creating codes such as part numbers from numeric values, and creating index keys that combine numeric and character data.
Str() is like Transform(), which formats numeric values as character strings using a mask instead of length and decimal specifications.
The inverse of Str() is Val(), which converts character numbers to numerics.
* If nLength is less than the number of whole number digits in
nNumber, Str() returns asterisks instead of the number.
* If nLength is less than the number of decimal digits
required for the decimal portion of the returned string, Harbour rounds the number to the available number of decimal places.
* If nLength is specified but nDecimals is omitted (no
decimal places), the return value is rounded to an integer.
cLocString The string to locate in the main string
cRepString The string to replace the cLocString
nPos The first occurrence to be replaced
nOccurrences Number of occurrence to replace
Returns
cReturn Formatted string
Description
This function searches for any occurrence of cLocString in cString and replaces it with cRepString. If cRepString is not specified, a NULL byte will replace cLocString.
If nPos is used, its value defines the first occurrence to be replaced. The default value is 1. Additionally, if used, the value of nOccurrences tell the function how many occurrences of cLocString in cString are to the replaced. The default of nOccurrences is all occurrences.
Examples
? StrTran( "Harbour Power", " ", " " ) // --> "Harbour Power"
? StrTran( "Harbour Power The Future of xBase", " ", " " , , 2 )
// --> "Harbour Power The future of xBase"
nNumber is the numeric expression to be converted to a character string.
nLength is the length of the character string to return, including decimal digits, decimal point, and sign.
nDecimals is the number of decimal places to return.
Returns
StrZero() returns nNumber formatted as a character string. If the optional length and decimal arguments are not specified, StrZero() returns the character string according to the following rules:
Results of StrZero() with No Optional Arguments
Expression Return Value Length
Field Variable Field length plus decimals
Expressions/constants Minimum of 10 digits plus decimals
Val() Minimum of 3 digits
Month()/Day() 3 digits
Year() 5 digits
RecNo() 7 digits
Description
StrZero() is a numeric conversion function that converts numeric values to character strings. It is commonly used to concatenate numeric values to character strings. StrZero() has applications displaying numbers, creating codes such as part numbers from numeric values, and creating index keys that combine numeric and character data.
StrZero() is like Transform(), which formats numeric values as character strings using a mask instead of length and decimal specifications.
The inverse of StrZero() is Val(), which converts character numbers to numerics.
* If nLength is less than the number of whole number digits in
nNumber, Str() returns asterisks instead of the number.
* If nLength is less than the number of decimal digits
required for the decimal portion of the returned string, Harbour rounds the number to the available number of decimal places.
* If nLength is specified but nDecimals is omitted (no
decimal places), the return value is rounded to an integer.
The StrZero() function was part of the CA-Cl*pper samples.
This functions returns a character string formed from cString, starting at the position of nStart and continuing on for a length of nLen characters. If nLen is not specified, the value will be all remaining characters from the position of nStart.
The value of nStart may be negative. If it is, the direction of operation is reversed from a default of left-to-right to right-to-left for the number of characters specified in nStart. If the number of characters from nStart to the end of the string is less than nLen the rest are ignored.
cFormatted Formatted expression in character format
Description
This function returns xExpression in the format of the picture expression passed to the function as cTemplate.
Their are two components that can make up cTemplate : a function string and a template string. Function strings are those functions that globally tell what the format of xExpression should be. These functions are represented by a single character precede by the @ symbol.
There are a couple of rules to follow when using function strings and template strings:
- First, a single space must fall between the function template
and the template string if they are used in conjunction with one another.
- Second, if both components make up the value of cTemplate, the
function string must precede the template string. Otherwise, the function string may appear with out the template string and vice versa.
The table below shows the possible function strings available with the Transform() function.
@B Left justify the string within the format.
@C Issue a CR after format is numbers are positive.
@D Put dates in SET DATE format.
@E Put dates in BRITISH format.
@L Make a zero padded string out of the number.
@R Insert non template characters.
@X Issue a DB after format is numbers are negative.
@Z Display any zero as blank spaces.
@( Quotes around negative numbers
@! Convert alpha characters to uppercased format.
The second part of cTemplate consists of the format string. Each character in the string may be formatted based on using the follow characters as template markers for the string.
A,N,X,9,# Any data type
L Shows logical as "T" or "F"
Y Shows logical as "Y" or "N"
! Convert to uppercase
$ Dollar sing in place of leading spaces in numeric expression
* Asterisks in place of leading spaces in numeric expression
, Commas position
. Decimal point position
Examples
LOCAL cString := "This is harbour"
LOCAL nNumber := 9923.34
LOCAL nNumber1 := -95842.00
LOCAL lValue := .T.
LOCAL dDate := Date()
? "working with String"
? "Current String is", cString
? "All uppercased", Transform( cString, "@!" )
? "Date is", dDate
? "Date is", Transform( dDate, "@D" )
? Transform( nNumber, "@L 99999999" ) // --> "009923.34"
? Transform( 0 , "@L 9999" ) // --> "0000"
Status
Ready
Compliance
The @L function template is a FoxPro/Xbase++ Extension
Show the content of a file on the console and/or printer
Syntax
__TypeFile( <cFile>, [<lPrint>] ) → NIL
Arguments
cFile is a name of the file to display. If the file have an extension, it must be specified (there is no default value).
lPrint is an optional logical value that specifies whether the output should go only to the screen (.F.) or to both the screen and printer (.T.), the default is (.F.).
Returns
__TypeFile() always return NIL.
Description
__TypeFile() function type the content of a text file on the screen with an option to send this information also to the printer. The file is displayed as is without any headings or formatting.
If cFile contain no path, __TypeFile() try to find the file first in the SET DEFAULT directory and then in search all of the SET PATH directories. If cFile cannot be found a run-time error occur.
Use SET CONSOLE OFF to suppress screen output. You can pause the output using Ctrl-S, press any key to resume.
__TypeFile() function is used in the preprocessing of the TYPE command.
Examples
// The following examples assume a file name `test.txt` exist in all
// specified paths, a run-time error would displayed if it does not
// display test.txt file on screen
__TypeFile( "test.txt" )
// display test.txt file on screen and printer
__TypeFile( "test.txt", .T. )
// display test.txt file on printer only
SET CONSOLE OFF
__TypeFile( "test.txt", .T. )
SET CONSOLE ON
Restore screen image and coordinate from an internal buffer
Syntax
RESTORE SCREEN
Arguments
none.
Description
RESTORE SCREEN restores saved image of the whole screen from an internal buffer that was saved by SAVE SCREEN, it also restore cursor position. After a call to 'RESTORE SCREEN` the internal buffer is cleared.
RESTORE SCREEN command is preprocessed into __XRestScreen() function during compile time. Note that RESTORE SCREEN FROM is preprocessed into RestScreen() function.
Examples
// save the screen, display list of files than restore the screen
SAVE SCREEN
DIR *.*
RESTORE SCREEN
Save whole screen image and coordinate to an internal buffer
Syntax
SAVE SCREEN
Arguments
none.
Description
SAVE SCREEN saves the image of the whole screen into an internal buffer, it also save current cursor position. The information could later be restored by RESTORE SCREEN. Each call to SAVE SCREEN overwrite the internal buffer.
SAVE SCREEN command is preprocessed into __XSaveScreen() function during compile time. Note that SAVE SCREEN TO is preprocessed into SaveScreen() function.
Examples
// save the screen, display list of files than restore the screen
SAVE SCREEN
DIR *.*
RESTORE SCREEN
nRow is the row number to display the menu cPrompt. Value could range from zero to MaxRow().
nCol is the column number to display the menu cPrompt. Value could range from zero to MaxCol().
cPrompt is the menu item character string to display.
xMsg define a message to display each time this menu item is highlighted. xMsg could be a character string or code block that is evaluated to a character string. If xMsg is not specified or of the wrong type, an empty string ("") would be used.
Returns
__AtPrompt() always return .F.
Description
With __AtPrompt() you define and display a menu item, each call to __AtPrompt() add another item to the menu, to start the menu itself you should call the __MenuTo() function (MENU TO command). You can define any row and column combination and they will be displayed at the order of definition. After each call to __AtPrompt(), the cursor is placed one column to the right of the last text displayed, and Row() and Col() are updated.
@...PROMPT command is preprocessed into __AtPrompt() function during compile time.
Examples
LOCAL nChoice
// display a two line menu with status line at the bottom
// let the user select favorite day
SET MESSAGE TO 24 CENTER
@ 10, 2 PROMPT "Sunday" MESSAGE "This is the 1st item"
@ 11, 2 PROMPT "Monday" MESSAGE "Now we're on the 2nd item"
MENU TO nChoice
DO CASE
CASE nChoice == 0 // user press <Esc> key
QUIT
CASE nChoice == 1 // user select 1st menu item
? "Guess you don't like Mondays"
CASE nChoice == 2 // user select 2nd menu item
? "Just another day for some"
ENDCASE
bBlock is a set/get code block for variable named cVariable.
cVariable is a character string that contain the name of the variable to hold the menu choices, if this variable does not exist a PRIVATE variable with the name cVariable would be created to hold the result.
Returns
__MenuTo() return the number of select menu item, or 0 if there was no item to select from or if the user pressed the Esc key.
Description
__MenuTo() invoked the menu define by previous __AtPrompt() call and display a highlight bar that the user can move to select an option from the menu. If cVariable does not exist or not visible, a PRIVATE variable named cVariable is created and hold the current menu selection. If there is a variable named cVariable, its value is used to select the first highlighted item.
Menu prompts and messages are displayed in current Standard color, highlighted bar is displayed using current Enhanced color.
Pressing the arrow keys move the highlighted bar. When a menu item is highlighted the message associated with it is displayed on the line specified with SET MESSAGE. If SET WRAP is ON and the user press up arrow while on the first selection the last menu item is highlighted, if the user press Down arrow while on the last item, the first item is highlighted.
Following are active keys that handled by __MenuTo():
key Meaning
Up Move to previous item
Down Move to next item
Left Move to previous item
Right Move to next item
Home Move to the first item
End Move to the last item
PgUp Select menu item, return position
PgDn Select menu item, return position
Enter Select menu item, return position
Esc Abort selection, return 0
First letter Select next menu with the same first letter,
return this item position.
upon exit the cursor is placed at MaxRow() - 1, 0 __MenuTo() can be nested without loosing the previous prompts.
MENU TO command is preprocessed into __MenuTo() function during compile time.
Examples
LOCAL nChoice
// display menu item on each screen corner and let user select one
CLS
SET MESSAGE TO MaxRow() / 2 CENTER
SET WRAP ON
@ 0 , 0 PROMPT "1. Upper left" MESSAGE " One "
@ 0 , MaxCol() - 16 PROMPT "2. Upper right" MESSAGE " Two "
@ MaxRow() - 1, MaxCol() - 16 PROMPT "3. Bottom right" MESSAGE "Three"
@ MaxRow() - 1, 0 PROMPT "4. Bottom left" MESSAGE "Four "
MENU TO nChoice
SetPos( MaxRow() / 2, MaxCol() / 2 - 10 )
IF nChoice == 0
?? "<Esc> was pressed"
ELSE
?? "Selected option is", nChoice
ENDIF
The //NOALERT command-line switch cause Cl*pper to ignore calls to the Alert() function, this function override this behavior and always display Alert() dialog box.
Examples
// make sure alert are been displayed
__NoNoAlert()
Status
Ready
Compliance
Undocumented CA-Cl*pper v5.x function available in builds with HB_CLP_UNDOC option enabled (default)
Restore screen image and coordinate from an internal buffer
Syntax
__XRestScreen()
Arguments
none.
Description
__XRestScreen() restores saved image of the whole screen from an internal buffer that was saved by __XSaveScreen(), it also restore cursor position. After a call to __XRestScreen() the internal buffer is cleared.
RESTORE SCREEN command is preprocessed into __XRestScreen() function during compile time. Note that RESTORE SCREEN FROM is preprocessed into RestScreen() function.
__XRestScreen() is a compatibility function, it is superseded by RestScreen() which allow you to restore the screen from a variable.
Examples
// save the screen, display list of files than restore the screen
SAVE SCREEN
DIR *.*
RESTORE SCREEN
Save whole screen image and coordinate to an internal buffer
Syntax
__XSaveScreen()
Arguments
none.
Description
__XSaveScreen() saves the image of the whole screen into an internal buffer, it also save current cursor position. The information could later be restored by __XRestScreen(). Each call to __XSaveScreen() overwrite the internal buffer.
SAVE SCREEN command is preprocessed into __XSaveScreen() function during compile time. Note that SAVE SCREEN TO is preprocessed into SaveScreen() function.
__XSaveScreen() is a compatibility function, it is superseded by SaveScreen() which allow you to save part or all the screen into a variable.
Examples
// save the screen, display list of files than restore the screen
SAVE SCREEN
DIR *.*
RESTORE SCREEN
nTop - topmost row used to display array (default 0)
nLeft - leftmost row used to display array (default 0)
nBottom - bottommost row used to display array (default MaxRow())
nRight - rightmost row used to display array (default MaxCol())
acMenuItems - the character array of items from which to select
alSelableItems - an array of items, either logical or character,
which is used to determine if a particular item may be selected. If the type of a given item is character, it is macro evaluated, and the result is expected to be a logical. A value of .T. means that the item may be selected, .F. that it may not. (See next argument: lSelectableItems)
lSelableItems - a logical value which is used to apply to all
items in acMenuItems. If .T., all items may be selected; if .F., none may be selected. (See previous argument: alSelectableItems) Default .T.
cUserFunction - the name of a function to be called which may
affect special processing of keystrokes. It is specified without parentheses or parameters. When it is called, it will be supplied with the parameters: nMode, nCurElement, and nRowPos. Default NIL.
bUserBlock - a codeblock to be called which may
affect special processing of keystrokes. It should be specified in the form {| nMode, nCurElemenet, nRowPos | MyFunc( nMode, nCurElemenet, nRowPos ) }. Default NIL.
nInitialItem - the number of the element to be highlighted as
the current item when the array is initially displayed. 1 origin. Default 1.
nWindowRow - the number of the window row on which the initial
item is to be displayed. 0 origin. Default 0.
Returns
nPosition - the number of the item to be selected, or 0 if the selection was aborted.
Description
Allows selection of an element from an array. Please see standard CA-Cl*pper documentation for AChoice() for additional detail.
Examples
LOCAL aItems := { "One", "Two", "Three" }
LOCAL nChoice := AChoice( 10, 10, 20, 20, aItems )
IF nChoice == 0
? "You did not choose an item"
ELSE
? ;
"You chose element", hb_ntos( nChoice ), ;
"which has a value of", aItems[ nChoice ]
ENDIF
Alert( <xMessage>, [<aOptions>], [<cColorNorm>], [<nDelay>] ) → nChoice or NIL
Arguments
xMessage Message to display in the dialog box. xMessage can be of any Harbour type. If xMessage is an array of Character strings, each element would be displayed in a new line. If xMessage is a Character string, you could split the message to several lines by placing a semicolon ; in the desired places.
aOptions Array with available response. Each element should be Character string. If omitted, default is { "Ok" }.
cColorNorm Color string to paint the dialog box with. If omitted, default color is "W+/R".
nDelay Number of seconds to wait to user response before abort. Default value is 0, that wait forever.
Returns
Alert() return Numeric value representing option number chosen.
If Esc was pressed, return value is zero.
The return value is NIL if Alert() is called with no parameters, or if xMessage type is not Character and HB_CLP_STRICT option was used. If nDelay seconds had passed without user response, the return value is 1.
Description
Alert() display simple dialog box on screen and let the user select one option. The user can move the highlight bar using arrow keys or Tab key. To select an option the user can press Enter, Space or the first letter of the option.
If the program is executed with the //NOALERT command-line switch, nothing is displayed and it simply returns NIL. This switch could be overridden with __NoNoAlert().
If the GT system is linked in, Alert() display the message using the full screen I/O system, if not, the information is printed to the standard output using OutStd().
Examples
LOCAL cMessage, aOptions, nChoice
// harmless message
cMessage := "Major Database Corruption Detected!;" + ;
"(deadline in few hours);;" + ;
"where DO you want to go today?"
// define response option
aOptions := { "Ok", "www.example.org", "Oops" }
// show message and let end user select panic level
nChoice := Alert( cMessage, aOptions )
DO CASE
CASE nChoice == 0
// do nothing, blame it on some one else
CASE nChoice == 1
? "Please call home and tell them you're going to be late"
CASE nChoice == 2
// make sure your resume is up to date
CASE nChoice == 3
? "Oops mode is not working in this version"
ENDCASE
Status
Ready
Compliance
This function is sensitive to HB_CLP_STRICT settings during the compilation of src/rtl/alert.prg
defined: xMessage accept Character values only and return NIL if other types are passed.
undefined: xMessage could be any type, and internally converted to Character string. If type is Array, multi-line message is displayed.
defined: Only the first four valid aOptions are taken.
undefined: aOptions could contain as many as needed options.
If HB_COMPAT_C53 was define during compilation of src/rtl/alert.prg the Left-Mouse button could be used to select an option.
The interpretation of the //NOALERT command-line switch is done only if HB_CLP_UNDOC was define during compilation of src/rtl/alert.prg
cColorNorm is a Harbour extension, or at least undocumented in Clipper 5.2 NG.
Browse( [<nTop>, <nLeft>, <nBottom>, <nRight>] ) → lOk
Arguments
nTop coordinate for top row display.
nLeft coordinate for left column display.
nBottom coordinate for bottom row display.
nRight coordinate for right column display.
Returns
Browse() return .F. if there is no database open in this work area, else it return .T.
Description
Browse() is a general purpose database browser, without any thinking you can browse a file using the following keys:
Key Meaning
Left Move one column to the left (previous field)
Right Move one column to the right (next field)
Up Move up one row (previous record)
Down Move down one row (next record)
PgUp Move to the previous screen
PgDn Move to the next screen
Ctrl+PgUp Move to the top of the file
Ctrl+PgDn Move to the end of the file
Home Move to the leftmost visible column
End Move to the rightmost visible column
Ctrl+Left Pan one column to the left
Ctrl+Right Pan one column to the right
Ctrl+Home Move to the leftmost column
Ctrl+End Move to the rightmost column
Esc Terminate Browse()
On top of the screen you see a status line with the following indication:
Record ###/### Current record number / Total number of records.
<none> There are no records, the file is empty.
<new> You are in append mode at the bottom of file.
<Deleted> Current record is deleted.
<bof> You are at the top of file.
You should pass whole four valid coordinate, if less than four parameters are passed to Browse() the coordinate are default to: 1, 0, MaxRow(), MaxCol().
Examples
// this one shows you how to browse around
USE test
Browse()
nTop coordinate for top row display. nTop could range from 0 to MaxRow(), default is 0.
nLeft coordinate for left column display. nLeft could range from 0 to MaxCol(), default is 0.
nBottom coordinate for bottom row display. nBottom could range from 0 to MaxRow(), default is MaxRow().
nRight coordinate for right column display. nRight could range from 0 to MaxCol(), default is MaxCol().
acColumns is an array of character expressions that contain database fields names or expressions to display in each column. If not specified, the default is to display all fields from the database in the current work area.
xUserFunc is a name of a user defined function or a code block that would be called every time unrecognized key is been pressed or when there are no keys waiting to be processed and dbEdit() goes into idle mode. If xUserFunc is a character string, it must contain root name of a valid user define function without parentheses. Both the user define function or the code block should accept two parameters: nMode, nCurrentColumn. Both should return a numeric value that correspond to one of the expected return codes (see table below for a list of nMode and return codes).
xColumnSayPictures is an optional picture. If xColumnSayPictures is a character string, all columns would used this value as a picture string. If xColumnSayPictures is an array, each element should be a character string that correspond to a picture string for the column with the same index. Look at the help for @...SAY to get more information about picture values.
xColumnHeaders contain the header titles for each column, if this is a character string, all columns would have that same header, if this is an array, each element is a character string that contain the header title for one column. Header may be split to more than one line by placing semicolon ; in places where you want to break line. If omitted, the default value for each column header is taken from acColumns or field name if acColumns was not specified.
xHeadingSeparators is an array that contain characters that draw the lines separating the headers and the fields data. Instead of an array you can use a character string that would be used to display the same line for all fields. Default value is a double line.
xColumnSeparators is an array that contain characters that draw the lines separating displayed columns. Instead of an array you can use a character string that would be used to display the same line for all fields. Default value is a single line.
xFootingSeparators is an array that contain characters that draw the lines separating the fields data area and the footing area. Instead of an array you can use a character string that would be used to display the same line for all footers. Default is to have to no footing separators.
xColumnFootings contain the footing to be displayed at the bottom of each column, if this is a character string, all columns would have that same footer, if this is an array, each element is a character string that contain the footer for one column. Footer may be split to more than one line by placing semicolon ; in places where you want to break line. If omitted, no footer are displayed.
Returns
dbEdit() return .F. if there is no database in use or if the number of columns to display is zero, else dbEdit() return .T.
Description
dbEdit() display and edit records from one or more work areas in a grid on screen. Each column is defined by element from acColumns and is the equivalent of one field. Each row is equivalent of one database record.
Following are active keys that handled by dbEdit():
Key Meaning
Left Move one column to the left (previous field)
Right Move one column to the right (next field)
Up Move up one row (previous record)
Down Move down one row (next record)
PgUp Move to the previous screen
PgDn Move to the next screen
Ctrl+PgUp Move to the top of the file
Ctrl+PgDn Move to the end of the file
Home Move to the leftmost visible column
End Move to the rightmost visible column
Ctrl+Left Pan one column to the left
Ctrl+Right Pan one column to the right
Ctrl+Home Move to the leftmost column
Ctrl+End Move to the rightmost column
When xUserFunc is omitted, two more keys are active:
Key Meaning
Esc Terminate Browse()
Enter Terminate Browse()
When dbEdit() execute xUserFunc it pass the following arguments: nMode and the index of current record in acColumns. If acColumns is omitted, the index number is the FieldName() number of the open database structure.
dbEdit()nMode could be one of the following:
dbedit.ch Meaning
DE_IDLE dbEdit() is idle, all movement keys have been handled.
DE_HITTOP Attempt to cursor past top of file.
DE_HITBOTTOM Attempt to cursor past bottom of file.
DE_EMPTY No records in work area, database is empty.
DE_EXCEPT Key exception.
The user define function or code block must return a value that tell dbEdit() what to do next.
User function return codes:
dbedit.ch Meaning
DE_ABORT Abort dbEdit().
DE_CONT Continue dbEdit() as is.
DE_REFRESH Force reread/redisplay of all data rows.
The user function is called once in each of the following cases: - The database is empty. - The user try to move past top of file or past bottom file. - Key exception, the uses had pressed a key that is not handled by dbEdit(). - The keyboard buffer is empty or a screen refresh had just occurred dbEdit() is a compatibility function, it is superseded by the TBrowse class and there for not recommended for new applications.
Examples
// Browse a file using default values
USE test
dbEdit()
Status
Started
Compliance
xUserFunc can take a code block value, this is a Harbour extension.
CA-Cl*pper will throw an error if there's no database open, Harbour would return .F.
CA-Cl*pper is buggy and will throw an error if the number of columns is zero, Harbour would return .F.
The CA-Cl*pper 5.2 NG state that the return value is NIL, this is wrong and should be read logical.
There is an undocumented result code (3) from the user defined function in CA-Cl*pper (both 87 and 5.x). This is an Append Mode which: "split the screen to allow data to be appended in windowed area". This mode is not supported by Harbour.
nInkeyCode is the inkey code, which should be inserted into the keyboard buffer.
Returns
There is no return value.
Description
Inserts an inkey code to the string buffer. The buffer is not cleared in this operation. This function allows to insert such inkey codes which are not in the range of 0 to 255. To insert more than one code, call the function repeatedly. The zero code cannot be inserted.
Examples
#include "inkey.ch"
// Stuff an <Alt+PgDn> key into the keyboard buffer
hb_keyPut( K_ALT_PGDN ); ? Inkey() // --> 417
hb_keyPut( K_F11 ); ? Inkey() // --> -40
Extracts the next key code from the Harbour keyboard buffer.
Syntax
Inkey( [<nTimeout>] [, <nEvents>] ) → nKey
Arguments
nTimeout is an optional timeout value in seconds, with a granularity of 1/10th of a second. If omitted, Inkey() returns immediately. If set to 0, Inkey() waits until an input event occurs. If set to any other value, Inkey() will return either when an input event occurs or when the timeout period has elapsed. If only this parameter is specified and it is not numeric, it will be treated as if it were 0. But if both parameters are specified and this parameter is not numeric, it will be treated as if it were not present.
nEvents is an optional mask of input events that are to be enabled. If omitted, defaults to hb_set.HB_SET_EVENTMASK. Valid input masks are in inkey.ch and are explained below. It is recommended that the mask names be used rather than their numeric values, in case the numeric values change in future releases of Harbour. To allow more than one type of input event, simply add the various mask names together.
inkey.ch Meaning
INKEY_MOVE Mouse motion events are allowed
INKEY_LDOWN The mouse left click down event is allowed
INKEY_LUP The mouse left click up event is allowed
INKEY_RDOWN The mouse right click down event is allowed
INKEY_RUP The mouse right click up event is allowed
INKEY_KEYBOARD All keyboard events are allowed
INKEY_ALL All mouse and keyboard events are allowed
HB_INKEY_EXTENDED Extended keyboard codes are used.
If the parameter is not numeric, it will be treated as if it were set to hb_set.HB_SET_EVENTMASK.
Returns
0 in case of timeout with no input event, otherwise returns a value in the range -47 to 386 for keyboard events or the range 1001 to 1007 for mouse events. Mouse events and non-printable keyboard events are represented by the K_<event> values listed in inkey.ch. Keyboard event return codes in the range 32 through 127 are equivalent to the printable ASCII character set. Keyboard event return codes in the range 128 through 255 are assumed to be printable, but results may vary based on hardware and nationality. If HB_INKEY_EXTENDED mode is used, then the return value for keyboard events ranges from 1 through 767 and 1077 through 1491, although not all codes are used.
Extended key codes consist of the PC keyboard scan code and one or more offset values. If no keyboard modifier was used, then HB_INKEY_NONE is added. The Alt key adds HB_INKEY_ALT, the Ctrl key adds HB_INKEY_CTRL, the Shift key adds HB_INKEY_SHIFT, and enhanced keys (KeyPad+/ and CursorPad keys) add HB_INKEY_ENHANCED. For example, F1 is scan code 59, so if you just press F1, you get key code 315, but Alt+F1 gives 443, Ctrl+F1 gives 57