Contents

LCC-Win32 C Library Functions

Except for the specialized libraries such as bignum, GC etc. library functions are collected as much as is possible into their natural groups - however the functions that do not easily fall into any category are collected in the system section.

All available functions are listed whether part of the ANSI C specification or otherwise.

Data types Describes the data types supported by lcc-win32.

bignum
 console
containers
GC (garbage collector)
gdbm
 Input Output
Intrinsics
linear algebra
math
memory
network
statistics
string
system
regular expressions
time/date
zlib

This functions are either imported from the C run time provided by windows (CRTDLL.DLL) or are statically linked in libc.lib, zlib.lib or others. The garbage collector is distributed in the form of a dll. Programs that use it have to include gc.dll in their distribution.


lcc

lcc-win32 native data types

Integer data types

Name | Size (bytes) | Standard?
signed char | 1 | yes
unsigned char | 1 | yes
short | 2 | yes
unsigned short | 2 | yes
int | 4 | yes
unsigned int | 4 | yes
long | 4 | yes. This type is identical to the int type.
unsigned long | 4
long long | 8 | yes
unsigned long long | 8 | yes
int128 | 16 | Not standard (yet). Include "int128.h" to use them, and link with int128.lib. There is no unsigned int128 type.

Floating point data types

Defined in "qfloat.h" and implemented in qfloat.lib

Name | Precision (digits) | Size (bytes) | Standard?
float | 6 | 4 | yes
double | 15 | 8 | yes
long double | 20 | 12 | yes
qfloat | 100 | 56 | No. Include "qfloat.h" and link with qfloat.lib

Indefinite precision numbers

They are defined in "bignums.h", and implemented in bignums.lib

Complex numbers

They are implemented in long double precision only. Include "complex.h" to use them.


128 Bit Integers

Lcc-win32 provides 128 bit integers. They can be used if you include the header file:

#include <int128.h>

The type name is int128.

They are used like any other integer type. The normal operators (+, - * and /) work with these integers as with normal integers.

There is no need to include any special library since the 128 bit routines are included in the standard C library that will be anyway looked up by the linker.


128 Bit Integers

384 bit floats

Lcc-win32 provides 384 bit floating point. They can be used if you include the header file:

#include <qfloat.h>

The type name is qfloat.

They are used like any other floating point type. The normal operators (+, - * and /) work with these numbers as with normal doubles or long doubles.

You should link with qfloat.lib to use this numbers.

All floating point library functions work with these numbers: sqrt, ldexp, etc, including the statistical library functions. The precision of these numbers is approximately 100 digits.


Math Funcs

LCC-Win32 Container Functions

Containers are data structures that organize the storage and retrieval of data stored within them.

The following data types are supported:

bitstring

stack

lists

vector

string

Lcc-win32 supports generic functions, i.e. functions that can receive a set of arguments. The generic functions supported by all containers are:

<T> new(<T>, args...);

<T> insert(<T>...);

<T> remove(<T>,...);

<T> get_element(<T>, int); // Not supported by stacks

<T> set_element(<T>, int,val); // Not supported by stacks


Using lists

Creating a list

To create a list you use the function newList(). If you want to create a list where all items have the same size (you will store data of the same type), you create the list using:

    List li = newList(sizeof(mytype));

Obviously you can pass an integer constant instead of using the sizeof primitive. In this case, the contents of each element will be stored and managed by the list. The functions that add items to the list copy the contents that are received.

If you want to create a list with elements of different sizes, you create the list using:

    List li = newList();

or

    List li = newList(0);

In this case the storage for each element is managed by you, and the list package stores just a pointer to the given data.

Lists can be read only (can't be modified). To set/unset a list as read-only you use the SetReadOnly() method.


Function

Function: Add

Synopsis
#include <containers.h>
int (*Add)(List *L1,void *data);

Description

This function adds an element at the end of the given list.

Returns

The number of elements in the list

Example:

List list;
MyStruct data;
int nb = list->lpVtbl->Add(&list,&data);

This simpler syntax is also accepted:

int nb = list->Add(&data);


abs

Function: Append

Synopsis
#include <list.h>
List (*Append)(list *L1,list *L2);

Description

This functions appends the second list to the first one. The input lists are left untouched, i.e. the last element of l1 will be replicated.

Returns

A pointer to a new list structure containing the new list.

Example:

List list,list1;
List *list3 = list->lpVtbl->Append(&list,&list1);

This simpler syntax is also accepted:

List list,list1;
List *list3 = list->Append(&list1);


abs

Function: Copy

Synopsis
#include <containers.h>
List (*Copy)(List *li);

Description

This function copies the list passed in argument. If the list is a list with data elements of different size, only the pointers to the data are copied, not the data itself. Otherwise, the new list contains a copy of the list and the data.

Returns

The newly created list.

Example:

List list,list1;
list1 = list->lpVtbl->Copy(&list);

This simpler syntax is also accepted:

List list,list1;
list1 = list->Copy();


Function

Function: GetCount

Synopsis
#include <containers.h>
int (*GetCount)(List *L1);

Description

This function returns the number of elements in the given list.

Returns

The number of elements in the list

Example:

List list;

int nb = list->lpVtbl->GetCount(&list);

This simpler syntax is also accepted:

int nb = list->GetCount(&data);


abs

Function: IndexAt

Synopsis
#include <list.h>
list_element *(IndexAt)(List *l,size_t position);
list_element *operator [](list *l,size_t position);

Description

This functions gets the element at the given position.

Returns

A pointer to the list_element contained in this element or NULL if the position was less than zero or greater than the size of the list minus one. A NULL list will also be considered a soft error and NULL will be returned.

Example:

List l;
list_element listE = l->lpVtbl->IndexAt(l,2);
list_element le = l[2];


Function

Function: IndexOf

Synopsis
#include <containers.h>
int (*IndexOf)(List *L1,void *data);

Description

This function will return the index of the element that contains the given data, or -1 if the element is not found. Note that for lists with different element sizes it is necessary to set the comparison function first, using SetCompareFunction.

Returns

The index or -1 if not found.

Example:

List list;

int nb = list->lpVtbl->IndexOf(&list,data);

This simpler syntax is also accepted:

int nb = list->IndexOf(data);

#include <stdio.h>
#include <string.h>
#include <containers.h>

int main(void)
{
    List data = newList(0);

    char * s;
    s = "first list";
    data.Add(s);
    s = "second list";
    data.Add(s);

    data.SetCompareFunction(strcmp);
    printf("Index of %s is %d\n",s,data.IndexOf(s));
}


abs

Function: Insert

Synopsis
#include <containers.h>
int (*Insert)(list *l, void *pdata);

Description

This function adds one element containing the given data pointer at the beginning of the list.

Returns

The number of elements in the list

Example:

List list;
MyType data
int nb = list->lpVtbl->Insert(&list,&data);

This simpler syntax is also accepted:

int nb = list->Insert(&data);


Function

Function: IsReadOnly

Synopsis
#include <containers.h>
int (*IsReadOnly)(List *L1);

Description

This function will return the value of the read-only flag.

Returns

The value of the read-only flag.

Example:

List list;

int nb = list->lpVtbl->IsReadOnly(&list);

This simpler syntax is also accepted:

int nb = list->IsReadOnly();


abs

Function: newList

Synopsis
#include <containers.h>
List *newList(size_t elementsize);

Description

This function builds a new list container, initially empty. The argument elementsize can be:

  • A positive number. This means that all the data in the list is the same size (the same type), and that the storage for the data is the responsability of the list container.
  • Zero or absent. This means that the elements in the list are of different size and that it is the user of the container that manages the storage for the data.

Returns

Returns a pointer to the newly created list, or NULL if there is no more memory left.


abs

Function: set_element_list

Synopsis
#include <list.h>
void *set_element_list(list *l,size_t position,void *pNewElement);
void *operator []=(list *l,size_t position,void *pNewElement);

Description

This functions set the element at the given position with the new data item. The data will be copied from the address given in newElement using the size of the list's elements. This data will be freed when the element is discarded or the whole list is discarded whichever comes first.

Returns

A pointer to the data contained in this element or NULL if the position was less than zero or greater than the size of the list minus one. A NULL list will also be considered a soft error and NULL will be returned.


abs

Function: Pop

Synopsis
#include <containers.h>
list_element (*Pop)(List *l);

Description

This functions removes one element at the start of the list. If the list is empty, nothing is done.

Returns

A pointer to the list element or NULL if the list was empty.


abs

Function: Push

Synopsis
#include <containers.h>
int (*Push)(list *l, void *pdata);

Description

This function adds one element containing the given data pointer at the beginning of the list.

Returns

The number of elements in the list

Example:

List list;
MyType data
int nb = list->lpVtbl->Push(&list,&data);

This simpler syntax is also accepted:

int nb = list->Push(&data);


abs

Function: Reverse

Synopsis
#include <containers.h>
List (*Reverse)(List *l);

Description

This function reverses the order of the given list.

Returns

The reversed input list.


Function

Function: SetReadOnly

Synopsis
#include <containers.h>
int (*SetReadOnly)(List *L1,int set_or_unset);

Description

This function will set the read-only flag in the given list to true if the "set_or_unset" argument is different from zero, to false otherwise.

Returns

The old value of the flag.

Example:

List list;

int nb = list->lpVtbl->SetReadOnly(&list,1);

This simpler syntax is also accepted:

int nb = list->SetReadOnly(1);


Lists are containers that support the storage and retrieval of data that is not contiguous in memory

Stacks are a sequence of data items where the only active item is the stack head, where an element can be either pushed or popped. The elemnts are retrieved in a LIFO manner: Last in, first out.

The interface supports the following functions:

Allocating/disposing of stacks

list *new_stack(void);
void dispose_stack(stack *s);

Copying stacks

list *copy_stack(stack *s);

Accessing the stack properties

size_t get_size_stack(stack *l);

Adding or deleting items

stack *push_stack(stack *s,void *pdata);
void *pop_stack(stack *s);


abs

Function: copy_stack

Synopsis
#include <stack.h>
list *copy_stack(stack *st);

Description

This function copies the stack passed in argument. Note that the contents of the stack are NOT copied, just the data containers will be copied.

Returns

A pointer to a newly created stack.


abs

Function: get_size_stack

Synopsis
#include <stack.h>
size_t get_size_stack(stack *st);

Description

This function returns the number of elements stored in the given stack

Returns

The length of the stack.


abs

Function: dispose_stack

Synopsis
#include <stack.h>
void dispose_stack(stack *st);

Description

This function destroys all the stack passed in argument. Note that only the stack is destroyed, not the data they contain, that is not managed by the stack.

Returns

No result.


abs

Function: new_stack

Synopsis
#include <stack.h>
list *new_stack(Malloc_Function_Type pmalloc=0,Free_Function_Type pfree=0);

Description

This function builds a new stack, initially empty. The arguments are:

  • The "pmalloc" function pointer should be the function that will be used to allocate memory when the list grows.
  • In a similar way, the "pfree" function pointer should be the function that the list will use for freeing the allocated memory. If this function pointers are NULL, they will default to malloc and free.

Returns

Returns a pointer to the newly created stack, or NULL if there is no more memory left.


abs

Function: pop_stack

Synopsis
#include <stack.h>
void *pop_stack(stack *s);

Description

This functions removes the top of the stack and returns a pointer to its data item. If the stack is empty, NULL is returned.

Returns

A pointer to the data contained in the removed element.


abs

Function: push_stack

Synopsis
#include <stack.h>
int push_stack(stack *s,void *pdata);

Description

This functions adds one element containing the given data pointer at the top of the stack.

Returns

The number of items in the stack.


Lists are containers that support the storage and retrieval of data that is not contiguous in memory

Lcc-win32 string library

Strings are a linear (one dimensional) sequence of characters. Like the other containers, strings accept the [ ] notation.

They come in two flavors: strings with single byte characters, and strings with multi-byte, i.e. two bytes for each character. All string functions come in two flavors: the ones for single and the ones for multi bytes. The share the same name, but end with 'A' for the single byte ones, or with 'W' for the wide character ones.

For instance the function Strcpy comes in two flavors: StrcpyA, that works with single-byte, and StrcpyW that accepts wide chars.

You can use both types of strings at the same time, but only one default. What the default is (wide or single) depends on the compile time switch 'UNICODE'

We have

#ifdef UNICODE
#define Strcpy StrcpyW
#else
#define Strcpy StrcpyA

You need to remember just one name. This rule is followed throughout the library, including the data types. We have StringA and StringW as primitive data types, and String will be wide if UNICODE is defined, single byte otherwise.

In this documentation the generic term "String" is used for both StringA and StringW. Implicit is that there are two versions, a 'A' and a 'W' versions.

Data structures

The String data type is a small structure that contains the length of the string, its capacity (allocated size), and a pointer to the characters. It comes in single-byte/multi byte flavors as StringA and StringW.

The Stringp data type represents a range of characters within a string. It contains a length, a pointer to the data, and a pointer to the original String containing the full contents. It comes with two flavors: StringpA and StringpW.

The interface supports the following functions:

Allocating

String *  overloaded new_string(size_t initial_size);
StringA * overloaded new_string(char *s);
StringW * overloaded new_string(wchar_t *s);

Copy

String *copy_string(String &);
String * overloaded copy(String &);
String *get_subrange_string(String &s, int start, int end);

Accessing string properties

size_t get_size_string(String &str);
size_t Strcapacity(String &str);
void *Strcontent(String &str);

Accessing the characters

int set_element_string(String
&s,size_t position,int newval);
int operator []=(String &s,size_t
position,int newval);
int operator []=(Stringp &s,size_t
position,int newval);
int get_element_string(String
&s,size_t position);
int operator [](String &s, size_t position);
int operator [](Stringp &s, size_t position);

Adding or deleting items

String & overloaded insert(String &s,size_t position,int pElement);
String &insert_string(String &s,size_t position,int Element);
String &erase_string(String &s,size_t position);

Applying a function to a whole string

String iterate_string(String &b,int (*fn)(char *data));
String Strmap(String & from, int (*map_fun) (int));

Utilities

bool concat_string(String *s1,String *s2);
bool nconcat_string(String *b1,bitstring *b2);
bool overloaded reverse(String &b);

Conversions

Strings can be used with printf and any other function that accepts a char * by using an explicit cast. For instance, to print the contents of a string in the standard output you would write:

String str;
...
printf("%s\n",(char *)Str);

The cast expression invokes the operator cast with the String before passing the result to the printf function.

bitstring overloaded ToString(int);
bitstring overloaded ToString(double);
bitstring overloaded ToString(char
*);
bitstring overloaded ToString(long
double);
String  operator()(const char* cstr);
String  operator()(const wchar_t *wstr);
char *operator()(String &str);
wchar_t *operator()(String &str);

String functions

This functions reflect the standard C library using Strings.

void overloaded Strcat(String & to, String &from);
void overloaded Strcat(String &to, wchar_t* from);
void overloaded Strcat(String &to, char* from);
String Strcatv(char *,...);

void Strchcat(String &s, int val);

void overloaded Strncat(String &to,char * from,size_t n);
void overloaded Strncat(String &to,wchar_t* from,size_t n);
void overloaded Strncat (String & to, String &from, size_t n);

int overloaded Strcmp(String & String, const char* str);
int overloaded Strcmp(const char* str, String & string);
int overloaded Strcmp(String& String, const wchar_t* str);
int overloaded Strcmp(const wchar_t* str, String& string);

int Strcmpi(String & s1, String & s2);
int Stricmp(String & s1, String & s2)
void overloaded Strcpy (String & target, String & source);
void overloaded Strcpy (String & target, char *source);
void overloaded Strcpy (String & target, wchar_t *source);
Stringp overloaded Strstr(String &text, String &word);

Stringp Strchr (String & string, int
element);
size_t  Strcspn (String & s1, const String &s2);
String  Strdup(String & to_be_cloned);
int     Strfgets (String & source, int n, FILE *from);
String  Strupr(String& from);
String  Strlwr(String
&from);
String  Strreverse(String &);
String  Strfromfile (char * file_name,int
binarymode);
String  Strfromfile  (String file_name,int
binarymode);
String  Strfrompipe(char *cmdline);
String  Strfrompipe(String cmdline);
String  Strfromenv(String varname);
bool    Strtofile(String s,char *filename,int
binarymode);
int     Strrepl(String &input,String
ToFind,String ToReplace);
int     Strrepl(String &input,
int charToFind,int charToReplace);
Stringp Strtok(String *string, const String &
delimiter);
size_t overloaded Strspn(const String &s1,const
String &s2);
size_t overloaded Strspn(const
String &s1, const char *s2);
int overloaded Strfind_first_of(String
&s,String &set);
int overloaded Strfind_first_of(String &s,char
*set);
int overloaded Strfind_last_of(String &s,String
&set);
int overloaded Strfind_last_of(String &s,char
*set);
int overloaded Strfind_last_not_of(String &s,String
&set);
int overloaded Strfind_last_not_ofA(String &s,char
*set);
int overloaded Strfind_last_not_ofW(String &s,wchar_t
*set);
Stringp Strchr(String s, int c);
void Strset(String &, int, size_t);

int operator == (const String& s1, const String& s2);
int operator == (const String & string1, int i);
int operator == (int i,const String & string1);

int operator < (const String & s1, const String & s2);
int operator <= (const String & s1, const String & s2);
int operator > (const String & s1, const String & s2);
int grString(String *s1,const String *s2);
int operator >= (const String & s1, const String & s2);
int geqString(String *s1,String *s2);

String Strerror(void);

String Strfilter(String,int (*predicate)(int));
String Strmap(String s,int (*fn)(int));

Iterators

A string pointer can be used as an iterator with the function next_string.

Stringp begin_string(String &s);
Stringp next_string(Stringp p);


abs

Functions: begin_string

Synopsis
#include <str.h>
Stringp begin_string(String &str);

Description

This function returns a Stringp (string pointer structure) that points to the start of the given string. If the string is invalid it will return an invalid_stringp.

This functions comes in multi-byte or single byte versions.

Returns

The string pointer structure or invalid_stringp if an invalid string is received.


abs

Functions: operator[ ] get_element_string

Synopsis
#include <str.h>
int get_element_string(String &str, size_t position);
int operator[](String &str, size_t position);

Description

This function returns the character stored at the given position in the given string.

Returns

The character stored at the given position.


abs

Functions: get_size_string Strcapacity

Synopsis
#include <str.h>
size_t get_size_string(String &str);
size_t *Strcapacity(String &str);

Description

This functions return the number of elements that can be stored in the given string. For wide character strings, the number of bytes will be 2*Strcapacity(str). For byte strings capacity and byte size will be the same.

Returns

The string capacity.


abs

Functions: insert_string

Synopsis
#include <str.h>
String &insert_string(String &str, size_t position,int newchar);
String &Strinsert(String &str, size_t position,int newchar);

Description

This functions insert the character before the given position in the given string.

Returns

A reference to the string given as argument.


abs

Functions: new_string (overloaded)

Synopsis
#include <str.h>
string *new_string(void);
string *new_string(int siz);
string *new_string(char *);
string *new_string(wchar_t);

Description

This functions create a new string from their arguments.

  • new_string(void) Creates a new string with the default size, and default type (byte sized chars).
  • new_string(int size) Creates a string with the given size.
  • new_string(char *template) Creates a new string using the given C string as template. The resulting string will be of type StringA, and have a length equal to strlen(template)
  • new_string(wchar_t *template) Creates a new string using the given wide character string as template. The resulting string will be of type StringW, and have a length equal to wcslen(template)

Returns

A pointer to the newly created string.


abs

Functions: next_string

Synopsis
#include <str.h>
Stringp next_string(Stringp &pstr);

Description

This function moves the given cursor to the next item in the string. The return value is either a valid cursor or invalid_stringp if the cursor has arrived at the end of the string.

This functions comes in multi-byte or single byte versions.

Returns

The string pointer structure given as argument or invalid_stringp if the pointer has arrived at the end of the string.


abs

Functions: get_element_vector operator[ ]

Synopsis
#include <vector.h>
void *get_element_vector(vector *v,size_t index);
void *operator[](vector *v,size_t index);

Description

Returns a pointer to the data stored at the given position.

Returns

A pointer to the indicated element.


abs

Functions: set_element_vector operator[ ]=

Synopsis
#include <vector.h>
void *set_element_vector(vector *v,size_t index, void *data);
void *operator[](vector *v,size_t index,void *data);

Description

Sets the data element at the given position to the contents of the given data. The data ill be copied to the vector.

Returns

A pointer to the indicated element.


abs

Functions: equal_vector operator==

Synopsis
#include <vector.h>
int equal_vector(vector *v1,vector *v2);
int operator==(vector v1,vector v2);

Description

Compares the two vectors for equality. The elements will be compared with memcmp.

Returns

The result is true if the vectors are equal, zero otherwise.


abs

Functions: erase erase_string

Synopsis
#include <str.h>
bool overloaded erase(String &str, size_t position);
bool erase_string(String &str, size_t position);

Description

This function removes the character at the given position in the given string.

Returns

True if the character was erased, false if the position was out of range or the input string was an invalid or empty string


abs

Functions: Strreverse reverse_string

Synopsis
#include <str.h>
String reverse_string(String &str);
String Strreverse(String &s);

Description

This function reverses the contents in the given string.

Returns

The string given as argument.


abs

Functions: Strcat

Synopsis
#include <str.h>

bool overloaded Strcat(String &to,
String & from);
bool overloaded Strcat(String &to, wchar_t* from);
bool overloaded Strcat(String &to, char*    from);

Description

This functions add to the first string the contents of a String, (first overloaded version), the contents of a C string (second overloaded version) or the contents of a C wide string (third overloaded version).

The first string must be a valid String.

Returns

True if the operation succeeded, false if there wasn't enough memory or the first string wasn't valid.


abs

Functions: Strcatv

Synopsis
#include <str.h>

StringA StrcatvA(char *s,...);
StringW StrcatvW(wchar_t *s,...);

Description

This function constructs a string from different C strings passed to it. The argument list *must* be finished with a NULL pointer.

All strings must be valid C strings.

Returns

The transformed string.

Example:

Strcatv("This", "is","a"," sentence",NULL);

Result

"This is a sentence"


abs

Functions: Strchcat

Synopsis
#include <str.h>

void  Strchcat(String &to, int val);

 Description

This function adds to the first string the character indicated by val. A resize operation could be necessary if the capacity of the string is exceeded.

The first string must be a valid String.

It exists in wide and multi byte versions, with the usual suffixed: StrchcatA and StrchcatW.

Returns

No return value


abs

Functions: Strchr

Synopsis
#include <str.h>
Stringp Strchr(const String& s1, int char_to_find);

Description

This function returns a pointer to the portion of the string s1 that begins with the first occurrence of "char_to_find". If the character is not found an invalid string pointer is returned. Comparisons operators check for this value, that is assumed to play the role of the Null pointer.

Both multi-byte and single byte versions exist.

Returns

A pointer structure to the portion of the string starting with the given character or an invalid string pointer if the character wasn't found.


abs

Functions: Strcmp

Synopsis
#include <str.h>

int overloaded Strcmp(String & string, const char*
str);
int overloaded Strcmp(const char* str, String & string);
int overloaded Strcmp (String& string, const wchar_t* str);
int overloaded Strcmp(Stringp &, Stringp&);
int overloaded Strcmp(StringpA &,char *);
int overloaded Strcmp(StringpW &,wchar_t *);

Description

The Functions from this family compare one String with another.
For the result of Strcmp it always holds:

  • -1 means s1 < s2
  • 0 means s1 == s2
  • 1 means s1 > s2

Returns

An integer with the result of the comparison.


abs

Functions: Strcmpi Stricmp

Synopsis
#include <str.h>

int Strcmpi (String & s1, String & s2);
int Stricmp (String & s1, String & s2)
Description

Compares the two strings ignoring case differences. With this difference, this function is identical to Strcmp. They exist in multi byte and wide character versions.

Returns

An integer with the result of the comparison.


abs

Functions: Strencrypt Strdecrypt

Synopsis
#include <str.h>

int Strencrypt(String & src);
int Strdecrypt(String &src);

Description

Strencrypt encrypts in place the given clear text string. The previous contents are destroyed.

Strdecrypt decrypts a previously encrypted string. The previous contents are destroyed.

The method used is PKCS_7_ASN_ENCODING | X509_ASN_ENCODING.

Returns

If successful, they return 1, zero otherwise.


abs

Functions: Strfgets

Synopsis
#include <str.h>
int Strfgets(const String& s1,int n,FILE *from);

Description

This function reads at most n characters from the given FILE. The function will stop if it finds a new line character. The new line character will not be included in the resulting string. The sequence of a \r and a \n will be recognized as an end of line terminator and will be ignored.

Returns

The number of characters read from the file. This will be zero at EOF.

Example:

#include <str.h>
#include <stdio.h>
int main(void)
{
    String s = new_string(0,SMALL);
    FILE *f;

    f = fopen("strfgets.c","rb");
    while (Strfgets(s,120,f)) {
        printf("%s\n",(char *)s);
    }
    fclose(f);
    return 0;
}

This produces the output:

#include <str.h>
#include <stdio.h>
int main(void)
{
    String s = new_string(0,SMALL);
    FILE *f;

    f = fopen("strfgets.c","rb");
    while (Strfgets(s,120,f)) {
        printf("%s\n",(char *)s);
    }
    fclose(f);
    return 0;
}


strncat

Function: Strfind_first_of

Synopsis
#include <str.h>
int overloaded Strfind_first_of(String &InputString, String &charsToFind);
int overloaded Strfind_first_ofA(String &InputString, char *charsToFind);
int overloaded Strfind_first_ofW(String &InputString, wchar_t *charsToFind);

Description

The Strfind_first_of functions return the position within the input string where the first character belonging to the "charsToFind" argument is found. If no match is found the result is -1. This function comes in single byte and double byte versions.

Returns

The index of the first match or -1 if no match is found.

See also

The Strcspn is identical, differing only in the return value when not found. Strcspn returns Strlen(InputString) when not found, and not -1.


strncat

Function: Strfind_last_of

Synopsis
#include <str.h>
int overloaded Strfind_last_of(String &InputString, String &charsToFind);
int overloaded Strfind_last_ofA(String &InputString, char *charsToFind);
int overloaded Strfind_last_ofW(String &InputString, wchar_t *charsToFind);

Description

The Strfind_last_of function returns the position within the input string where the last character belonging to the "charsToFind" argument is found. If no match is found the result is -1.

Returns

The index of the last match or -1 if no match is found.


strncat

Function: Strfind_last_not_of

Synopsis
#include <str.h>
int overloaded Strfind_last_not_of(String &InputString, String &charsToFind);
int overloaded Strfind_last_not_ofA(String &InputString, char *charsToFind);
int overloaded Strfind_last_not_ofW(String &InputString, wchar_t *charsToFind);

Description

The Strfind_last_not_of functions return the position within the input string where the last character not belonging to the "charsToFind" argument is found. If no match is found the result is -1.

Returns

The index of the last character that doesn't match or -1 if all characters match.


abs

Functions: Strfilter

Synopsis
#include <str.h>
String Strfilter(String &str, int (*predicate)(int));
StringA Strfilter(String &str, char *set);
StringW Strfilter(String &str,wchar_t *set);
String Strfilter(String &str, String &set);

Description

The first version of the Strfilter function builds a new string with the characters for which the predicate function returns true.

The second and third versions use the given set. If a character in the string is in the set, it will be added to the result.

Returns

A new string with all characters for which the predicate function returns true or is in the given set.

Example:

#include <str.h>
#include <stdio.h>
int isnumeric(int c)
{
    return c >= '0' && c <= '9';
}

int main(void)
{
    String s = "The subject age is 45 years\n";

    String s2 = Strfilter(s,isnumeric);
    printf("%s\n",(char *)s2);
    return 0;
}

This will output

45


abs

Functions: Strfromfile

Synopsis
#include <str.h>

String overloaded Strfromfile (char *filename,int binarymode);
String overloaded Strfromfile (String filename,int binarymode);

Description

Reads the contents of the given file into a String. If binarymode is TRUE, it will read the file including the \r\n line terminator. Else it will ignore the \r and lines will end in \n only.

Returns

A string with the contents of the given file.


strncat

Function: Strfrompipe

Synopsis
#include <str.h>
int overloaded Strfrompipe(String & cmdline);
int overloaded Strfrompipe(char * cmdline);

Description

The Strfrompipe function starts the process indicated by the cmdline parameter, and stores all the output that goes into stdout and stderr into a String.

Note that the first parameter of the command line should be a full path specification of the program to start, including the root drive. Do not rely on the path. For instance you should not write:

    Strfrompipe("cmd /k dir");

but

    Strfrompipe("c:\\windows\\system32\\cmd.exe /K dir");

Returns

It returns the string with the contents of the program's output or an invalid string if the command couldn't be started.


abs

Functions: Strerror

Synopsis
#include <str.h>
String Strerror(void);

Description

Returns a string with a description of the value stored in errno.

Returns

The error message string.


abs

Functions: Strmap

Synopsis
#include <str.h>
String Strmap (String & from, int (*map_fun) (int));

Description

This function applies the given function to each character in the string. The result is stored in the corresponding position of the result string.

Returns

The new string with the results of the mapping function.

Example:

#include <stdio.h>
#include <str.h>

int toUpper(int c)
{
    if (c >= 'a' && c <= 'z')
        c -= ' ';
    return c;
}

int main(void)
{
    String s = "This is A sTriNg witH manY UppErCasE ChArAcTers";

    String sUpper = Strmap(s,toUpper);
    printf("Source string: %s\nResult string: %s\n",(char *)s,(char *)sUpper);
    return 0;
}

This produces the output:

Source string: This is A sTriNg witH manY UppErCasE ChArAcTers
Result string: THIS IS A STRING WITH MANY UPPERCASE CHARACTERS


abs

Functions: Strncat

Synopsis
#include <str.h>

void overloaded Strncat(String &to, String &
from,size_t n);
void overloaded Strncat(String &to, wchar_t* from,size_t n);
void overloaded Strncat(String &to, String & from,	size_t n);

Description

This functions add to the first string the contents of a String, (first overloaded version), the contents of a C string (second overloaded version) or the contents of a C wide string (third overloaded version). At most n characters will be copied. The number of characters can be smaller if the end of the string (the terminating zero) is found first.

The first string must be a valid String.

Returns

The transformed string.


abs

Functions: Strdup

Synopsis
#include <str.h>
String Strdup(const String& s1);

Description

This function returns a copy of the given string.

Returns

The string copy.


abs

Functions: Strresize

Synopsis
#include <str.h>

int Strresize (String & target, size_t new_size);

Description

Changes the capacity of the given string to accomodate new_size characters. If the new capacity is smaller than the current length of the string, the string will be truncated, but the capacity remains the same.

Returns

Returns 1 if the operation suceeded, zero otherwise


abs

Functions: Strupr

Synopsis
#include <str.h>
String Strupr(const String& s1);

Description

This function returns a copy of the original string with all lower case character transformed in upper case ones.

Returns

The a transformed copy of the original string.


abs

Functions: Strlwr

Synopsis
#include <str.h>
String Strlwr(const String& s1);

Description

This function returns a copy of the original string with all upper case character transformed in lower case ones. Only the single-byte flavor is implemented.

Returns

The a transformed copy of the original string.


strrchr

Function: Strstr

Synopsis
#include <str.h>
Stringp overloaded Strstr(String &text, String &word);
StringpA overloaded StrstrA(StringA &text, char *word);
StringpW overloaded StrstrW(StringW &text, wchar_t *word);

Description

The Strstr function locates the first occurrence of the pattern "word" in the string s.

Returns

The strrchr function returns a String pointer structure pointing to the first character in the found pattern, or an invalid_stringp if the pattern does not occur in the string.


strncat

Function: Strrepl

Synopsis
#include <str.h>
int overloaded Strrepl(String &Input, String &StringToFind, String *Replacement);
int overloaded Strrepl(String &Input, char *StringToFind, char *Replacement);
int overloaded Strrepl(String &Input, int charToFind,int charToReplace);

Description

The Strrepl function replaces in Input all occurrences of StringToFind by Replacement, writing the modified contents into the Input string. The original input string is modified in place. This may provoke a resize operation if the capacity of the input string is smaller than the needed length.

If Replacement is the invalid string or NULL, all occurrences of StringToFind will be erased if any are found.

There is a wide character set and a single byte character set version.

The second form will replace all occurrences of the character 'charToFind' by "charToReplace' in place.

Returns

It returns the number of replacements done.

Example

#include <string.h>

#include <stdio.h>

int main(void)
{
    String p = "This is a string with WORD in it, and then another WORD in it ";
    String a = new_string(512);

    Strcpy(a,p);
    printf("%s\n",(char *)a);
    printf("needed length is %d\n",Strrepl(p,"WORD","ANOTHER WORD",NULL));
    Strrepl(p,"WORD","ANOTHER WORD",a);
    printf("%s\n",(char *)a);
    Strrepl(a,"ANOTHER WORD ",NULL,a);
    printf("(%d), %s\n",Strlen(a),(char *)a);

    return 0;
}

This will print:

This is a string with WORD in it, and then another WORD in it
needed length is 79
(79), This is a string with ANOTHER WORD in it, and then another ANOTHER WORD in it
(52), This is a string with in it, and then another in it


abs

Functions: Strtofile

Synopsis
#include <str.h>

bool Strtofile(String &s,char *filename,int binarymode);

Description

Writes the contents of the given string into a file. If binarymode is TRUE, it will write the file including the \r\n line terminator. Else it will ignore the \r and lines will end in \n only.

Returns

True if the operation was successful, false otherwise. The reasons for failure can be invalid arguments (invalid string, NULL file name), or errors in the file operations.


abs

Functions: Strtok

Synopsis

#include <str.h>
Stringp overloaded Strtok(String *string, const String & delimiter);
StringpA overloaded StrtokA(String *string, const char *delimiter);
StringpW overloaded
    StrtokW(String *string, const wchar_t *delimiter);

Description

The Strtok function gets the next token from string string, where tokens are strings separated by characters from delimiter. To get the first token from string, Strtok is called with string as its first parameter. Remaining tokens from string are obtained by calling Strtok with a null pointer for the first parameter. The string of delimiters, can differ from call to call.

The function Strtok writes null characters into the buffer pointed to by string.

It exists both in wide char strings and single byte strings.

Returns

A stringp describing the subset of the string that matched, or invalid_stringp if nothing was found.

Example

#include <str.h>
#include <stdio.h>

int main(void)
{
    String input = "abc,d";
    Stringp p;

    /* strtok places a NULL terminator
    at the end of the token, if found */
    p = Strtok(&input, ",");
    if (p) printf("%s\n", (char *)p);

    /* A second call to strtok using a NULL
    as the first parameter returns a pointer
    to the character following the token */
    p = Strtok(NULL, ",");
    if (p) printf("%s\n", (char *)p);
    return 0;
}

This produces the output:

abc
d


strrchr

Function: Strset

Synopsis
#include <str.h>
void Strset(String s, int c);

Description

The Strset function initializes all characters in the string to the given one.

Returns

No return value


strspn

Function: Strspn

Synopsis
#include <str.h>
size_t overloaded Strspn(const String &s1, const string &s2);
size_t overloaded Strspn(const String &s1, const char *s2);

Description

The Strspn function computes the length of the maximum initial segment of the string pointed to by s1 which consists entirely of characters from the string pointed to by s2.

Returns

The Strspn function returns the length of the segment.

Example:

#include<str.h>
#include<stdio.h>

int main(void)
{
  String string ="7803 Main St.";

  printf("The number length is %d.\n",Strspn(string,"1234567890"));

  return 0;
}

Output:

The number length is 4.


strrchr

Function: Strchr

Synopsis
#include <str.h>
Stringp Strchr(String s, int c);

Description

The Strrchr function locates the first occurrence of c (converted to a char) in the string s.

Returns

The strrchr function returns a String pointer structure pointing to the character, or an invalid_stringp if c does not occur in the string.


String Funcs

LCC-Win32 String Collection Functions

String collections are conceptually resizable arrays of strings. They will automatically increase their size when you add strings to them, and they can be used as push-down stacks.

The general syntax for the use of string collections looks like this:

#include <stdio.h>
#include <strcollection.h>
static void PrintStringCollection(StringCollection *SC)
{
    printf("Count %d, Capacity %d\n",SC->count,SC->capacity);
    for (int i=0; i<SC->count;i++) {
        printf("%s\n",SC->contents[i]);
    }
    printf("\n");
}

int main(void)
{
    StringCollection *SC = newStringCollection();
    char *p;

    // Add some items to the collection
    SC->Add("Martin");
    SC->Insert("Jakob");
    printf("Count should be 2, is %d\n",SC->GetCount());
    PrintStringCollection(SC);

    //Insert items at a given position
    SC->InsertAt(1,"Position 1");
    SC->InsertAt(2,"Position 2");
    PrintStringCollection(SC);

    // Remove some items
    SC->Remove("Jakob");
    PrintStringCollection(SC);

    // Use the collection as a pushdown stack
    SC->Push("pushed");
    PrintStringCollection(SC);
    SC->Pop();
    PrintStringCollection(SC);

    // Operator overloading allows to address it as an array
    p = SC[1];
    printf("Item position 1:%s\n",p);
    PrintStringCollection(SC);
}

As you can see, this syntax is slightly different than the normal function call syntax. Instead of writing:

    Add(SC,"Martin");

we write

    SC->Add("Martin");

or, using standard C:

    SC->lpVtbl->Add(SC,"Martin");

The advantage of using this syntax is that there could be a lot of functions called "Add" floating around, so we could not use this easy to remember name. We would have to write something like:

    StringCollectionAdd(SC,"Martin");

This is much more difficult to remember, specially if you take into account case. Was it stringCollectionadd or strCollectionADD? Or even str_collection_add ???

String collection functions:


atof

Function: Add

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->Add(const char
    *nptr);
int SC->lpVtbl->Add(StringCollection &SC,char *nptr);

Description

The Add function will insert the given character string into the collection.

Returns

The number of items in the collection. A return value of zero means there is no more memory, a return value of -1 means the given string collection is read only and cannot be modified.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    // use the short-hand syntax
    SC->Add("Martin");
    //Use standard C syntax
    SC->lpVtbl->Add(SC,"Martin");
}


atof

Function: AddRange

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->AddRange(const char
    **nptr);
int SC->lpVtbl->AddRange(StringCollection &SC,char **nptr);

Description

The AddRange function will insert the given character string table into the collection. The string table should be terminated by a NULL pointer.

Returns

The number of items in the collection. A return value of zero means there is no more memory, a return value of -1 means the given string collection is read only and cannot be modified.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    char *tab[] = "Martin","Serge","Annie",NULL};
    // use the short-hand syntax
    SC->AddRange(tab);
    //Use standard C syntax
    SC->lpVtbl->AddRange(SC,tab);
}


atof

Function: Apply

Synopsis
#include <strcollection.h>
StringCollection *SC;
void SC->Apply(int (*Applyfn)(char *,void *),void *arg);
void SC->lpVtbl->Apply(StringCollection &SC,int (*Applyfn)(char *,void *),void *arg);

Description

The Apply function will call the given function passing it as arguments each string in the collection, and a user defined argument passed to Apply as an argument.

Returns

No return value

Example
#include <strcollection.h>
void myfn(char *str,void *arg)
{
    printf("%s\n",str);
}
int main(void)
{
    StringCollection *SC = newStringCollection(5);
char *tab[] =
    "Martin","Serge","Annie",NULL};
// This will print all strings in the collection
// use the short-hand syntax
    SC->Apply(myfn,NULL);
    //Use standard C syntax
    SC->lpVtbl->Apply(SC,myfn,NULL);
}


atof

Function: Clear

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->Clear(void);
int SC->lpVtbl->Apply(StringCollection &SC);

Description

The Clear function will erase all items in the collection. If the library was compiled without using the garbage collector, each item will be freed before releasing it.

Returns

The number of items erased, i.e. the old count.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);

    // use the short-hand syntax
    SC->Clear();
    //Use standard C syntax
    SC->lpVtbl->Clear(SC);
}


atof

Function: Contains

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->Contains(char
    *StrToSearch);
int SC->lpVtbl->Contains(StringCollection &SC,char *StrToSearch);

Description

The Contains function will search (case sensitive) for the given string.

Returns

Returns 1 if the string is in the collection, zero otherwise. The given string should not be NULL. The comparison is case-sensitive.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    char *tab[] = "Martin","Serge","Annie",NULL};
    SC->AddRange(tab);
    // use the short-hand syntax
    if (SC->Contains("Serge") != 0)
        printf("OK. Serge is in the collection\n";
}


atof

Function: Copy

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->Copy(StringCollection
    &src);
int SC->lpVtbl->Copy(StringCollection &SC);

Description

Copies the contents and all characteristics of a string collection into a freshly allocated one.

Returns

The result is a new string collection or NULL if there is no more memory to finish this operation.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5),*copy;
    int i = SC->Push("Item1");
    // use the short-hand syntax
copy = SC->Copy(SC);
    // use the longer but standard syntax
    copy = SC->lpVtbl->Copy(SC);
}


atof

Function: CopyTo

Synopsis
#include <strcollection.h>
StringCollection *SC;
char **SC->CopyTo();
char **SC->lpVtbl->CopyTo(StringCollection &SC);

Description

The CopyTo function copies the contents of the collection into a NULL terminated string pointer array. The array and the contained strings are freshly allocated data, the collection retains all the data stored in it.

Returns

Returns the string pointer array, that should be freed by the user if the library was compiled without using the garbage collector. If a memory error occurs it returns NULL.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    char *tab[] = "Martin","Serge","Annie",NULL};
    char **p;
    p = SC->CopyTo();
    // use the longer but standard syntax
    p = SC->lpVtbl->CopyTo(SC);
}


atof

Function: Finalize

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->Finalize();
int SC->lpVtbl->Finalize(StringCollection &SC);

Description

The Finalize function releases the memory used by the collection. It is only necessary if the library was compiled without the garbage collector.

Returns

Returns the number of elements that were in the collection.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    SC->Finalize();
    // use the longer but standard syntax
    SC->lpVtbl->Finalize(SC);
}


atof

Function: GetCapacity

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->GetCapacity();
int SC->lpVtbl->GetCapacity(StringCollection &SC);

Description

The GetCapacity function returns the number of items that can be stored in a collection without resizing it.

Returns

Returns the number of elements that can be stored in the collection without resizing.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    int
    capacity = SC->Capacity();
// use the longer but standard syntax
capacity = SC->lpVtbl->Capacity(SC);
}


atof

Function: GetCount

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->GetCount();
int SC->lpVtbl->GetCount(StringCollection &SC);

Description

The GetCount function returns the number of items that can are stored in the collection.

Returns

Returns the number of elements that are stored.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    int
    count = SC->Count();
// use the longer but standard syntax
count = SC->lpVtbl->Count(SC);
}


atof

Function: IndexAt

Synopsis
#include <strcollection.h>
StringCollection *SC;
char *SC->IndexAt(int
    idx);
char *SC->lpVtbl->IndexAt(StringCollection &SC,int idx);
char *operator[](StringCollection &SC,int idx);

Description

The IndexAt returns the character at the given position.

Returns

Indexes the collection and returns the string at the given position. If the index is out of range, the function returns NULL. This can be confusing if you use NULLs within the collection.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    char *tab[] = "Martin","Serge","Annie",NULL};
    // use the short-hand syntax
    SC->AddRange(tab);
    char
    *p = SC->IndexAt(2); // p should be "Annie"
// use the longer but standard syntax
p = SC->lpVtbl->IndexAt(SC,2); // p should be
    "Annie"
p = SC[2]; // p should be "Annie"
}


atof

Function: IndexOf

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->IndexOf(char
    *);
int SC->lpVtbl->IndexOf(StringCollection &SC,char *str);

Description

The IndexOf function returns the index of the given string or -1 if not found. Comparisons are case sensitive. If the given string is NULL, it will be never found.

Returns

The index of the string or -1 if not found.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    char *tab[] = "Martin","Serge","Annie",NULL};
    // use the short-hand syntax
    int i = SC->IndexOf("Serge"); // i should be 1
    // use the longer but standard syntax
    i = SC->lpVtbl->IndexOf(SC,"Serge"); // i should be 1
}


atof

Function: Insert

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->Insert(char *str);
int SC->lpVtbl->Insert(StringCollection &SC,char *str);

Description

The Insert function inserts the given string at the position zero.

Returns

The number of items in the collection

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);

    // use the short-hand syntax
    int i = SC->Insert("Serge"); // i should be 1
    // use the longer but standard syntax
    i = SC->lpVtbl->Insert(SC,"Serge"); // i should be 1
}


atof

Function: InsertAt

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->InsertAt(char
    *str,int idx);
int SC->lpVtbl->InsertAt(StringCollection &SC,char *str,int idx);

Description

The InsertAt function inserts the given string at the given position.

Returns

The number of items in the collection if the insertion succeeds. The result is zero if there is no more memory or the index is outside the bounds of the collection.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);

    // use the short-hand syntax
    int i = SC->InsertAt("Serge",0); // i should be 1
    // use the longer but standard syntax
    i = SC->lpVtbl->Insert(SC,"Serge",0); // i should be 2 now
}


atof

Function: IsCaseSensitive

Synopsis
#include <strcollection.h>
StringCollection *SC;
char *SC->IsCaseSensitive(int
    newval);
char *SC->lpVtbl->IsCaseSensitive(StringCollection &SC,int newval);

Description

Returns the value of the case sensitive flag. This flag controls whether comparisons will be made respecting case (the default) or ignoring it.

Returns

The value of the flag.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    int i = SC->Add("Item1");
    // use the short-hand syntax
i = SC->IsCaseSensitive();
    // use the longer but standard syntax
    i = SC->lpVtbl->IsCaseSensitive(SC);
}


atof

Function: IsReadOnly

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->IsReadOnly(void);
int SC->lpVtbl->IsReadOnly(StringCollection &SC);

Description

Returns the value of the read-only flag.

Returns

If the collection has the flag set it returns 1, zero otherwise.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);

    // use the short-hand syntax
    int i = SC->IsReadOnly(); // i should be 0
    SC->SetReadOnly(1);
    // use the longer but standard syntax
    i = SC->lpVtbl->IsReadOnly(SC); // i should be 1 now
}


atof

Function: Map

Synopsis
#include <strcollection.h>
StringCollection *SC;
int *SC->Map(int (*Applyfn)(char *));
int *SC->lpVtbl->Map(StringCollection &SC,int (*Applyfn)(char *));

Description

Allocates an integer vector of the same length as the number of items in the collection. Then calls the given function, storing its result in the integer array.

Returns

The integer array.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);

    // use the short-hand syntax
    int *i = SC->Map(strcmp);
    // use the longer but standard syntax
    i = SC->lpVtbl->Map(SC,strcmp);
}


atof

Function: Pop

Synopsis
#include <strcollection.h>
StringCollection *SC;
char *SC->Pop(void);
char *SC->lpVtbl->Pop(StringCollection &SC);

Description

Returns the string with the highest index in the collection. This is equivalent to SC[SC->GetCount()] . If the collection is empty it returns NULL.

Returns

The string at the given position. If the library was compiled without the garbage collector, the user should free this string.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
SC->Push("Item 1");
    // use the short-hand syntax
    char *p = SC->Pop();
    // use the longer but standard syntax
    p = SC->lpVtbl->Pop(SC);
}


atof

Function: Push

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->Push(char *str);
int SC->lpVtbl->Push(StringCollection &SC);

Description

Inserts a string at the end of the collection (highest index).

Returns

The result is the number of items in the collection if successful, or zero if the collection is read-only or there isn't enough memory to complete the operation.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    // use the short-hand syntax
    int i = SC->Push("Item1");
    // use the longer but standard syntax
    i = SC->lpVtbl->Push(SC,"Item 2"); // i should be 2 now
}


atof

Function: Remove

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->Remove(char *str);
int SC->lpVtbl->Remove(StringCollection &SC,char *str);

Description

Removes the given string if found.

Returns

The result is the number of items in the collection if successful, or -1 if the collection is read-only or the string is not found.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    int i = SC->Push("Item1");
    // use the short-hand syntax
i = SC->Remove("Item1"); // i should be zero
    // use the longer but standard syntax
    i = SC->lpVtbl->Remove(SC,"Item1"); // i should be -1 now
}


atof

Function: RemoveAt

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->RemoveAt(int
    idx);
int SC->lpVtbl->RemoveAt(StringCollection &SC,int idx);

Description

Removes the string at the given position.

Returns

The result is the number of items in the collection if successful, or -1 if the index is out of range, -2 if the collection is read-only.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    int i = SC->Push("Item1");
    // use the short-hand syntax
i = SC->RemoveAt(0); // i should be zero
    // use the longer but standard syntax
    i = SC->lpVtbl->RemoveAt(SC,0); // i should be -1 now
}


atof

Function: ReplaceAt

Synopsis
#include <strcollection.h>
StringCollection *SC;
char *SC->ReplaceAt(int
    idx,char *newstr);
char *SC->lpVtbl->ReplaceAt(StringCollection &SC,int idx,char *newstr);
char * operator[]=(StringCollection *SC,int idx,char *newval)

Description

Replaces the string at the given position.

Returns

The result is the new string. This is useful for making chained assignments.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    int i = SC->Add("Item1");
    // use the short-hand syntax
SC->ReplaceAt(0,"New item 1");
    // use the longer but standard syntax
    SC->lpVtbl->ReplaceAt(SC,"Newest item 1");
}


atof

Function: SetCaseSensitive

Synopsis
#include <strcollection.h>
StringCollection *SC;
char *SC->CaseSensitive(int
    newval);
char *SC->lpVtbl->SetCaseSensitive(StringCollection &SC,int newval);

Description

Set or unsets the case sensitive flag. This flag controls whether comparisons will be made respecting case (the default) or ignoring it.

Returns

The old value of the flag.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    int i = SC->Add("Item1");
    // use the short-hand syntax
SC->CaseSensitive(1);
    // use the longer but standard syntax
    SC->lpVtbl->SetCaseSensitive(SC,0);
}


atof

Function: SetReadOnly

Synopsis
#include <strcollection.h>
StringCollection *SC;
int SC->SetReadOnly(int
    newval);
int SC->lpVtbl->SetReadOnly(StringCollection &SC,int newval);

Description

Set or unsets the read-only flag.

Returns

The old value of the flag.

Example
#include <strcollection.h>
int main(void)
{
    StringCollection *SC = newStringCollection(5);
    int i = SC->Add("Item1");
    // use the short-hand syntax
SC->ReadOnly(1);
    // use the longer but standard syntax
    SC->lpVtbl->SetReadOnly(SC,0);
}


atof

Function: Add

Synopsis
#include <containers.h>
ArrayList AL;
int AL.Add(const void *nptr);
int AL.lpVtbl->Add(AL,void *nptr);

Description

The Add function will insert the given element into the flexible array

Returns

The number of items in the array. A return value of zero means there is no more memory, a return value of -1 means the given array is read only and cannot be modified.

Exceptions

CONTAINER_ERROR_NOMEMORY. No more memory is available.
CONTAINER_ERROR_BADARG nptr is NULL.

Example
#include <containers.h>
int main(void)
{
    DATA data; // data is a user defined datatype
    ArrayList AL = newArrayList(sizeof(DATA),5);
    // use the short-hand syntax
    AL.Add(data);
    //Use standard C syntax
    AL.lpVtbl->Add(AL,data);
}


atof

Function: AddRange

Synopsis
#include <containers.h>
ArrayList AL;
int AL.AddRange(const void **nptr);
int AL.lpVtbl->AddRange(ArrayList &AL,void **nptr);

Description

The AddRange function will insert the given elements into the array. The table should be terminated by a NULL pointer.

Returns

The number of items in the array. A return value of zero means there is no more memory, a return value of -1 means the given array is read only and cannot be modified.

Exceptions

CONTAINER_ERROR_NOMEMORY. No more memory is available.
CONTAINER_ERROR_BADARG nptr is NULL.

Example
#include <containers.h>
int main(void)
{
    DATA d1,d2,d3; // DATA is a user defined type
    ArrayList AL = newArrayList(sizeof(DATA),5);
void *tab[4];
tab[0]=&d1;
    tab[1]=&d2;    tab[2]=&d3;
    tab[3]=NULL;
// use the short-hand syntax
    AL.AddRange(tab);
    //Use standard C syntax
    AL.lpVtbl->AddRange(AL,tab);
}


atof

Function: Clear

Synopsis
#include <containers.h>
ArrayList AL;
int AL.Clear(void);
int AL.lpVtbl->Clear(ArrayList &AL);

Description

The Clear function will erase all items in the array. If the library was compiled without using the garbage collector, each item will be freed before releasing it.

Returns

The number of items erased, i.e. the old count.

Example
#include <containers.h>
int main(void)
{
    DATA data; // DATA is a user defined type
    ArrayList AL = newArrayList(sizeof(DATA),5);

    // use the short-hand syntax
    AL.Clear();
    //Use standard C syntax
    AL.lpVtbl->Clear(AL);
}


atof

Function: Contains

Synopsis
#include <containers.h>
ArrayList AL;
int AL.Contains(void *ElementToSearch);
int AL.lpVtbl->Contains(ArrayList &AL,void *ElementToSearch);

Description

The Contains function will search for the given element using memcmp. The comparison only compares the size of the data structure stored in the array. Pointers are not followed.

Returns

Returns 1 if the element is in the collection, zero otherwise. The given pointer should not be NULL.

Exceptions

CONTAINER_ERROR_BADARG ElementToSearch is NULL.

Example
#include <containers.h>
int main(void)
{
    DATA data; // DATA is some user defined type
    ArrayList AL = newArrayList(sizeof(DATA),5);
    void *tab[2];
    // Code for the filling of the DATA structure omitted
    tab[0] = &data;    tab[1] = NULL;
    AL.AddRange(tab);
    // use the short-hand syntax
    if (AL.Contains(data) != 0)
        printf("OK\n";
}


atof

Function: CopyTo

Synopsis
#include <containers.h>
ArrayList AL;
void **AL.CopyTo();
void **AL.lpVtbl->CopyTo(ArrayList &AL);

Description

The CopyTo function copies the contents of the collection into a NULL terminated element pointer array. The array and the contained elements are freshly allocated data, the collection retains all the data stored in it.

Returns

Returns the element pointer array, that should be freed by the user if the library was compiled without using the garbage collector. If a memory error occurs it returns NULL.

Exceptions

CONTAINER_ERROR_NOMEMORY. No more memory is available.
CONTAINER_ERROR_BADARG nptr is NULL.

Example
#include <containers.h>
int main(void)
{
    DATA data; // DATA is a user defined type
    ArrayList AL = newArrayList(sizeof(DATA),5);
    void **tab;
    void **p;
    //
    Code for the filling of the structure(s) omitted
tab[0] = &data;    tab[1] = NULL;
AL.AddRange(tab);
p = AL->CopyTo();
// use the longer but standard syntax
p = AL.lpVtbl->CopyTo(AL);
}


atof

Function: Finalize

Synopsis
#include <containers.h>
ArrayList AL;
int AL.Finalize();
int AL.lpVtbl->Finalize(ArrayList &AL);

Description

The Finalize function releases the memory used by the array and the array structure itself. It is only necessary if the library was compiled without the garbage collector.

Returns

Returns the number of elements that were in the array.

Example
#include <containers.h>
int main(void)
{
    ArrayList AL = newArrayList(5);
    AL.Finalize();
    // use the longer but standard syntax
    AL.lpVtbl->Finalize(AL);
}


atof

Function: GetCapacity

Synopsis
#include <containers.h>
ArrayList AL;
int AL.GetCapacity();
int AL.lpVtbl->GetCapacity(ArrayList &AL);

Description

The GetCapacity function returns the number of items that can be stored in the array without resizing it.

Returns

Returns the number of elements that can be stored in the array without resizing.

Example
#include <containers.h>
int main(void)
{
DATA data;// DATA is a user defined type
    ArrayList AL = newArrayList(sizeof(DATA),5);
    int
    capacity = AL.Capacity();
// use the longer but standard syntax
capacity = AL.lpVtbl->Capacity(SC);
}


atof

Function: GetCount

Synopsis
#include <containers.h>
ArrayList AL;
int AL.GetCount();
int AL.lpVtbl->GetCount(ArrayList &AL);

Description

The GetCount function returns the number of items that can are stored in the array.

Returns

Returns the number of elements that are stored.

Example
#include <containers.h>
int main(void)
{
    DATA data; // DATA is a user defined type
    ArrayList AL = newArrayList(sizeof(data),5);
    int
    count = AL.Count();
// use the longer but standard syntax
count = AL.lpVtbl->Count(AL);
}


atof

Function: IndexOf

Synopsis
#include <containers.h>
ArrayList AL;
int AL.IndexOf(void *);
int AL.lpVtbl->IndexOf(ArrayList &AL,void *str);

Description

The IndexOf function returns the index of the given element or -1 if not found. Comparisons use memcmp. If the given element pointer is NULL, it will be never found, but no error occurs.

Returns

The index of the element or -1 if not found.

Example
#include <containers.h>
int main(void)
{
    DATA data; // DATA is a user defined type
    ArrayList AL = newArrayList(sizeof(DATA),5);
    // use the short-hand syntax
    int i = AL.IndexOf(data); // i should be 0 if data is the first element
    // use the longer but standard syntax
    i = AL.lpVtbl->IndexOf(AL,data);
}


atof

Function: IndexAt

Synopsis
#include <containers.h>
ArrayList AL;
void *AL.IndexAt(int
    idx);
void *AL.lpVtbl->IndexAt(ArrayList &AL,int idx);
void *operator[](ArrayList &AL,int idx);

Description

The IndexAt returns the character at the given position.

Returns

Indexes the collection and returns the string at the given position. If the index is out of range, the function returns NULL. This can be confusing if you use NULLs within the collection.

Example
#include <containers.h>
int main(void)
{
    DATA d1,d2; // DATA is a user defined type
    ArrayList AL = newArrayList(sizeof(data),5);
void *tab[3];

tab[0] = &d1;    tab[1] =
    &d2;    tab[2] = NULL;
// use the short-hand syntax
    AL.AddRange(tab);
    void *p =
    AL.IndexAt(1); // p should be d2
// use the longer but standard syntax
p = AL.lpVtbl->IndexAt(AL,2); // p should be d2
// Use the operator overloading syntax
p = AL[2]; // p should be d2
}


atof

Function: Insert

Synopsis
#include <containers.h>
ArrayList AL;
int AL.Insert(void *element);
int AL.lpVtbl->Insert(ArrayList &AL,void *element);

Description

The Insert function inserts the given element at the position zero.

Returns

The number of items in the array

Example
#include <containers.h>
int main(void)
{
    DATA data; // DATA is a user defined type
    ArrayList AL = newArrayList(sizeof(DATA),5);

    // use the short-hand syntax
    int i = AL.Insert(data); // i should be 0
    // use the longer but standard syntax
    i = AL.lpVtbl->Insert(AL,data);
}


atof

Function: InsertAt

Synopsis
#include <containers.h>
StringCollection AL;
int AL.InsertAt(void *str,int idx);
int AL.lpVtbl->InsertAt(StringCollection &AL,void *str,int idx);

Description

The InsertAt function inserts the given element at the given position.

Returns

The number of items in the array if the insertion succeeds. The result is zero if there is no more memory or the index is outside the bounds of the array.

Exceptions

CONTAINER_ERROR_NOMEMORY. No more memory is available.
CONTAINER_ERROR_BADARG str is NULL.

Example
#include <containers.h>
int main(void)
{
    ArrayList AL = newArrayList(sizeof(DATA),5);

    // use the short-hand syntax
    int i = AL.InsertAt(data,0); // i should be 1
    // use the longer but standard syntax
    i = AL.lpVtbl->Insert(AL,data,0); // i should be 2 now
}


atof

Function: Pop

Synopsis
#include <containers.h>
ArrayList AL;
void *AL.Pop(void);
void *AL.lpVtbl->Pop(ArrayList &AL);

Description

Returns the element with the highest index in the collection. If the array is empty or if it is marked read-only it returns NULL.

Returns

The string at the given position. If the library was compiled without the garbage collector, the user should free this string.

Example
#include <arraylist.h>
int main(void)
{
    DATA item1; // DATA is a user defined type
    ArrayList *SC = newArrayList(sizeof(DATA),5);
SC->Push(item1);
    // use the short-hand syntax
    void *p = SC->Pop();
    // use the longer but standard syntax
    p = SC->lpVtbl->Pop(SC);
}


atof

Function: Push

Synopsis
#include <containers.h>
ArrayList AL;
int AL.Push(void *str);
int AL.lpVtbl->Push(ArrayList &AL);

Description

Inserts an element at the end of the collection (highest index).

Returns

The result is the number of items in the array if successful, or zero if the array is read-only or there isn't enough memory to complete the operation.

Example
#include <containers.h>
int main(void)
{
    DATA data; // DATA is a user defined type
    ArrayList AL = newArrayList(sizeof(DATA),5);
    // use the short-hand syntax
    int i = AL.Push(data);
    // use the longer but standard syntax
    i = AL.lpVtbl->Push(AL,data); // i should be 2 now
}


atof

Function: Remove

Synopsis
#include <containers.h>
Arraylist AL;
int AL->Remove(void *str);
int AL->lpVtbl->Remove(Arraylist &AL,void *str);

Description

Removes the given element if found. The comparison is done using memcmp

Returns

The result is the number of items in the array if successful, or -1 if the array is read-only or the element is not found.

Example
#include <containers.h>
int main(void)
{
    DATA data ; // DATA is a user defined type
    Arraylist AL = newArraylist(sizeof(data),5);
    int i = AL.Push(data);
    // use the short-hand syntax
i = AL.Remove(data); // i should be zero
    // use the longer but standard syntax
    i = AL.lpVtbl->Remove(AL,data); // i should be -1 now since the item was already removed
}


atof

Function: RemoveAt

Synopsis
#include <containers.h>
ArrayList AL;
int AL.RemoveAt(int idx);
int AL.lpVtbl->RemoveAt(ArrayList &AL,int idx);

Description

Removes the element at the given position.

Returns

The result is the number of items in the array if successful, or -1 if the index is out of range, -2 if the array is read-only.

Example
#include <containers.h>
int main(void)
{
    DATA data;// DATA is a user defined type
    ArrayList *AL = newArrayList(sizeof(DATA),5);
    int i = AL.Push(data);
    // use the short-hand syntax
i = AL.RemoveAt(0); // i should be zero
    // use the longer but standard syntax
    i = AL.lpVtbl->RemoveAt(AL,0); // i should be -1 now
}


atof

Function: ReplaceAt

Synopsis
#include <containers.h>
ArrayList AL;
void *AL.ReplaceAt(int idx,void *newval);
void *AL.lpVtbl->ReplaceAt(ArrayList &SC,int idx,void *newval);
void * operator[]=(ArrayList *AL,int idx,void *newval)

Description

Replaces the element at the given position. The element at the position is freed if the library was not compiled with the garbage collector.

Returns

The result is the new element. This is useful for making chained assignments.

Example
#include <containers.h>
int main(void)
{
    DATA item1; // DATA is a user defined type
    ArrayList AL = newArrayList(5);
    int i = AL.Add(item1);
    // use the short-hand syntax
AL.ReplaceAt(0,"New item 1");
    // use the longer but standard syntax
    AL.lpVtbl->ReplaceAt(AL,"Newest item 1");
}


Lists are containers that support the storage and retrieval of data that is not contiguous in memory

Bit strings are a linear (one dimensional) sequence of bits. Like the other containers, bit strings accept the [ ] notation.

The interface supports the following functions:

Allocating/disposing of bit strings

bitstring *new_bitstring(size_t elementSize,Malloc_Function_Type pmalloc,Free_Function_Type pfree);
void dispose_bitstring(list *);

Copying bit strings

bitstring *copy_bitstring(bitstring *);
bitstring *get_subrange_bitstring(bitstring *bs, size_t start,size_t end);

Accessing the bit string properties

size_t get_size_bitstring(bitstring *bs);
void set_size_bitstring(bitstring *bs);
Malloc_Function_Type get_allocator_bitstring(bitstring *l);
Free_Function_Type get_destructor_bitstring(bitstring *);

Accessing the bits

void *set_element_bitstring(bitstring *bl,size_t position,bool bit);
void *operator []=(bitstring *bs,size_t position,bool bit);
void *get_element_bitstring(bitstring *bs,size_t position);
void *operator [](bitstring *bs, size_t position);

Adding or deleting items

list *insert_bitstring(list *l,size_t position,void *pElement);
list *remove_bitstring(list *l,size_t position);

Applying a function to a whole list

void *iterate_bitstring(bitstring *b,int (*fn)(void *data));
list *binary_map_list(list *l1,list *l2,binary_operator fn);

Utilities

list *concat_bitstring(bitstring *l1,bitstring *l2);
list *nconcat_list(bitstring *b1,bitstring *b2);
list *reverse_bitstring(bitstring *b);
int sprint_bitstring(bitstring *b,size_t bufsiz, char *buf);
int fprint_bitstring(bitstring *b,FILE *out);

Conversions

bitstring overloaded ToBitstring(int);

bitstring overloaded ToBitstring(double);

bitstring overloaded ToBitstring(char *);

bitstring overloaded ToBitstring(long double);


ilogb

Function: countbits

Synopsis
#include <bitstring.h>
int countbits(int x);

Description

The countbits function returns the number of 1 bits in the given integer.

Returns

The countbits function returns the number of set bits.

Library:

Link with containers.lib

Example:

#include <bitstring.h>
#include <stdio.h>
int main(void)
{
    printf("bits in 0xffffffff=%d\n",countbits(-1));
    return 0;
}

Output

bits in 0xffffffff=32


abs

Function: concat_bitstring

Synopsis
#include <bitstring.h>
list *concat_bitstring(bitstring *B1,bitstring *B2);

Description

This function appends the second bitstring to the first one. The inputs are left untouched, i.e. a newly allocated bitstring will be returned.

Returns

A pointer to a new list structure containing the new list. or NULL if there wasn't enough memory.


abs

Function: copy_bitstring

Synopsis
#include <bitstring.h>
list *copy_bitstring(bitstring *bs);

Description

This function copies the bitstring passed in argument. The contents of the bit string are also copied.

Returns

A pointer to a newly created bit string or NULL if there isn't any memory left.


abs

Function: get_size_bitstring

Synopsis
#include <bitstring.h>
int get_size_bitstring(bitstring *bs);

Description

This function returns the number of bits stored in the given bit string. If the input string is NULL, the result is zero.

Returns

The length of the bitstring.


abs

Function: new_bitstring

Synopsis
#include <bitstring.h>
Bitstring *new_bitstring(size_t bitlen);

Description

This function builds a new bit string container. The argument is the number of bits the bit string will contain.

Returns

Returns a pointer to the newly created bit string, or NULL if there is no more memory left.


abs

Function: reverse_bitstring

Synopsis
#include <bitstring.h>
void *reverse_bitstring(bitstring *b);

Description

This function reverses the order of the given bitstring.

Returns

A pointer to the newly created reversed bitstring.


abs

Function: set_element_bitstring

operator [ ]=

Synopsis
#include <bitstring.h>
bool set_element_bitstring(bitstring *bs,size_t position,bool bit);
bool operator []=(bitstring *bs,size_t position, bool bit);

Description

This functions set the element at the given position with the new bit. Note that any bit value different than zero will be understood as 1.

Returns

The boolean value passed in argument.


String Funcs

LCC-Win32 String Library Functions

_i64toa _ui64toa | isxdigit | strlwr | wcschr
_mbccpy | itoa | strncat | wcscmp
atof | mbbtombc | strncmp | wcscoll
atoi | mbbtype | strncpy | wcscspn
atol | mblen | strpbrk | wcslen
ecvt | mbstowcs | strrchr | wcsncat
gcvt | snprintf xsnprintf | strspn | wcsncmp
isalnum | sprintf xsprintf | strstr | wcsncpy
isalpha | strchr | strtod | wcspbrk
iscntrl | strcmp | strtok | wcsrchr
isdigit | strcmpi | strtol | wcsspn
isgraph | strcoll | strtrim | wcsstr
islower | strcpy | strxfrm | wcstok
isprint | strcspn | tolower | wcstol
ispunct | strerror | toupper | wcstombs
isspace | strlen | vsprintf | wcsxfrm
isupper |  | vsnprintf | wctomb
 |  | wcscat |


_i64toa

Function: _i64toa _ui64toa

Synopsis
#include <stdlib.h>
char *_i64toa(long long value, char *outbuf, int radix);
char *_ui64toa(unsigned long long value, char *outbuf, int radix);

Description

Converts the given 64 bit value into a character string stored in outbuf, using the given radix.


_mbccpy

Function: _mbccpy

Synopsis
#include <mbstring.h>
void _mbccpy(unsigned char * s1,unsigned char * s2);

Description

The _mbccpy function copies the multibyte string pointed to by s2 (including the terminating null character) into the array pointed to by s1. If the s1 argument doesn't point to the lead byte of a multiple character no copy is performed.

Returns

The mbccpy function returns no value

Portability

Windows


atof

Function: atof

Synopsis
#include <stdlib.h>
double atof(const char *nptr);

Description

The atof function converts the initial portion of the string pointed to by nptr to double representation. Except for the behavior on error, it is equivalent to strtod(nptr, (char **)NULL)

Returns

The atof function returns the converted value.

Example
#include <stdlib.h>
int main(void)
{
    char *s;
    s = "-2309.12E-5";
    printf("%15.13g",atof(s));
return 0;
}
-0.0230912


atoi

Function: atoi atoi64

Synopsis
#include <stdlib.h>
int atoi(const char *nptr);
long long atoi64(const char *);

Description

The atoi function converts the initial portion of the string pointed to by nptr to int representation.

Except for the behavior on error, it is are equivalent to

atoi: (int)strtol(nptr, (char **)NULL, 10)

Returns

The atoi function returns the converted value.


atol

Function: atol

Synopsis
#include <stdlib.h>
long int atol(const char *nptr);

Description

The atol function converts the initial portion of the string pointed to by nptr to long int representation.

Except for the behavior on error, they are equivalent to

atol: strtol(nptr, (char **)NULL, 10)

Returns

The atol function returns the converted value.


ecvt

Function: ecvt

Synopsis
#include <stdlib.h>
char *_ecvt(double value, int count, int *dec, int *sign);

Description

converts a floating-point number to a character string. The value parameter is the floating-point number to be converted. This function stores up to count digits of value as a string and appends a null character. If the number of digits in value exceeds count, the low-order digit is rounded. If there are fewer than count digits, the string is padded with zeros.

Only digits are stored in the string. The position of the decimal point and the sign of value can be obtained from dec and sign after the call. The dec parameter points to an integer value giving the position of the decimal point with respect to the beginning of the string. A 0 or negative integer value indicates that the decimal point lies to the left of the first digit. The sign parameter points to an integer that indicates the sign of the converted number. If the integer value is 0, the number is positive, otherwise the number is negative.

_ecvt and _fcvt use a single statically allocated buffer for the conversion. Each call to one of these routines destroys the result of the previous call.

Portability

Windows / Unix


gcvt

Function: gcvt

Synopsis
#include <stdlib.h>
char *_gcvt(double value, int ndigits, char *buf);

Description

Converts a floating-point number to a character string. The value parameter is the floating-point number to be converted. It produces ndigits significant digits in either printf() F format or E format.

_gcvt and _fcvt use a single statically allocated buffer for the conversion. Each call to one of these routines destroys the result of the previous call.

Portability

Windows / Unix


isalnum

Function: isalnum iswalnum

Synopsis
#include <ctype.h>
int isalnum(int c);
int iswalnum(wint_t c);

Description

The isalnum function tests for any character for which isalpha or isdigit is true.


isalpha

Function: isalpha

Synopsis
#include <ctype.h>
int isalpha(int c);

Description

The isalpha function tests for any character for which isupper or islower is true, or any character that is one of a locale-specific set of alphabetic characters for which none of iscntrl, isdigit, ispunct, or isspace is true. In the "C" locale, isalpha returns true only for the characters for which isupper or islower is true.


iscntrl

Function: iscntrl

Synopsis
#include <ctype.h>
int iscntrl(int c);

Description

The iscntrl function tests for any control character.


isdigit

Function: isdigit

Synopsis
#include <ctype.h>
int isdigit(int c);

Description

The isdigit function tests for any decimal-digit character, i.e. characters between 0 and 9 inclusive.


isgraph

Function: isgraph

Synopsis
#include <ctype.h>
int isgraph(int c);

Description

The isgraph function tests for any printing character except space ( ).


islower

Function: islower

Synopsis
#include <ctype.h>
int islower(int c);

Description

The islower function tests for any character that is a lowercase letter or is one of a locale-specific set of characters for which none of iscntrl, isdigit, ispunct, or isspace is true. In the "C" locale, islower returns true only for the characters defined as lowercase letters


isprint

Function: isprint

Synopsis
#include <ctype.h>
int isprint(int c);

Description

The isprint function tests for any printing character including space ( ).


ispunct

Function: ispunct

Synopsis
#include <ctype.h>
int ispunct(int c);

Description

The ispunct function tests for any printing character that is one of a locale-specific set of punctuation characters for which neither isspace nor isalnum is true.


isspace

Function: isspace

Synopsis
#include <ctype.h>
int isspace(int c);

Description

The isspace function tests for any character that is a standard white-space character or is one of a locale-specific set of characters for which isalnum is false. The standard white-space characters are the following: space ( ), form feed (\f), new-line (\n), carriage return (\r), horizontal tab (\t), and vertical tab (\v). In the "C" locale, isspace returns true only for the standard white-space characters.


isupper

Function: isupper

Synopsis
#include <ctype.h>
int isupper(int c);

Description

The isupper function tests for any character that is an uppercase letter or is one of a locale-specific set of characters for which none of iscntrl, isdigit, ispunct, or isspace is true. In the "C" locale, isupper returns true only for the characters defined as uppercase letters.


isxdigit

Function: isxdigit

Synopsis
#include <ctype.h>
int isxdigit(int c);

Description

The isxdigit function tests for any hexadecimal-digit character.


itoa

Function: itoa

Synopsis
#include <stdlib.h>
char *itoa(int value, char *string, int radix);

Description

The itoa function converts the digits of the given value argument to a null-terminated character string and stores the result (up to 17 bytes) in string. If radix equals 10 and value is negative, the first character of the stored string is the minus sign (-)

Returns

Returns a pointer to the given string.


mbbtombc

Function: mbbtombc

Synopsis
#include <mbstring.h>
unsigned short mbbtombc(unsigned short c);
unsigned short _mbbtombc(unsigned short c);

Description

The mbbtombc function converts a given single-byte multibyte character to a corresponding double-byte multibyte character. Characters must be within the range 0x20 0x7E or 0xA1 0xDF to be converted.

Returns

If successful, it returns a multi byte character. Otherwise it returns c.


mbbtype

Function: mbbtype

Synopsis
#include <mbstring.h>
#include <mbctype.h>
int mbbtype(unsigned char c, int type);
int _mbbtype(unsigned char c, int type);

Description

The mbbtype function returns the type of byte within a string. This decision is context-sensitive as specified by the value of type, which provides the control test condition. type is the type of the previous byte in the string. The manifest constants are defined in MBCTYPE.H.

Returns

If successful, it returns a multi byte character. Otherwise it returns c.


mblen

Function: mblen

Synopsis
#include <stdlib.h>
int mblen(const char *src, size_t n);

Description

If src is not a null pointer, the mblen function determines the number of bytes contained in the multibyte character pointed to by src. Except that the shift state of the mbtowc function is not affected, it is equivalent to mbtowc((wchar_t *)0, s, n);

The implementation shall behave as if no library function calls the mblen function.

Returns

If src is a null pointer, the mblen function returns a nonzero or zero value, if multibyte character encodings, respectively, do or do not have state-dependent encodings. If src is not a null pointer, the mblen function either returns 0 (if src points to the null character), or returns the number of bytes that are contained in the multibyte character (if the next n or fewer bytes form a valid multibyte character), or returns 1 (if they do not form a valid multibyte character).


mbstowcs

Function: mbstowcs

Synopsis
#include <stdlib.h>
size_t mbstowcs(wchar_t * restrict pwcs, const char * restrict s, size_t n);

Description

The mbstowcs function converts a sequence of multibyte characters that begins in the initial shift state from the array pointed to by 's' into a sequence of corresponding codes and stores not more than n codes into the array pointed to by pwcs. No multibyte characters that follow a null character (which is converted into a code with value zero) will be examined or converted. Each multibyte character is converted as if by a call to the mbtowc function, except that the shift state of the mbtowc function is not affected.

No more than 'n' elements will be modified in the array pointed to by pwcs. If copying takes place between objects that overlap, the behavior is undefined.

Returns

If an invalid multibyte character is encountered, the mbstowcs function returns (size_t)-1. Otherwise, the mbstowcs function returns the number of array elements modified, not including a terminating zero code, if any.


snprintf

Function: snprintf xsnprintf

Synopsis
#include <stdio.h>
int snprintf(char * restrict s, size_t length, const char * restrict format, ...);
int xsnprintf(char * restrict s, size_t length, const char * restrict format, ...);

Description

The snprintf function is equivalent to fprintf, except that the output is written into an array (specified by argument 's') rather than to a stream. If length is zero, nothing is written, and 's' may be a null pointer. Otherwise, output characters beyond the length-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.

This function is in the native windows C runtime. It does not support long long or long double arguments.

The xsnprintf function is the lcc-win32 version of snprintf that supports long long and long double data. It is based on the trio package.

Returns

The snprintf function returns the number of characters that would have been written had length been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than length.

See printf for format specifiers.


sprintf

Function: sprintf

Synopsis
#include <stdio.h>
int sprintf(char * restrict s, const char * restrict format, ...);
int xsprintf(char * restrict s, const char *restrict format,...);

Description

The sprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument 's') rather than to a stream. A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.

This function is the native windows C runtime. It does not support long long or long double arguments.

The xsprintf function is the lcc-win32 version of sprintf, that supports long long and long double data. It is based on the trio package.

Returns

The sprintf function returns the number of characters written in the array, not counting the terminating null character, or a negative value if an encoding error occurred.

See printf for format specifiers.


strchr

Function: strchr

Synopsis
#include <string.h>
char *strchr(const char *s, int c);

Description

The strchr function locates the first occurrence of c (converted to a char) in the string pointed to by s.

The terminating null character is considered to be part of the string.

Returns

The strchr function returns a pointer to the located character, or a null pointer if the character does not occur in the string.


strcmp

Function: strcmp

Synopsis
#include <string.h>
int strcmp(const char *s1, const char *s2);

Description

The strcmp function compares the string pointed to by s1 to the string pointed to by s2.

Returns

The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.


strcmpi

Function: strcmpi , stricmp , _strcmpi , _stricmp

Synopsis
#include <string.h>
int strcmpi(const char *s1, const char *s2);
int stricmp(const char *s1, const char *s2);

This functions are NOT part of the ANSI C library.

Description

The strcmpi function compares the string pointed to by s1 to the string pointed to by s2 ignoring case differences between each letter.

Returns

The strcmpi function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

Remarks

Lcc-win32 defines both with and without underscores for your convenience. Microsoft supports the names with underscores.

Actually, in CRTDLL.DLL only _strcmpi is exported.


strcoll

Function: strcoll

Synopsis
#include <string.h>
int strcoll(const char *s1, const char *s2);

Description

The strcoll function compares the string pointed to by s1 to the string pointed to by s2, both interpreted as appropriate to the LC_COLLATE category of the current locale.

Returns

The strcoll function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2 when both are interpreted as appropriate to the current locale.


strcpy

Function: strcpy

Synopsis
#include <string.h>
char *strcpy(char * restrict s1,const char * restrict s2);

Description

The strcpy function copies the string pointed to by s2 (including the terminating null character) into the array pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.

Returns

The strcpy function returns the value of s1.


strcspn

Function: strcspn

Synopsis
#include <string.h>
size_t strcspn(const char *s1, const char *s2);

Description

The strcspn function computes the length of the maximum initial segment of the string pointed to by s1 which consists entirely of characters not from the string pointed to by s2.

Returns

The strcspn function returns the length of the segment.


strerror

Function: strerror

Synopsis
#include <string.h>
char *strerror(int errnum);

Description

The strerror function maps errnum to an error-message string, returning a pointer to the string. strerror does not actually print the message: For that, you need to call an output function such as fprintf:

if (( access( "datafile",2 )) == -1 )
    fprintf( stderr, "%s", strerror(NULL) );

The actual error number for strerror is stored in the variable errno. The system error messages are accessed through the variable _sys_errlist, which is an array of messages ordered by error number.

strerror accesses the appropriate error message by using the errno value as an index to the variable _sys_errlist. The value of the variable _sys_nerr is defined as the maximum number of elements in the _sys_errlist array. To produce accurate results, call strerror immediately after a library routine returns with an error. Otherwise, subsequent calls to strerror can overwrite the errno value.


strstr

Function: strbase64

Synopsis
#include <string.h>

char *strtobase64( char *dst,size_t destsiz,unsigned char *src,size_t srcsiz);
char *strfrombase64( char *dst,size_t destsiz,unsigned char *src,size_t srcsiz);

Description

This functions encode or decode the binary buffers into base 64 encoded data.

strtobase64 encodes srcsiz bytes starting at the pointer src and writes the result into dst. No more than dstsiz bytes are written. If the dst pointer is NULL, the function returns the number of characters that would be necessary to encode the source.

strfrombase64 decodes srcsiz bytes starting at src, and writes the result to dst. No more than dstsiz bytes are written. If the dst pointer is NULL, the function returns the number of characters that would be required to decode the source.

Returns

The number of characters encoded/decoded or the number of characters required if the destination pointer is NULL. If an internal error is detected, the result is -1.

Example:

#include <string.h>
#include <stdio.h>
int main(void)
{
    char srcbuf[1024],dstbuf[1024];
    int siz;

    strcpy(srcbuf,"This is a string to encode");
    siz = strtobase64(dstbuf,sizeof(dstbuf),srcbuf,strlen(srcbuf));
    printf("%s -->\n%s\n",srcbuf,dstbuf);
    strfrombase64(srcbuf,sizeof(srcbuf),dstbuf,siz);
    printf("Decoding:\n%s -->\n%s\n",dstbuf,srcbuf);
    return 0;
}

produces:

This is a string to encode -->
VGhpcyBpcyBhIHN0cmluZyB0byBlbmNvZGU=
Decoding:
VGhpcyBpcyBhIHN0cmluZyB0byBlbmNvZGU= -->
This is a string to encode


strlen

Function: strlen

Synopsis
#include <string.h>
size_t strlen(const char *s);

Description

The strlen function computes the length of the string pointed to by s.

Returns

The strlen function returns the number of characters that precede the terminating null character.

Note

If the optimization option is chosen, lcc-win32 will inline this function.

See also:

strnlen_s


strlwr

Function: strlwr

Synopsis
#include <string.h>
size_t strlwr(const char *s);

Description

The strlwr function coverts its input string to lowercase.

Returns

The strlwr function returns a pointer to the converted string.

See also:

strnlwr


strncat

Function: strncat

Synopsis
#include <string.h>
char *strncat(char * restrict s1,const char * restrict s2, size_t n);

Description

The strncat function appends not more than n characters (a null character and characters that follow it are not appended) from the array pointed to by s2 to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1. A terminating null character is always appended to the result.Thus, the maximum number of characters that can end up in the array pointed to by s1 is strlen(s1)+n+1. If copying takes place between objects that overlap, the behavior is undefined.

Returns

The strncat function returns the value of s1.


strncmp

Function: strncmp, strnicmp

Synopsis
#include <string.h>
int strncmp(const char *s1, const char *s2, size_t n);

Description

The strncmp function compares not more than n characters (characters that follow a null character are not compared) from the array pointed to by s1 to the array pointed to by s2.

Returns

The strncmp function returns an integer greater than, equal to, or less than zero, accordingly as the possibly null-terminated array pointed to by s1 is greater than, equal to, or less than the possibly null-terminated array pointed to by s2.

strnicmp ignores the case when comparing the strings.

Portability

strnicmp is a strictly windows function.


strncpy

Function: strncpy

Synopsis
#include <string.h>
char *strncpy(char * restrict s1,const char * restrict s2, size_t n);

Description

The strncpy function copies not more than n characters (characters that follow a null character are not copied) from the array pointed to by s2 to the array pointed to by s1.Thus, if there is no null character in the first n characters of the array pointed to by s2, the result will not be null-terminated. If copying takes place between objects that overlap, the behavior is undefined.

If the array pointed to by s2 is a string that is shorter than n characters, null characters are appended to the copy in the array pointed to by s1, until n characters in all have been written.

Returns

The strncpy function returns the value of s1.


strlen

Function: strnlen strnlen_s

Synopsis
#include <string.h>
size_t strnlen(const char *s,size_t maxsize);
size_t strnlen_s(const char *s,size_t maxsize);

Description

The strnlen_s and the strnlen functions compute the length of the string pointed to by s. Both are identical, but the name strnlen_s is defined by ANSIC, and the name strnlen is proposed by GNU. This function will never access any characters beyond the given maximum length.

If the scan reaches s+maxsize without finding any zero byte, maxsize is returned.

Returns

The strnlen/strnlen_s functions returns the number of characters that precede the terminating null character. If s is NULL, zero is returned.

Note

If the optimization option is chosen, lcc-win32 will inline this function.

See also:

strlen


strcpy

Function: strlcpy

Synopsis
#include <string.h>
unsigned int strcpy(char * restrict s1,const char * restrict s2,unsigned int bufsize);

Description

The strlcpy function copies the string pointed to by s2 (including the terminating null character) into the array pointed to by s1 respecting the size of s1 that is given in the third parameter. The resulting string is always zero terminated. If copying takes place between objects that overlap, the behavior is undefined.

Returns

The strcpy function returns the length of the resulting string.


strlwr

Function: strnlwr

Synopsis
#include <string.h>
size_t strnlwr(const char *s, size_t maxsize);

Description

The strnlwr function converts its input string to lowercase, processing at most maxsize characters. If the input string is NULL, nothing is done and NULL is returned.

Returns

The strnlwr function returns a pointer to the converted string.

See also


strncat

Function: strlcat

Synopsis
#include <string.h>
char *strlcat(char * restrict s1,const char * restrict s2,unsigned int bufsize);

Description

The strlcat function appends to the array of characters pointed by s1 characters from the array pointed to by s2 respecting the size of s1 given in the third parameter "bufsize". The initial character of s2 overwrites the null character at the end of s1. A terminating null character is always appended to the result. Thus, the maximum number of characters that can end up in the array pointed to by s1 is bufsize-1. If copying takes place between objects that overlap, the behavior is undefined.

Returns

The strlcat function returns the length of s2.

See also:

strcat, strncat strlcat


strstr

Function: strnupr

Synopsis
#include <string.h>
char *strnupr(const char *s1,size_t maxsize);

Description

The strnupr function transforms in place the null terminated character string pointed to by s1 into uppercase characters, processing at most maxsize characters. If the given pointer s1 is NULL, nothing is done and the function returns NULL.

Returns

The strupr function returns a pointer to s1.

See also:

strupr


strpbrk

Function: strpbrk

Synopsis
#include <string.h>
char *strpbrk(const char *s1, const char *s2);

Description

The strpbrk function locates the first occurrence in the string pointed to by s1 of any character from the string pointed to by s2.

Returns

The strpbrk function returns a pointer to the character, or a null pointer if no character from s2 occurs in s1.

Example:

#include<string.h>
#include<stdio.h>

int main(void)
{
  char string[]="Hi there, Chip!";
  char *string_ptr;

  while((string_ptr=strpbrk(string," "))!=NULL)
    *string_ptr='-';

  printf("New string is \"%s\".\n",string);
  return 0;
}


strrchr

Function: strrchr

Synopsis
#include <string.h>
char *strrchr(const char *s, int c);

Description

The strrchr function locates the last occurrence of c (converted to a char) in the string pointed to by s. The terminating null character is considered to be part of the string.

Returns

The strrchr function returns a pointer to the character, or a null pointer if c does not occur in the string.


strncat

Function: strrepl

Synopsis
#include <string.h>
int strrepl(char * InputString, char *StringToFind, char *Replacement, char *Output);

Description

The strrepl function replaces in InputString all occurrences of StringToFind by Replacement, writing the modified contents into the Output string. The original input string is not modified.

If the Output argument is NULL, strrepl will return the space that would be needed (including the terminating zero) for the replacement.

If Replacement is NULL and Output is not NULL, all occurrences of StringToFind will be erased.

Returns

The strrepl function returns the needed length for the replacements if its Output argument is NULL. If not, it returns the number of replacements done.

Example

#include <string.h>

#include <stdio.h>

int main(void)
{
    char *p = "This is a string with WORD in it, and then another WORD in it ";
    char a[512];

    strcpy(a,p);
    printf("%s\n",a);
    printf("needed length is %d\n",strrepl(p,"WORD","ANOTHER WORD",NULL));
    strrepl(p,"WORD","ANOTHER WORD",a);
    printf("(%d), %s\n",1+strlen(a),a);
    strrepl(a,"ANOTHER WORD ",NULL,a);
    printf("(%d), %s\n",strlen(a),a);

    return 0;
}

This will print:

This is a string with WORD in it, and then another WORD in it
needed length is 79
(79), This is a string with ANOTHER WORD in it, and then another ANOTHER WORD in it
(52), This is a string with in it, and then another in it


strspn

Function: strspn

Synopsis
#include <string.h>
size_t strspn(const char *s1, const char *s2);

Description

The strspn function computes the length of the maximum initial segment of the string pointed to by s1 which consists entirely of characters from the string pointed to by s2.

Returns

The strspn function returns the length of the segment.

Example:

#include<string.h>
#include<stdio.h>

int main(void)
{
  char string[]="7803 Main St.";

  printf("The number length is %d.\n",strspn(string,"1234567890"));

  return 0;
}

Output:

The number length is 4.


strstr

Function: strstr

Synopsis
#include <string.h>
char *strstr(const char *s1, const char *s2);

Description

The strstr function locates the first occurrence in the string pointed to by s1 of the sequence of characters (excluding the terminating null character) in the string pointed to by s2.

Returns

The strstr function returns a pointer to the located string, or a null pointer if the string is not found. If s2 points to a string with zero length, the function returns s1.


strtod

Function: strtod strtold

Synopsis
#include <stdlib.h>
double strtod(const char * restrict nptr, char ** restrict endptr);
double strtold(const char * restrict nptr, char ** restrict endptr);

Description

The strtod function converts the initial portion of the string pointed to by nptr to double, the strtold function converts it to long double representation respectively. First, they decompose the input string into three parts: an initial, possibly empty, sequence of white-space characters (as specified by the isspace function), a subject sequence resembling a floating-point constant or representing an infinity or NaN (not a number); and a final string of one or more unrecognized characters, including the terminating null character of the input string. Then, they attempt to convert the subject sequence to a floating-point number, and return the result.

The expected form of the subject sequence is an optional plus or minus sign, then one of the following:

· a nonempty sequence of decimal digits optionally containing a decimal-point character, then an optional exponent part as defined in 6.4.4.2;

· a0x or 0X, then a nonempty sequence of hexadecimal digits optionally containing a decimal-point character, then an optional binary-exponent part as defined in 6.4.4.2, where either the decimal-point character or the binary-exponent part is present;

· one of INF or INFINITY, ignoring case

· one of NAN or NAN(n-char-sequence opt ), ignoring case in the NAN part, where:

n-char-sequence:

digit
nondigit
n-char-sequence digit
n-char-sequence nondigit

The subject sequence is defined as the longest initial subsequence of the input string, starting with the first non-white-space character, that is of the expected form. The subject sequence contains no characters if the input string is not of the expected form. If the subject sequence has the expected form for a floating-point number, the sequence of characters starting with the first digit or the decimal-point character (whichever occurs first) is interpreted as a floating constant, except that the decimal-point character is used in place of a period, and that if neither an exponent part, a binary-exponent part, nor a decimal-point character appears, a decimal point is assumed to follow the last digit in the string. A character sequence INF or INFINITY is interpreted as an infinity, if representable in the return type, else like a floating constant that is too large for the range of the return type. A character sequence NAN or NAN (n-char-sequence opt), is interpreted as a quiet NaN, if supported in the return type, else like a subject sequence part that does not have the expected form; the meaning of the n-char sequences is implementation-defined. If the subject sequence begins with a minus sign, the value resulting from the conversion is negated. A pointer to the final string is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

If the subject sequence has the hexadecimal form and FLT_RADIX is a power of 2, then the value resulting from the conversion is correctly rounded.

In other than the "C" locale, additional locale-specific subject sequence forms may be accepted.

If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

Recommended practice

If the subject sequence has the hexadecimal form and FLT_RADIX is not a power of 2, then the result should be one of the two numbers in the appropriate internal format that are adjacent to the hexadecimal floating source value, with the extra stipulation that the error should have a correct sign for the current rounding direction.

If the subject sequence has the decimal form and at most DECIMAL_DIG (defined in <float.h>) significant digits, then the value resulting from the conversion should be correctly rounded. If the subject sequence D has the decimal form and more than DECIMAL_DIG significant digits, consider the two bounding, adjacent decimal strings L and U, both having DECIMAL_DIG significant digits, such that the values of L, D, and U satisfy L D U. The result of conversion should be one of the (equal or adjacent) values that would be obtained by correctly rounding L and U according to the current rounding direction, with the extra stipulation that the error with respect to D should have a correct sign for the current rounding direction.

Returns

The functions return the converted value, if any. If no conversion could be performed, zero is returned. If the correct value is outside the range of representable values, plus or minus HUGE_VAL, HUGE_VALF, or HUGE_VALL is returned (according to the return type and sign of the value), and the value of the macro ERANGE is stored in errno. If the result underflows, the functions return a value whose magnitude is no greater than the smallest normalized positive number in the return type; whether errno acquires the value ERANGE is implementation-defined.


strtok

Function: strtok

Synopsis
#include <string.h>
char *strtok(char * restrict s1,const char * restrict s2);

Description

A sequence of calls to the strtok function breaks the string pointed to by s1 into a sequence of tokens, each of which is delimited by a character from the string pointed to by s2. The first call in the sequence has a non-null first argument; subsequent calls in the sequence have a null first argument. The separator string pointed to by s2 may be different from call to call.

The first call in the sequence searches the string pointed to by s1 for the first character that is not contained in the current separator string pointed to by s2. If no such character is found, then there are no tokens in the string pointed to by s1 and the strtok function returns a null pointer. If such a character is found, it is the start of the first token.

#include <string.h>
#include <stdio.h>

int main(void)
{
    char input[16] = "abc,d";
    char *p;

    /* strtok places a NULL terminator
       in front of the token, if found */
    p = strtok(input, ",");
    if (p) printf("%s\n", p);

    /* A second call to strtok using a NULL
       as the first parameter returns a pointer
       to the character following the token */
    p = strtok(NULL, ",");
    if (p) printf("%s\n", p);
    return 0;
}


strtol

Function: strtol,strtoll,strtoul strtoull

Synopsis
#include <stdlib.h>
long int strtol(const char * restrict nptr,char ** restrict endptr,int base);
long long strtoll(const char * restrict nptr,char ** restrict endptr,int base);
unsigned long int strtoul(const char * restrict nptr,char ** restrict endptr,int base);
unsigned long long strtoull(const char * restrict nptr,char ** restrict endptr,int base);

Description

The strtol, strtoll, and strtoul functions convert the initial portion of the string pointed to by nptr to long int, long long int, unsigned long int, and unsigned long long int representation, respectively. First, they decompose the input string into three parts: an initial, possibly empty, sequence of white-space characters (as specified by the isspace function), a subject sequence resembling an integer represented in some radix determined by the value of base, and a final string of one or more unrecognized characters, including the terminating null character of the input string. Then, they attempt to convert the subject sequence to an integer, and return the result.

If the value of base is zero, the expected form of the subject sequence is that of an integer constant optionally preceded by a plus or minus sign, but not including an integer suffix. If the value of base is between 2 and 36 (inclusive), the expected form of the subject sequence is a sequence of letters and digits representing an integer with the radix specified by base, optionally preceded by a plus or minus sign, but not including an integer suffix. The letters from a (or A) through z (or Z) are ascribed the values 10 through 35; only letters and digits whose ascribed values are less than that of base are permitted. If the value of base is 16, the characters 0x or 0X may optionally precede the sequence of letters and digits, following the sign if present.

The subject sequence is defined as the longest initial subsequence of the input string, starting with the first non-white-space character, that is of the expected form. The subject sequence contains no characters if the input string is empty or consists entirely of white space, or if the first non-white-space character is other than a sign or a permissible letter or digit.

If the subject sequence has the expected form and the value of base is zero, the sequence of characters starting with the first digit is interpreted as an integer constant according to the rules of 6.4.4.1. If the subject sequence has the expected form and the value of base is between 2 and 36, it is used as the base for conversion, ascribing to each letter its value as given above. If the subject sequence begins with a minus sign, the value resulting from the conversion is negated (in the return type). A pointer to the final string is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

Returns

The strtol, and strtoul functions return the converted value, if any. If no conversion could be performed, zero is returned. If the correct value is outside the range of representable values, LONG_MIN, LONG_MAX, LLONG_MIN, LLONG_MAX, ULONG_MAX,orULLONG_MAX is returned (according to the return type and sign of the value, if any), and the value of the macro ERANGE is stored in errno.


strtrim

Function: strtrim

Synopsis
#include <string.h>
int strtrim(char *str);

Description

strtrim will destructively eliminate redundant spaces from the given string. All sequences of more than one space or tab will be replaced by a single space. strtrim uses the macro isspace to determine whether a character is a space char or not.

Returns

The length of the (possibly changed) string.

Note

This function is not part of the standard library. Its code is:

int strtrim(char *str)
{
    char *src = str,*dst = str;

    while (isspace(*src))
        src++;
    do {
        while (*src && !isspace(*src))
            *dst++ = *src++;
        if (*src) {
            *dst++ = *src++;
            while (isspace(*src))
                src++;
        }
    } while (*src);
    if (dst != src && isspace(dst[-1]))
        dst--;
    *dst = 0;
    return dst - src;
}


strxfrm

Function: strxfrm

Synopsis
#include <tchar.h>
size_t strxfrm(char * restrict s1,const char * restrict s2, size_t n);

Description

The strxfrm function transforms the string pointed to by s2 and places the resulting string into the array pointed to by s1. The transformation is such that if the strcmp function is applied to two transformed strings, it returns a value greater than, equal to, or less than zero, corresponding to the result of the strcoll function applied to the same two original strings. No more than 'n' characters are placed into the resulting array pointed to by s1, including the terminating null character. If n is zero, s1 is permitted to be a null pointer. If copying takes place between objects that overlap, the behavior undefined.

Returns

The strxfrm function returns the length of the transformed string (not including the terminating null character). If the value returned is n or more, the contents of the array pointed to by s1 are indeterminate.


tolower

Function: tolower

Synopsis
#include <ctype.h>
int tolower(int c);

Description

The tolower function converts an uppercase letter to a corresponding lowercase letter.

Returns

If the argument is a character for which isupper is true and there are one or more corresponding characters, as specified by the current locale, for which islower is true, the tolower function returns one of the corresponding characters (always the same one for any given locale); otherwise, the argument is returned unchanged.


toupper

Function: toupper

Synopsis
#include <ctype.h>
int toupper(int c);

Description

The toupper function converts a lowercase letter to a corresponding uppercase letter.

Returns

If the argument is a character for which islower is true and there are one or more corresponding characters, as specified by the current locale, for which isupper is true, the toupper function returns one of the corresponding characters (always the same one for any given locale); otherwise, the argument is returned unchanged.


vsprintf

Function: vsprintf vswprintf xvsprintf

Synopsis
#include <stdarg.h>
#include <stdio.h>
int vsprintf(char * restrict s, const char * restrict format, va_list arg);
int xvsprintf(char * restrict s, const char * restrict format, va_list arg);

#include <stdarg.h>
#include <wchar.h>
int vswprintf(wchar_t * restrict s, const wchar_t *restrict format, va_list arg);

Description

The vsprintf function is equivalent to sprintf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vsprintf function does not invoke the va_end macro. If copying takes place between objects that overlap, the behavior is undefined.

Returns

The vsprintf function returns the number of characters written in the array, not counting the terminating null character, or a negative value if an encoding error occurred.

The vswprintf function is the wide character counterpart of vsprintf and xvsprintf is the LCC-Win32 version that allows the use of long long and long double types.

See printf for format specifiers.


vsnprintf

Function: vsnprintf xvsnprintf

Synopsis
#include <stdarg.h>
#include <stdio.h>
int vsnprintf(char *str, size_t count, const char *fmt, va_list args);
int xvsnprintf(char *str, size_t count, const char *fmt, va_list args);

Description

The vsnprintf() function formats data under control of the format control string and stores the result in str. The maximum number of characters to store, including a terminating null character, is specified by count. For details on the format string, refer to the printf() function.

The vsnprintf() function is equivalent to snprintf(), with a variable argument list.

Returns

The number of characters written into the array, not counting the terminating null character, or a negative value if count or more characters are requested to be generated. An error can occur while converting a value for output.

The xvsnprintf is the LCC-Win32 version that allows the use of long long and long double types.

EXample

#include <stdio.h>
#include <stdarg.h>
#include <string.h>

char msgbuf[80];

char *fmtmsg( char *format, ... )
{
    va_list arglist;

    va_start( arglist, format );
    strcpy( msgbuf, "Error: " );
    vsnprintf( &msgbuf[7], 80-7, format, arglist );
    va_end( arglist );
    return( msgbuf );
}

int main( void )
{
    char *msg;

    msg = fmtmsg( "%s %d %s", "Failed", 100, "times" );
    printf( "%s\n", msg );

    return 0;
}


wcscat

Function: wcscat

Synopsis
#include <wchar.h>
wchar_t *wcscat(wchar_t * restrict s1, const wchar_t * restrict s2);

Description

The wcscat function appends a copy of the wide string pointed to by s2 (including the terminating null wide character) to the end of the wide string pointed to by s1. The initial wide character of s2 overwrites the null wide character at the end of s1.

Returns

The wcscat function returns the value of s1.


wcschr

Function: wcschr

Synopsis
#include <wchar.h>
wchar_t *wcschr(const wchar_t *s, wchar_t c);

Description

The wcschr function locates the first occurrence of c in the wide string pointed to by s. The terminating null wide character is considered to be part of the wide string.

Returns

The wcschr function returns a pointer to the located wide character, or a null pointer if the wide character does not occur in the wide string.


wcscmp

Function: wcscmp

Synopsis
#include <wchar.h>
int wcscmp(const wchar_t *s1, const wchar_t *s2);

Description

The wcscmp function compares the wide string pointed to by s1 to the wide string pointed to by s2.

Returns

The wcscmp function returns an integer greater than, equal to, or less than zero, accordingly as the wide string pointed to by s1 is greater than, equal to, or less than the wide string pointed to by s2.


wcscoll

Function: wcscoll

Synopsis
#include <wchar.h>
int wcscoll(const wchar_t *s1, const wchar_t *s2);

Description

The wcscoll function compares the wide string pointed to by s1 to the wide string pointed to by s2, both interpreted as appropriate to the LC_COLLATE category of the current locale.

Returns

The wcscoll function returns an integer greater than, equal to, or less than zero, accordingly as the wide string pointed to by s1 is greater than, equal to, or less than the wide string pointed to by s2 when both are interpreted as appropriate to the current locale.


wcscspn

Function: wcscspn

Synopsis
#include <wchar.h>
size_t wcscspn(const wchar_t *s1, const wchar_t *s2);

Description

The wcscspn function computes the length of the maximum initial segment of the wide string pointed to by s1 which consists entirely of wide characters not from the wide string pointed to by s2.

Returns

The wcscspn function returns the length of the segment.


wcslen

Function: wcslen

Synopsis
#include <wchar.h>
size_t wcslen(const wchar_t *s);

Description

The wcslen function computes the length of the wide string pointed to by s.

Returns

The wcslen function returns the number of wide characters that precede the terminating null wide character.


wcsncat

Function: wcsncat

Synopsis
#include <wchar.h>
wchar_t *wcsncat(wchar_t * restrict s1,const wchar_t * restrict s2,size_t n);

Description

The wcsncat function appends not more than n wide characters (a null wide character and those that follow it are not appended) from the array pointed to by s2 to the end of the wide string pointed to by s1. The initial wide character of s2 overwrites the null wide character at the end of s1.

A terminating null wide character is always appended to the result.

Returns

The wcsncat function returns the value of s1.


wcsncmp

Function: wcsncmp

Synopsis
#include <wchar.h>
int wcsncmp(const wchar_t *s1, const wchar_t *s2, size_t n);

Description

The wcsncmp function compares not more than n wide characters (those that follow a null wide character are not compared) from the array pointed to by s1 to the array pointed to by s2.

Returns

The wcsncmp function returns an integer greater than, equal to, or less than zero, accordingly as the possibly null-terminated array pointed to by s1 is greater than, equal to, or less than the possibly null-terminated array pointed to by s2.


wcsncpy

Function: wcsncpy

Synopsis
#include <wchar.h>
wchar_t *wcsncpy(wchar_t * restrict s1,const wchar_t * restrict s2,size_t n);

Description

The wcsncpy function copies not more than n wide characters (those that follow a null wide character are not copied) from the array pointed to by s2 to the array pointed to by s1. If the array pointed to by s2 is a wide string that is shorter than n wide characters, null wide characters are appended to the copy in the array pointed to by s1, until n wide characters in all have been written.

Returns

The wcsncpy function returns the value of s1.


strncat

Function: wcsrepl

Synopsis
#include <wchar.h>
char *wcsrepl(wchar_t * InputString, wchar_t *StringToFind, wchar_t *Replacement, wchar_t *Output);

Description

The wcsrepl function replaces in InputString all occurrences of StringToFind by Replacement, writing the modified contents into the Output string. The original input string is not modified.

If the Output argument is NULL, wcsrepl will return the space that would be needed (including the terminating zero) for the replacement in wchar_t units.

If Replacement is NULL and Output is not NULL, all occurrences of StringToFind will be erased.

Returns

The wcsrepl function returns the needed length for the replacements if its Output argument is NULL. If not, it returns the number of replacements done.


wcspbrk

Function: wcspbrk

Synopsis
#include <wchar.h>
wchar_t *wcspbrk(const wchar_t *s1, const wchar_t *s2);

Description

The wcspbrk function locates the first occurrence in the wide string pointed to by s1 of any wide character from the wide string pointed to by s2.

Returns

The wcspbrk function returns a pointer to the wide character in s1, or a null pointer if no wide character from s2 occurs in s1.


wcsrchr

Function: wcsrchr

Synopsis
#include <wchar.h>
wchar_t *wcsrchr(const wchar_t *s, wchar_t c);

Description

The wcsrchr function locates the last occurrence of c in the wide string pointed to by s. The terminating null wide character is considered to be part of the wide string.

Returns

The wcsrchr function returns a pointer to the wide character, or a null pointer if c does not occur in the wide string.


wcsspn

Function: wcsspn

Synopsis
#include <wchar.h>
size_t wcsspn(const wchar_t *s1, const wchar_t *s2);

Description

The wcsspn function computes the length of the maximum initial segment of the wide string pointed to by s1 which consists entirely of wide characters from the wide string pointed to by s2.

Returns

The wcsspn function returns the length of the segment.


wcsstr

Function: wcsstr

Synopsis
#include <wchar.h>
wchar_t *wcsstr(const wchar_t *s1, const wchar_t *s2);

Description

The wcsstr function locates the first occurrence in the wide string pointed to by s1 of the sequence of wide characters (excluding the terminating null wide character) in the wide string pointed to by s2.

Returns

The wcsstr function returns a pointer to the located wide string, or a null pointer if the wide string is not found. If s2 points to a wide string with zero length, the function returns s1.


wcstok

Function: wcstok

Synopsis
#include <wchar.h>
wchar_t *wcstok(wchar_t * restrict s1, const wchar_t * restrict s2, wchar_t ** restrict ptr);

Description

A sequence of calls to the wcstok function breaks the wide string pointed to by s1 into a sequence of tokens, each of which is delimited by a wide character from the wide string pointed to by s2. The third argument points to a caller-provided wchar_t pointer into which the wcstok function stores information necessary for it to continue scanning the same wide string.

The first call in a sequence has a non-null first argument and stores an initial value in the object pointed to by ptr. Subsequent calls in the sequence have a null first argument and the object pointed to by ptr is required to have the value stored by the previous call in the sequence, which is then updated. The separator wide string pointed to by s2 may be different from call to call.

The first call in the sequence searches the wide string pointed to by s1 for the first wide character that is not contained in the current separator wide string pointed to by s2. If no such wide character is found, then there are no tokens in the wide string pointed to by s1 and the wcstok function returns a null pointer. If such a wide character is found, it is the start of the first token.

The wcstok function then searches from there for a wide character that is contained in the current separator wide string. If no such wide character is found, the current token extends to the end of the wide string pointed to by s1, and subsequent searches in the same wide string for a token return a null pointer. If such a wide character is found, it is overwritten by a null wide character, which terminates the current token.

In all cases, the wcstok function stores sufficient information in the pointer pointed to by ptr so that subsequent calls, with a null pointer for s1 and the unmodified pointer value for ptr, shall start searching just past the element overwritten by a null wide character (if any).

Returns

The wcstok function returns a pointer to the first wide character of a token, or a null pointer if there is no token.


wcstol

Function: wcstol wcstoul

Synopsis
#include <wchar.h>
long int wcstol(const wchar_t * restrict nptr,wchar_t ** restrict endptr,int base);
unsigned long int wcstoul(const wchar_t * restrict nptr, wchar_t ** restrict endptr,int base);

Description

The wcstol, and wcstoul functions convert the initial portion of the wide string pointed to by nptr to long int, or unsigned long int representation, respectively.

First, they decompose the input string into three parts: an initial, possibly empty, sequence of white-space wide characters (as specified by the iswspace function), a subject sequence resembling an integer represented in some radix determined by the value of base, and a final wide string of one or more unrecognized wide characters, including the terminating null wide character of the input wide string. Then, they attempt to convert the subject sequence to an integer, and return the result. If the value of base is zero, the expected form of the subject sequence is that of an integer constant preceded by a plus or minus sign, but not including an integer suffix. If the value of base is between 2 and 36 (inclusive), the expected form of the subject sequence is a sequence of letters and digits representing an integer with the radix specified by base, optionally preceded by a plus or minus sign, but not including an integer suffix

The letters from a (or A) through z (or Z) are ascribed the values 10 through 35; only letters and digits whose ascribed values are less than that of base are permitted. If the value of base is 16, the wide characters 0x or 0X may optionally precede the sequence if letters and digits, following the sign if present.

The subject sequence is defined as the longest initial subsequence of the input wide string, starting with the first non-white-space wide character, that is of the expected form. The subject sequence contains no wide characters if the input wide string is empty or consists entirely of white space, or if the first non-white-space wide character is other than a sign or a permissible letter or digit.

If the subject sequence has the expected form and the value of base is zero, the sequence of wide characters starting with the first digit is interpreted as an integer constant. If the subject sequence has the expected form and the value of base is between 2 and 36, it is used as the base for conversion, ascribing to each letter its value as given above. If the subject sequence begins with a minus sign, the value resulting from the conversion is negated (in the return type). A pointer to the final wide string is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

In other than the "C" locale, additional locale-specific subject sequence forms may be accepted.

If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

Returns

The wcstol, wcstoll, wcstoul, and wcstoull functions return the converted value, if any. If no conversion could be performed, zero is returned. If the correct value is outside the range of representable values, LONG_MIN, LONG_MAX, LLONG_MIN, LLONG_MAX, ULONG_MAX, or ULLONG_MAX is returned (according to the return type sign of the value, if any), and the value of the macro ERANGE is stored in errno.


wcstombs

Function: wcstombs

Synopsis
#include <stdlib.h>
size_t wcstombs(char * restrict s, const wchar_t * restrict pwcs, size_t n);

Description

The wcstombs function converts a sequence of codes that correspond to multibyte characters from the array pointed to by pwcs into a sequence of multibyte characters that begins in the initial shift state and stores these multibyte characters into the array pointed to by s, stopping if a multibyte character would exceed the limit of n total bytes or if a null character is stored. Each code is converted as if by a call to the wctomb function, except that the shift state of the wctomb function is not affected.

No more than 'n' bytes will be modified in the array pointed to by s. If copying takes place between objects that overlap, the behavior is undefined.

Returns

If a code is encountered that does not correspond to a valid multibyte character, the wcstombs function returns (size_t)-1. Otherwise, the wcstombs function returns the number of bytes modified, not including a terminating null character, if any.


wcsxfrm

Function: wcsxfrm

Synopsis
#include <wchar.h>
size_t wcsxfrm(wchar_t * restrict s1, const wchar_t * restrict s2, size_t n);

Description

The wcsxfrm function transforms the wide string pointed to by s2 and places the resulting wide string into the array pointed to by s1. The transformation is such that if the wcscmp function is applied to two transformed wide strings, it returns a value greater than, equal to, or less than zero, corresponding to the result of the wcscoll function applied to the same two original wide strings. No more than n wide characters are placed into the resulting array pointed to by s1, including the terminating null wide character. If n is zero, s1 is permitted to be a null pointer.

Returns

The wcsxfrm function returns the length of the transformed wide string (not including the terminating null wide character). If the value returned is n or greater, the contents of the array pointed to by s1 are indeterminate.

Example

The value of the following expression is the length of the array needed to hold the transformation of the wide string pointed to by s:

1 + wcsxfrm(NULL, s, 0)


wctomb

Function: wctomb

Synopsis
#include <stdlib.h>
int wctomb(char *s, wchar_t wchar);

Description

The wctomb function determines the number of bytes needed to represent the multibyte character corresponding to the code whose value is wchar (including any change in shift state). It stores the multibyte character representation in the array object pointed to by 's' (if s is not a null pointer). At most MB_CUR_MAX characters are stored. If the value of wchar is zero, the wctomb function is left in the initial shift state.

The implementation shall behave as if no library function calls the wctomb function.

Returns

If sis a null pointer, the wctomb function returns a nonzero or zero value, if multibyte character encodings, respectively, do or do not have state-dependent encodings. If s is not a null pointer, the wctomb function returns 1 if the value of wchar does not correspond to a valid multibyte character, or returns the number of bytes that are contained in the multibyte character corresponding to the value of wchar.

In no case will the value returned be greater than the value of the MB_CUR_MAX macro.


wtoi

Function: wtoi wtol

Synopsis
#include <io.h>
int wtoi(const wchar_t *string);

Description

The wtoi function converts a wide-character string to an integer value. wtol converts a wide-character string to a long integer value. The input string is a sequence of characters that can be interpreted as a numerical value of the specified type. The output value is affected by the setting of the LC_NUMERIC category of the current locale. The function stops reading the input string at the first character that it cannot recognize as part of a number.

Returns

Each function returns the int or long value produced by interpreting the input characters as a number. If the input cannot be converted to a value of the appropriate type, wtoi returns 0 and wtol returns 0L. The return value is undefined in case of overflow.


IO Funcs

LCC-Win32 IO Library Functions

_findclose | access | fscanf | printf xprintf
_findfirst | cgets | fseek | putc
_findnext | chdir | fsetpos | putchar
_fsopen | chmod | fstat | puts
_makepath | cputs | ftell | remove
inp inpw inpd | creat | fwrite | rename
_pipe | dup dup2 | getc | rewind
_rmtmp | eof | getchar | rmdir
_splitpath | fclose | getcwd | scanf
_stat | feof | getdcwd | setbuf
_tell | ferror | getdrive | setmode
_unlink | fflush | gets | setvbuf
_waccess | fgetc | inp inpw inpd | sopen
_wchmod | fgetpos | insline | sscanf
_wcreat | fgets | isatty | tempnam
_wfindfirst | fopen | kbhit | tmpfile
_wfindnext | fprintf xfprintf | lseek | tmpnam
_wmktemp | fputc | mktemp | ungetc
_wopen | fputchar | open | vfprintf
_wrename | fputs | open_osfhandle | vprintf
_wunlink | fread | putc | vscanf
 | freopen | pclose | write
 |  | popen |


_findclose

Function: _findclose

Synopsis
#include <io.h>
int _findclose( long handle );

Description

If successful, _findclose returns 0. Otherwise, it returns 1 and sets errno to ENOENT, indicating that no more matching files could be found.


_findfirst

Function: _findfirst

Synopsis
#include <io.h>
long _findfirst( char *filespec, struct _finddata_t *fileinfo );

Description

If successful, _findfirst returns a unique search handle identifying the file or group of files matching the filespec specification, which can be used in a subsequent call to _findnext, or to _findclose. Otherwise, _findfirst returns 1 and set errno to one of the following values:

ENOENT File specification that could not be matched

EINVAL Invalid filename specification


_findfirst

Function: findfiles

Synopsis
#include <io.h>
char ** findfiles( char *filespec,int flags=0);

Description

If successful, findfiles returns an array of character strings finished by a NULL containing the files that match the given filespec. Directory names will have a name that ends with the backslash ( \\ ) character.

If the given filespec is NULL, the specification "*.*" will be assumed. Otherwise, it should be an absolute path to some existing directory, followed by a possible ambiguous file specification. For instance: "c:\mydir\*.c" or "c:\*.obj". The directory part is optional. If it is absent, the current directory will be used.

Several specifications can be given for the same path. They should be separated by the character FINDFILES_SPECSEPARATOR, currently the '+' character. For instance to find all files that end in .c or .h, you would use: "*.c+*.h".

The optional flags argument can be any combination of the following:

FINDFILES_NODIRS | Ignores any directories. Default is to include directory names.
FINDFILES_ONLYDIRS | Only directories will be included in the result
FINDFILES_RECURSIVE | Recurse in sub-directories
FINDFILES_NOHIDDEN | Ignore hidden files

This flags can be combined with the OR operator.
The resulting character array should be freed with the free() function.

Returns:

A character array finished by a NULL pointer containing the names of the found files, or NULL if there wasn't enough memory to hold the data.

Library: Needs shlwapi.lib

Errors:

ENOMEM Not enough memory is avaliable for this operation.

Example:

#include <stdio.h>
#include <io.h>
/* this program
will print all the files using the file specification given.
For instance findfiles
c:\mydir\*.c will find all files with a .c extension */
int main(int argc,char *argv[])
{
char **flist = findfiles(argv[1]);
char **s = flist;

while (*s) {
printf("%s\n",*s);
s++;
}
free(flist);
}


_findnext

Function: _findnext

Synopsis
#include <io.h>
int _findnext( long handle, struct _finddata_t *fileinfo );

Description

If successful, _findnext returns 0. Otherwise, it returns 1 and set errno to ENOENT, indicating that no more matching files could be found.


fputchar

Function: _fputchar _fputwchar

Synopsis
#include <stdio.h>
int fputchar(int c);
#include <wchar.h>
int _fputwchar(wchar_t c);

Description

The _fputchar function writes the character specified by c (converted to an unsigned char) to the standard output stream.

The _fputwchar function writes the wide character specified by c to the standard output stream.

Returns

The _fputchar or _fputwchar function returns the character written. If a write error occurs, the error indicator for the stream is set and _fputchar returns EOF or WEOF.


_fsopen

Function: _fsopen fsopen

Synopsis
#include <stdio.h>
FILE *_fsopen(char *filename,char *mode, int shflag);

Description

This function opens a file with file sharing. Its arguments are the same as fopen, but augmented with the shflag, that can be one of:

_SH_COMPAT     Sets Compatibility mode for 16-bit applications

_SH_DENYNO     Permits read and write access

_SH_DENYRD     Denies read access to file

_SH_DENYRW     Denies read and write access to file

_SH_DENYWR     Denies write access to file

Returns

A pointer to the FILE structure or NULL, if the operation fails.

Portability

Windows


_makepath

Function: _makepath

Synopsis
#include <stdlib.h>
void _makepath(char *path,const char *drive, const char *dir, const char *fname, const char *ext);

Description

The makepath function creates a single path from its arguments and stores it in the path argument. The arguments are:

· drive: Contains a letter corresponding to the desired drive and an optional trailing colon. If null, no drive letter and colon appear in the result.

· dir: Contains the specification of a directory. The trailing path is optional, and both forward and backward slashes can be used.

· fname: Contains the file name without any path or drive components.

· ext: contains the extension without the period.

The result is stored in the path argument, that should be no longer than MAX_PATH, defined in stdlib.h

Returns

The _makepath function returns no value.

Portability

Windows


_outp

Function: _outp _outpw _outpd

Synopsis
#include <conio.h>
int _outp(unsigned short port, int databyte);
int _outpw(unsigned short port, int databyte);
int _outpd(unsigned short port, int databyte);

Description

The _outp function writes a byte to the specified output port. The port argument can be any unsigned integer in the range from 0 to 65535.

The _outpw function will output an unsigned short, and the _outpd function will output an unsigned long.

Returns

Returns the value written to the port.

Note that this functions will fail under windows NT.


_pipe

Function: _pipe

Synopsis
#include <io.h>
#include <fcntl.h>
int _pipe(int *phandles, unsigned int psize, int textmode);

Description

The _pipe function creates a pipe. A pipe is an I/O channel that a program uses to pass information to other programs. Is similar to a file in that it has a file pointer, a file descriptor, or both, and can be read from or written to using the standard library's input and output functions. However, a pipe does not represent a specific file or device. Instead, it represents temporary storage in memory that is independent of the programs own memory and is controlled entirely by the operating system.

_pipe is similar to _open but opens the pipe for reading and writing, returning two file handles instead of one. The program can use both sides of the pipe or close the one it does not need. For example, the command processor creates a pipe when executing a command such as

type myfile | grep someword

The standard output handle of the type program is attached to the pipes write handle. The standard input handle of grep is attached to the pipes read handle. This eliminates the need for creating temporary files to pass information to other programs.

The _pipe function returns two handles to the pipe in the phandles argument. The element phandles[0] contains the read handle, and the element phandles[1] contains the write handle. Pipe file handles are used in the same way as other file handles. (The low-level input and output functions _read and _write can read from and write to a pipe.) To detect the end-of-pipe condition, check for a _read request that returns 0 as the number of bytes read.

The psize argument specifies the amount of memory, in bytes, to reserve for the pipe. The textmode argument specifies the translation mode for the pipe. The manifest constant _O_TEXT specifies a text translation, and the constant _O_BINARY specifies binary translation. If the textmode argument is 0, _pipe uses the default translation mode specified by the default-mode variable _fmode.

In multithreaded programs, no locking is performed. The handles returned are newly opened and should not be referenced by any thread until after the _pipe call is complete.

In Windows NT and Windows 95, a pipe is destroyed when all of its handles have been closed. (If all read handles on the pipe have been closed, writing to the pipe causes an error.) All read and write operations on the pipe wait until there is enough data or enough buffer space to complete the I/O request

Returns

Returns 0 if successful. It returns 1 to indicate an error, in which case errno is set to one of two values: EMFILE, which indicates no more file handles available, or ENFILE, which indicates a system file table overflow.


_rmtmp

Function: _rmtmp

Synopsis:

#include <stdio.h>
int _rmtmp(void);

Description

Removes all temporary files created by the program. This function is not a standard ANSI C function.

Returns

Returns the number of temporary files deleted

Example
#include <stdio.h>
int main( void )
{
    FILE *stream;
    int i;
    /* Create temporary files. */
    for( i = 1; i <= 4; i++ )
    {
        if( (stream = tmpfile()) == NULL ) {
            perror( "Could not open new temporary file\n" );
            break;
        }
        else
            printf( "Temporary file %d was created\n", i );
    }
    /* Remove temporary files. */
    printf( "%d temporary files deleted\n", _rmtmp() );
}


_splitpath

Function: _splitpath

Synopsis
<include <stdlib.h>
void _splitpath( const char *path, char *drive, char *dir, char *fname, char *ext );

This function does NOT belong to the ANSI C library.

Description

The _splitpath function breaks a path into its four components. _splitpath automatically handles multibyte-character string arguments as appropriate, recognizing multibyte-character sequences according to the multibyte code page currently in use.

Each argument is stored in a buffer; the manifest constants _MAX_DRIVE, _MAX_DIR, _MAX_FNAME, and _MAX_EXT (defined in STDLIB.H) specify the maximum size necessary for each buffer. The other arguments point to buffers used to store the path elements. After a call to _splitpath is executed, these arguments contain empty strings for components not found in path. You can pass a NULL pointer to _splitpath for any component you dont need.

Returns

This function returns no value.


stat

Function: _stat

Synopsis
#include <sys/types.h>
#include <sys/stat.h>
int _stat( const char *path, struct _stat *buffer );

Description

The _stat function obtains information about the file or directory specified by path and stores it in the structure pointed to by buffer. _stat automatically handles multibyte-character string arguments as appropriate, recognizing multibyte-character sequences according to the multibyte code page currently in use.

The _stat structure, defined in SYS\STAT.H, includes the following fields.

gid | Numeric identifier of group that owns file. Not used under windows
st_atime | Time of last access of file.
st_ctime | Time of creation of file.
st_dev | Drive number of the disk containing the file (same as st_rdev).
st_ino | Not used under windows
st_mode | Bit mask for file-mode information. The _S_IFDIR bit is set if path specifies a directory; the _S_IFREG bit is set if path specifies an ordinary file or a device. User read/write bits are set according to the files permission mode; user execute bits are set according to the filename extension.
st_mtime | Time of last modification of file.
st_nlink | Always 1 on non-NTFS file systems.
st_rdev | Drive number of the disk containing the file (same as st_dev).
st_size | Size of the file in bytes; a 64-bit integer for _stati64 and _wstati64
uid | Not used under windows

If path refers to a device, the size, time, _dev, and _rdev fields in the _stat structure are meaningless. Because STAT.H uses the _dev_t type that is defined in TYPES.H, you must include TYPES.H before STAT.H in your code.

Returns

Each of these functions returns 0 if the file-status information is obtained. A return value of 1 indicates an error, in which case errno is set to ENOENT, indicating that the filename or path could not be found.


_tell

Function: _tell _telli64

Synopsis
#include <io.h>
long _tell(int handle);
long long _telli64(int handle);

Description

The _tell function gets the current position of the file pointer (if any) associated with the handle argument. The position is expressed as the number of bytes from the beginning of the file. For the _telli64 function, this value is expressed as a 64-bit integer.


_unlink

Function: _unlink

Synopsis

#include <stdio.h>
int _unlink(const char *filename);

Description

_unlink deletes a file specified by filename. Any drive, path, and file name can be used as a filename. Wildcards are not allowed.

Read-only files cannot be deleted by this call. If your file has read-only attribute use chmod to change it.

Note: If your file is open, be sure to close it before unlinking it.

Return Value

On success, unlink returns 0.

On error, it returns -1 and sets the global variable errno to one of the following values:

EACCES Permission denied

ENOENT Path or file name not found


_waccess

Function: _waccess

Synopsis
#include <io.h>
int _waccess(const unsigned short *, int);

Description

The parameters of this function are:

path File or directory path

mode Permission setting

Each of these functions returns 0 if the file has the given mode. The function returns 1 if the named file does not exist or is not accessible in the given mode; in this case, errno is set as follows:

EACCES Access denied: files permission setting does not allow specified access.

ENOENT Filename or path not found.

The mode parameter can have the following values:

1) Zero: Meaning testing for existence only

2) 2: Meaning testing for write access

3) 4: Meaning testing for read access

4) 6: Meaning testing for read/write access


_wchmod

Function: _wchmod

Synopsis

#include <io.h>
int _wchmod(const unsigned short *path, int amode);

Description

Changes file access mode.

_wchmod sets the file-access permissions of the file given by path according to the mask given by amode. path points to a wide string.

amode can contain one or both of the symbolic constants S_IWRITE and S_IREAD (defined in sys\stat.h).

Value of amode Access permission

S_IWRITE Permission to write

S_IREAD Permission to read

S_IREAD | S_IWRITE Permission to read and write (write permission implies read permission)

Return Value

Upon successfully changing the file access mode, _wchmod returns 0. Otherwise, _wchmod returns a value of -1.

In the event of an error, the global variable errno is set to one of the following values:

EACCES Permission denied

ENOENT Path or file name not found


_wcreat

Function: _wcreat

Synopsis

#include <io.h>
int _wcreat(const unsigned short *path, int amode);

Description

Creates a new file or overwrites an existing one.

Note: Remember that a backslash in a path requires '\\'.

_wcreat creates a new file or prepares to rewrite an existing file given by path. amode applies only to newly created files.

A file created with _wcreat is always created in the translation mode specified by the global variable _fmode (O_TEXT or O_BINARY).

If the file exists and the write attribute is set, _wcreat truncates the file to a length of 0 bytes, leaving the file attributes unchanged. If the existing file has the read-only attribute set, the _wcreat call fails and the file remains unchanged.

The _wcreat call examines only the S_IWRITE bit of the access-mode word amode. If that bit is 1, the file can be written to. If the bit is 0, the file is marked as read-only. All other operating system attributes are set to 0.

amode can be one of the following (defined in sys\stat.h):

Value of amode Access permission

S_IWRITE Permission to write

S_IREAD Permission to read

S_IREAD / S_IWRITE Permission to read and write (write permission implies read permission)

Return Value

Upon successful completion, _wcreat returns the new file handle, a nonnegative integer; otherwise, it returns -1.

In the event of error, the global variable errno is set to one of the following:

EACCES Permission denied

ENOENT Path or file name not found

EMFILE Too many open files


_wfindfirst

Function: _wfindfirst

Synopsis
#include <io.h>
long _wfindfirst( unsigned short *filespec, struct _finddata_t *fileinfo );

Description

If successful, _wfindfirst returns a unique search handle identifying the file or group of files matching the filespec specification, which can be used in a subsequent call to _wfindnext, or to _wfindclose. Otherwise, _wfindfirst returns 1 and set errno to one of the following values:

ENOENT File specification that could not be matched

EINVAL Invalid filename specification


_wfindnext

Function: _wfindnext

Synopsis
#include <io.h>
int _wfindnext( long handle, struct _finddata_t *fileinfo );

Description

If successful, _wfindnext returns 0. Otherwise, they return 1 and set errno to ENOENT, indicating that no more matching files could be found.


_wmktemp

Function: _wmktemp

Synopsis

#include <io.h>
unsigned short *_wmktemp(unsigned short *template);

Description

Makes a unique file name.

_wmktemp replaces the string pointed to by template with a unique file name and returns template.

template should be a null-terminated string with six trailing Xs. These Xs are replaced with a unique collection of letters plus a period, so that there are two letters, a period, and three suffix letters in the new file name.

Starting with AA.AAA, the new file name is assigned by looking up the name on the disk and avoiding pre-existing names of the same format.

Return Value

If template is well-formed, _wmktemp returns the address of the template string. Otherwise, it returns null.


_wopen

Function: _wopen

Synopsis
#include <io.h>
int _wopen(const unsigned short *filename, int oflag,[int pmode]);

Description

The _wopen function returns a file handle for the opened file. A return value of 1 indicates an error, in which case errno is set to one of the following values:

EACCES | Tried to open read-only file for writing, or files sharing mode does not allow specified operations, or given path is directory
EEXIST | _O_CREAT and _O_EXCL flags specified, but filename already exists
EINVAL | Invalid oflag or pmode argument
EMFILE | No more file handles available (too many open files)
ENOENT | File or path not found

oflag is an integer expression formed from one or more of the following manifest constants or constant combinations defined in FCNTL.H:

_O_APPEND | Moves file pointer to end of file before every write operation.
_O_BINARY | Opens file in binary (untranslated) mode. (See fopen for a description of binary mode.)
_O_CREAT | Creates and opens new file for writing. Has no effect if file specified by filename exists. pmode argument is required when _O_CREAT is specified.
_O_CREAT | _O_SHORT_LIVED | Create file as temporary and if possible do not flush to disk. pmode argument is required when _O_CREAT is specified.
_O_CREAT | _O_TEMPORARY | Create file as temporary; file is deleted when last file handle is closed. pmode argument is required when _O_CREAT is specified.
_O_CREAT | _O_EXCL | Returns error value if file specified by filename exists. Applies only when used with _O_CREAT.
_O_RANDOM | Specifies primarily random access from disk
_O_RDONLY | Opens file for reading only;
_O_RDWR | Opens file for both reading and writing;
_O_SEQUENTIAL | Specifies primarily sequential access from disk
_O_TEXT | Opens file in text (translated) mode.
_O_TRUNC | Opens file and truncates it to zero length; file must have write permission. Used with _O_CREAT opens an existing file or creates a new file.
_O_WRONLY | Opens file for writing only;

The pmode argument is required only when _O_CREAT is specified. If the file already exists, pmode is ignored. Otherwise, pmode specifies the file permission settings, which are set when the new file is closed the first time. _wopen applies the current file-permission mask to pmode before setting the permissions (for more information, see _umask). pmode is an integer expression containing one or both of the following manifest constants, defined in SYS\STAT.H:

_S_IREAD | Reading only permitted
_S_IWRITE | Writing permitted (effectively permits reading and writing)
_S_IREAD | _S_IWRITE | Reading and writing permitted

When both constants are given, they are joined with the bitwise-OR operator ( | ). In Windows NT, all files are readable, so write-only permission is not available; thus the modes _S_IWRITE and _S_IREAD | _S_IWRITE are equivalent.

Returns

An integer representing a handle to the open file, or -1 if the operation fails.


_wrename

Function: _wrename

Synopsis
#include <stdio.h>
int _wrename(const unsigned short *old, const unsigned short *new);

Description

The _wrename function causes the file whose name is the string pointed to by old to be henceforth known by the name given by the string pointed to by new. The file named old is no longer accessible by that name. If a file named by the string pointed to by new exists prior to the call to the rename function, the behavior is implementation-defined.

Returns

The _wrename function returns zero if the operation succeeds, nonzero if it fails in which case if the file existed previously it is still known by its original name.


_wunlink

Function: _wunlink

Synopsis

#include <io.h>
int _wunlink(const unsigned short *filename);

Description

_wunlink deletes a file specified by filename. Any drive, path, and file name can be used as a filename. Wildcards are not allowed.

Read-only files cannot be deleted by this call. If your file has read-only attribute use _wchmod to change it.

Note: If your file is open, be sure to close it before unlinking it.

Return Value

On success, unlink returns 0.

On error, it returns -1 and sets the global variable errno to one of the following values:

EACCES Permission denied

ENOENT Path or file name not found


access

Function: access

Synopsis
#include <io.h>
int access( const char *path, int mode );
int _access( const char *path, int mode );

Description

The parameters of this function are:

path File or directory path

mode Permission setting

Each of these functions returns 0 if the file has the given mode. The function returns -1 if the named file does not exist or is not accessible in the given mode; in this case, errno is set as follows:

EACCES Access denied: files permission setting does not allow specified access.

ENOENT Filename or path not found.

The mode parameter can have the following values:

1) Zero: Meaning testing for existence only

2) 2: Meaning testing for write access

3) 4: Meaning testing for read access

4) 6: Meaning testing for read/write access


cgets

Function: cgets _cgets

Synopsis
#include <conio.h>
char *cgets(char *buffer);

Description

The _cgets function reads a string of characters from the console and stores the string and its length in the location pointed to by buffer.

The buffer parameter must be a pointer to a character array. The first element of the array, buffer[0], must contain the maximum length (in characters) of the string to be read. The array must contain enough elements to hold the string, a terminating null character ('0'), and two additional bytes.

The function reads characters until a carriage return linefeed (CR-LF) combination or the specified number of characters is read.

The string is stored starting at buffer[2]. If the function reads a CR-LF, it stores the null character ('0'). _cgets then stores the actual length of the string in the second array element, buffer [1]. Because all editing keys are active when _cgets is called, pressing F3 repeats the last entry.


chdir

Function: chdir

Synopsis
#include <direct.h>
int chdir(const char *dirname);

Description

The chdir function changes the current directory to the specified one, that must exist.

Returns

The chdir function returns 0 if successful, -1 otherwise

Portability

Windows

Note that lcc-win32 accepts both _chdir and chdir.


cputs

Function: cputs

Synopsis
#include <conio.h>
int cputs(char *string);

Description

The cputs function prints the given character string at the console. The string should be zero terminated.

Returns

If successful, returns zero.. If an error occurs it returns -1


dup

Function: dup

Synopsis
#include <io.h>
int dup(int handle);
int dup2(int handle1,int handle2);

Description

The _dup and _dup2 functions associate a second file handle with a currently open file. These functions can be used to associate a predefined file handle, such as that for stdout, with a different file. Operations on the file can be carried out using either file handle. The type of access allowed for the file is unaffected by the creation of a new handle. _dup returns the next available file handle for the given file.

_dup2 forces handle2 to refer to the same file as handle1. If handle2 is associated with an open file at the time of the call, that file is closed.

Both _dup and _dup2 accept file handles as parameters. To pass a stream (FILE *) to either of these functions, use _fileno. The fileno routine returns the file handle currently associated with the given stream. The following example shows how to associate stderr (defined as FILE * in STDIO.H) with a handle:

ccstderr = _dup( _fileno( stderr ));

Returns

_dup returns the new file handle, _dup2 returns zero to indicate success. Otherwise it returns -1.


eof

Function: eof

Synopsis
#include <io.h>
int eof(int handle);

Description

This function tests whether the file represented by its handle argument has reached the end of the file or not.

Returns

Returns 0 if the end of file hasn’t been reached, 1 if the handle is at EOF, -1 if there is an error.

Portability

Windows. Under Unix a similar function exists for the TCL library, but not for the C library.


fclose

Function: fclose

Synopsis
#include <stdio.h>
int fclose(FILE *stream);

Description

The fclose function causes the stream pointed to by stream to be flushed and the associated file to be closed. Any unwritten buffered data for the stream are delivered to the host environment to be written to the file; any unread buffered data are discarded. The stream is disassociated from the file. If the associated buffer was automatically allocated, it is deallocated.

Returns

The fclose function returns zero if the stream was successfully closed, or EOF if any errors were detected.


feof

Function: feof

Synopsis
#include <stdio.h>
int feof(FILE *stream);

Description

The feof function tests the end-of-file indicator for the stream pointed to by stream.

Returns

The feof function returns nonzero if and only if the end-of-file indicator is set for stream.


ferror

Function: ferror

Synopsis
#include <stdio.h>
int ferror(FILE *stream);

Description

The ferror function tests the error indicator for the stream pointed to by stream.

Returns

The ferror function returns nonzero if and only if the error indicator is set for stream.


fflush

Function: fflush

Synopsis
#include <stdio.h>
int fflush(FILE *stream);

Description

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

If stream is a null pointer, the fflush function performs this flushing action on all streams for which the behavior is defined above.

Returns

The fflush function sets the error indicator for the stream and returns EOF if a write error occurs, otherwise it returns zero.

Example
#include <stdio.h>
#include <conio.h>
int main( void )
{
    int integer;
    char string[81];
    /* Read each word as a string. */
    printf( "Enter a sentence of 3 words with scanf: " );
    for( integer = 0; integer < 3; integer++ )
    {
        scanf( "%s", string );
        printf( "%s", string );
    }
    /* You must flush the input buffer before using gets. */
    fflush( stdin );
    printf( "Enter the same sentence with gets: " );
    gets( string );
    printf( "%s", string );
}

Enter a sentence of 3 words with scanf: hello my world

hello
my
world

Enter the same sentence with gets: hello my world

hello my world


fgetc

Function: fgetc

Synopsis
#include <stdio.h>
int fgetc(FILE *stream);

Description

If a next character is present from the input stream pointed to by stream, the fgetc function obtains that character as an unsigned char converted to an int and advances the associated file position indicator for the stream (if defined).

Returns

The fgetc function returns the next character from the input stream pointed to by stream. If the stream is at end-of-file, the end-of-file indicator for the stream is set and fgetc returns EOF. If a read error occurs, the error indicator for the stream is set and fgetc returns EOF.


fgetpos

Function: fgetpos

Synopsis
#include <stdio.h>
int fgetpos(FILE * restrict stream, fpos_t * restrict pos);

Description

The fgetpos function stores the current values of the parse state (if any) and file position indicator for the stream pointed to by stream in the object pointed to by pos.

The values stored contain unspecified information usable by the fsetpos function for repositioning the stream to its position at the time of the call to the fgetpos function.

Returns

If successful, the fgetpos function returns zero; on failure, the fgetpos function returns nonzero and stores an implementation-defined positive value in errno. For lcc-win32, this values are:

· EBADF Bad file handle

· EINVAL The pos value is invalid


fgets

Function: fgets

Synopsis
#include <stdio.h>
char *fgets(char * restrict s, int n, FILE * restrict stream);

Description

The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

Returns

The fgets function returns s if successful. If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned. If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned.


fopen

Function: fopen

Synopsis
#include <stdio.h>
FILE *fopen(const char * filename,const char * mode);

Description

The fopen function opens the file whose name is the string pointed to by filename, and associates a stream with it. The argument mode points to a string. If the string is one of the following, the file is open in the indicated mode. Otherwise, the behavior is undefined.

r      open text file for reading

w      truncate to zero length or create text file for writing

a      append; open or create text file for writing at end-of-file

rb     open binary file for reading

wb     truncate to zero length or create binary file for writing

ab     append; open or create binary file for writing at end-of-file

r+     open text file for update (reading and writing)

w+     truncate to zero length or create text file for update

a+     append; open or create text file for update, writing at end-of-file

r+b    open binary file for update (reading and writing)

rb+    open binary file for update (reading and writing)

w+b    truncate to zero length or create binary file for update

wb+    truncate to zero length or create binary file for update

a+b    append; open or create binary file for update, writing at end-of-file

ab+    append; open or create binary file for update, writing at end-of-file

Opening a file with read mode (r as the first character in the mode argument) fails if the file does not exist or cannot be read.

Opening a file with append mode (a as the first character in the mode argument) causes all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to the fseek function.

In some implementations, opening a binary file with append mode (b as the second or third character in the above list of mode argument values) may initially position the file position indicator for the stream beyond the last data written, because of null character padding.

When a file is opened with update mode (+ as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of- file.

Opening (or creating) a text file with update mode may instead open (or create) a binary stream in some implementations.

When opened, a stream is fully buffered if and only if it can be determined not to refer to an interactive device. The error and end-of-file indicators for the stream are cleared.

Returns

The fopen function returns a pointer to the object controlling the stream. If the open operation fails, fopen returns a null pointer.


fprintf

Function: fprintf

Synopsis
#include <stdio.h>
int fprintf(FILE * stream, const char * format, ...);

Description

The fprintf function writes output to the stream pointed to by stream, under control of the string pointed to by format that specifies how subsequent arguments are converted for output.

For the details of the format see printf


fputc

Function: fputc fputcw

Synopsis
#include <stdio.h>
int fputc(int c, FILE *stream);
int fputwc(int c, FILE *stream);

Description

The fputc function writes the character specified by c (converted to an unsigned char) to the output stream pointed to by stream, at the position indicated by the associated file position indicator for the stream (if defined), and advances the indicator appropriately. If the file cannot support positioning requests, or if the stream was opened with append mode, the character is appended to the output stream.

The fputwc function is the wide character counterpart of fputc.

Returns

The fputc function returns the character written. If a write error occurs, the error indicator for the stream is set and fputc returns EOF or WEOF.


fputs

Function: fputs

Synopsis
#include <stdio.h>
int fputs(const char * restrict s, FILE * restrict stream);

Description

The fputs function writes the string pointed to by s to the stream pointed to by stream. The terminating null character is not written.

Returns

The fputs function returns EOF if a write error occurs; otherwise it returns a nonnegative value.


fread

Function: fread

Synopsis
#include <stdio.h>
size_t fread(void * restrict ptr,size_t size, size_t nmemb,FILE * restrict stream);

Description

The fread function reads, into the array pointed to by ptr, up to nmemb elements whose size is specified by size, from the stream pointed to by stream. The file position indicator for the stream (if defined) is advanced by the number of characters successfully read. If an error occurs, the resulting value of the file position indicator for the stream is indeterminate. If a partial element is read, its value is indeterminate.

Returns

The fread function returns the number of elements successfully read, which may be less than nmemb if a read error or end-of-file is encountered. If size or nmemb is zero, fread returns zero and the contents of the array and the state of the stream remain unchanged.


freopen

Function: freopen

Synopsis
#include <stdio.h>
FILE *freopen(const char * filename, const char * mode, FILE * restrict stream);

Description

The freopen function opens the file whose name is the string pointed to by filename and associates the stream pointed to by stream with it. The mode argument is used just as in the fopen function.

The primary use of the freopen function is to change the file associated with a standard text stream (stderr, stdin, or stdout), as those identifiers need not be modifiable lvalues to which the value returned by the fopen function may be assigned. This is not the case in lcc-win32. The standard file descriptors stdin, stdout and stderr are lvalues and can be modified.

If filename is a null pointer, the freopen function attempts to change the mode of the stream to that specified by mode, as if the name of the file currently associated with the stream had been used. It is implementation-defined which changes of mode are permitted (if any), and under what circumstances.

The freopen function first attempts to close any file that is associated with the specified stream. Failure to close the file is ignored. The error and end-of-file indicators for the stream are cleared.

Returns

The freopen function returns a null pointer if the open operation fails. Otherwise, freopen returns the value of stream.


fscanf

Function: fscanf

Synopsis
#include <stdio.h>
int fscanf(FILE * restrict stream,const char * restrict format, ...);
int xfscanf(FILE * restrict stream,const char * restrict format, ...);

Description

The fscanf function reads input from the stream pointed to by stream, under control of the string pointed to by format that specifies the admissible input sequences and how they are to be converted for assignment, using subsequent arguments as pointers to the objects to receive the converted input. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored.

This function is in the native windows C runtime. It does not support long long or long double arguments.

The xfscanf function is the lcc-win32 version of fscanf that supports long long and long double data. It is based on the trio package.

The format is a multibyte character sequence, beginning and ending in its initial shift state. The format is composed of zero or more directives: one or more white-space characters, an ordinary multibyte character (neither % nor a white-space character), or a conversion specification. Each conversion specification is introduced by the character %.

After the %, the following appear in sequence:

· An optional assignment-suppressing character *.

· An optional nonzero decimal integer that specifies the maximum field width (in characters).

· An optional length modifier that specifies the size of the receiving object.

· A conversion specifier character that specifies the type of conversion to be applied.

The fscanf function executes each directive of the format in turn. If a directive fails, as detailed below, the function returns. Failures are described as input failures (due to the occurrence of an encoding error or the unavailability of input characters), or matching failures (due to inappropriate input).

A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read.

A directive that is an ordinary multibyte character is executed by reading the next characters of the stream. If any of those characters differ from the ones composing the directive, the directive fails and the differing and subsequent characters remain unread.

A directive that is a conversion specification defines a set of matching input sequences, as described below for each specifier. A conversion specification is executed in the

following steps:

Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or nspecifier.225)

An input item is read from the stream, unless the specification includes an n specifier. An input item is defined as the longest sequence of input characters which does not exceed any specified field width and which is, or is a prefix of, a matching input sequence. The first character, if any, after the input item remains unread. If the length of the input item is zero, the execution of the directive fails; this condition is a matching failure unless end-of- file, an encoding error, or a read error prevented input from the stream, in which case it is an input failure.

Except in the case of a % specifier, the input item (or, in the case of a %n directive, the count of input characters) is converted to a type appropriate to the conversion specifier. If the input item is not a matching sequence, the execution of the directive fails: this condition is a matching failure. Unless assignment suppression was indicated by a *, the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result. If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.

The length modifiers and their meanings are the same as those of fprintf.

Returns

The fscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.


fseek

Function: fseek

Synopsis
#include <stdio.h>
int fseek(FILE *stream, long int offset, int whence);

Description

The fseek function sets the file position indicator for the stream pointed to by stream. If a read or write error occurs, the error indicator for the stream is set and fseek fails. For a binary stream, the new position, measured in characters from the beginning of the file, is obtained by adding offset to the position specified by whence.

The specified position is the beginning of the file if whence is SEEK_SET, the current value of the file position indicator if SEEK_CUR, or end-of-file if SEEK_END. A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END. For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.

After determining the new position, a successful call to the fseek function undoes any effects of the ungetc function on the stream, clears the end-of-file indicator for the stream, and then establishes the new position. After a successful fseek call, the next operation on an update stream may be either input or output.

Returns

The fseek function returns nonzero only for a request that cannot be satisfied.


fsetpos

Function: fsetpos

Synopsis
#include <stdio.h>
int fsetpos(FILE *stream, const fpos_t *pos);

Description

The fsetpos function sets the mbstate_t object (if any) and file position indicator for the stream pointed to by stream according to the value of the object pointed to by pos, which shall be a value obtained from an earlier successful call to the fgetpos function on a stream associated with the same file. If a read or write error occurs, the error indicator for the stream is set and fsetpos fails.

A successful call to the fsetpos function undoes any effects of the ungetc function on the stream, clears the end-of-file indicator for the stream, and then establishes the new parse state and position. After a successful fsetpos call, the next operation on an update stream may be either input or output.

Returns

If successful, the fsetpos function returns zero; on failure, the fsetpos function returns nonzero and stores an implementation-defined positive value in errno.

Lcc-win32/windows sets EINVAL (bad value of stream) or EBADF (invalid file handle)


fstat

Function: fstat

Synopsis
#include <sys\stat.h>
int fstat(int handle, struct _stat *buffer);

Description

This function retrieves different information for the indicated file, pointed by the handle argument, and puts it in the indicated buffer, that points to a structure of type _stat.

The fields of this structure indicate:

st_atime     Time of last file access.

st_ctime     Time of creation of file.

st_dev       If a device, handle; otherwise 0.

st_mode      Bit mask for file-mode information. The _S_IFCHR
           bit is set if handle refers to a device. The _S_IFREG
           bit is set if handle refers to an ordinary file. The
           read/write bits are set according to the file’s
           permission mode. _S_IFCHR and other constants are
           defined in SYS.H.

st_mtime     Time of last modification of file.

st_nlink     Always 1 on non-NTFS file systems.

st_rdev      If a device, handle; otherwise 0.

st_size      Size of the file in bytes.

Returns

Zero if succesful, -1 on error. In the later case errno is set to EBADF : bad file handle.


ftell

Function: ftell

Synopsis
#include <stdio.h>
long int ftell(FILE *stream);

Description

The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

Returns

If successful, the ftell function returns the current value of the file position indicator for the stream. On failure, the ftell function returns 1L and stores an implementation-defined positive value in errno.

Lcc-win32 sets EINVAL (bad value of stream) or EBADF (invalid file handle).


fwrite

Function: fwrite

Synopsis
#include <stdio.h>
size_t fwrite(const void * restrict ptr,size_t size, size_t nmemb,FILE * restrict stream);

Description

The fwrite function writes, from the array pointed to by ptr,up to nmemb elements whose size is specified by size, to the stream pointed to by stream. The file position indicator for the stream (if defined) is advanced by the number of characters successfully written. If an error occurs, the resulting value of the file position indicator for the stream is indeterminate.

Returns

The fwrite function returns the number of elements successfully written, which will be less than nmemb only if a write error is encountered.


getc

Function: getc

Synopsis
#include <stdio.h>
int getc(FILE *stream);

Description

The getc function is equivalent to fgetc, except that if it is implemented as a macro, it may evaluate stream more than once, so the argument should never be an expression with side effects.

Returns

The getc function returns the next character from the input stream pointed to by stream. If the stream is at end-of-file, the end-of-file indicator for the stream is set and getc returns EOF. If a read error occurs, the error indicator for the stream is set and getc returns EOF.


getchar

Function: getchar

Synopsis
#include <stdio.h>
int getchar(void);

Description

The getchar function is equivalent to getc with the argument stdin.

Returns

The getchar function returns the next character from the input stream pointed to by stdin. If the stream is at end-of-file, the end-of-file indicator for the stream is set and getchar returns EOF. If a read error occurs, the error indicator for the stream is set and getchar returns EOF.


getcwd

Function: getcwd wgetcwd

Synopsis
#include <direct.h>
char *getcwd(char *buffer,int maxlen);

Description

The getcwd function gets the full path of the current working directory for the default drive and stores it at the given buffer.

The integer argument maxlen specifies the maximum length for the path. An error occurs if the length of the path (including the terminating null character) exceeds maxlen. The buffer argument can be NULL; a buffer of at least size maxlen (more only if necessary) will automatically be allocated, using malloc, to store the path. This buffer can later be freed by calling free and passing it the getcwd return value (a pointer to the allocated buffer).

Returns

Each of these functions returns a pointer to buffer. A NULL return value indicates an error, and errno is set either to ENOMEM, indicating that there is insufficient memory to allocate maxlen bytes (when a NULL argument is given as buffer), or to ERANGE, indicating that the path is longer than maxlen characters.


getdcwd

Function: getdcwd

Synopsis
#include <direct.h>
char *getdcwd(int drive, char *buffer,int maxlen);

Description

The getdcwd function writes the current working directory for the specified drive to the buffer indicated by buffer, without exceeding maxlen chars. If buffer is NULL, a freshly allocated buffer is returned using malloc.

If the current working directory is the root, the string ends with a backslash (. If the current working directory is a directory other than the root, the string ends with the directory name and not with a backslash.

The drive argument can be zero (current drive), 1 (drive A) 2, (drive B), 3 (drive C) etc.

Returns

Returns a pointer to the given buffer.

Portability

Windows. (There is no drive concept under Unix)


getdrive

Function: getdrive

Synopsis
#include <stdio.h>
int getdrive(void);

Description

The getdrive function returns an integer representing the current drive : 1 for the A drive, 2 for the B drive, 3 for the C drive, etc.

Returns

Returns the number of the current drive

Portability

Windows


gets

Function: gets

Synopsis
#include <stdio.h>
char *gets(char *s);

Description

The gets function reads characters from the input stream pointed to by stdin, into the array pointed to by s, until end-of-file is encountered or a new-line character is read. Any new-line character is discarded, and a null character is written immediately after the last character read into the array.

Returns

The gets function returns s if successful. If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned. If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned.


inp

Function: inp inpw inpd

Synopsis
#include <conio.h>
int inp( unsigned short port );
unsigned short inpw( unsigned short port );
unsigned long inpd( unsigned short port );

Description

The functions return the byte, word, or double word read from port. There is no error return. The inp, inpw, and inpd functions read a byte, a word, and a double word, respectively, from the specified input port. The input value can be any unsigned short integer in the range 0 - 65,535.

Note: This functions use a privileged instruction (in) and will fail with an exception under windows NT.


insline

Function: insline

Synopsis
#include <conio.h>
void insline(void);

link with tcconio.lib

Description

Inserts a line at the current text cursor position, moving down all other lines of text.


isatty

Function: isatty

Synopsis
#include <io.h>
int isatty(int handle);

Description

This function tests whether the given file handle is a character device (a console, a printer or a serial port).

Returns

Non zero if the file handle is associated with a character device, zero otherwise.

Portability

Windows UNIX


kbhit

Function: kbhit

Synopsis
#include <conio.h>
int kbhit(void);

Description

This routine returns non zero if a key has been pressed, zero otherwise.

Returns

Non zero: Keyboard has been hit, zero, the user didn't touch the keyboard.

Portability

Strictly windows function.


lseek

Function: lseek

Synopsis
#include <io.h>
long lseek(int handle, long offset, int origin);

Description

lseek returns the offset, in bytes, of the new position from the beginning of the file. The function returns -1L to indicate an error and sets errno either to EBADF, meaning the file handle is invalid, or to EINVAL, meaning the value for origin is invalid or the position specified by offset is before the beginning of the file. On devices incapable of seeking (such as terminals and printers), the return value is undefined.

The handle parameter refers to an open file.

The offset parameter indicates the number of bytes from the origin.

The origin parameter is one of: SEEK_SET (0) for using the beginning of the file as the origin, SEEK_CUR (1) for using the current position as the origin, or SEEK_END (2), for using the end of the file as the origin.


open

Function: open

Synopsis
#include <io.h>
int open(const char *filename, int oflag,[int pmode]);

Description

The open function returns a file handle for the opened file. A return value of -1 indicates an error, in which case errno is set to one of the following values:

EACCES | Tried to open read-only file for writing, or files sharing mode does not allow specified operations, or given path is directory
EEXIST | _O_CREAT and _O_EXCL flags specified, but filename already exists
EINVAL | Invalid oflag or pmode argument
EMFILE | No more file handles available (too many open files)
ENOENT | File or path not found

oflag is an integer expression formed from one or more of the following manifest constants or constant combinations defined in FCNTL.H:

_O_APPEND | Moves file pointer to end of file before every write operation.
_O_BINARY | Opens file in binary (untranslated) mode. (See fopen for a description of binary mode.)
_O_CREAT | Creates and opens new file for writing. Has no effect if file specified by filename exists. pmode argument is required when _O_CREAT is specified.
_O_CREAT | _O_SHORT_LIVED | Create file as temporary and if possible do not flush to disk. pmode argument is required when _O_CREAT is specified.
_O_CREAT | _O_TEMPORARY | Create file as temporary; file is deleted when last file handle is closed. pmode argument is required when _O_CREAT is specified.
_O_CREAT | _O_EXCL | Returns error value if file specified by filename exists. Applies only when used with _O_CREAT.
_O_RANDOM | Specifies primarily random access from disk
_O_RDONLY | Opens file for reading only;
_O_RDWR | Opens file for both reading and writing;
_O_SEQUENTIAL | Specifies primarily sequential access from disk
_O_TEXT | Opens file in text (translated) mode.
_O_TRUNC | Opens file and truncates it to zero length; file must have write permission. Used with _O_CREAT opens an existing file or creates a new file.
_O_WRONLY | Opens file for writing only;

The pmode argument is required only when _O_CREAT is specified. If the file already exists, pmode is ignored. Otherwise, pmode specifies the file permission settings, which are set when the new file is closed the first time. open applies the current file-permission mask to pmode before setting the permissions (for more information, see _umask). pmode is an integer expression containing one or both of the following manifest constants, defined in SYS\STAT.H:

_S_IREAD | Reading only permitted
_S_IWRITE | Writing permitted (effectively permits reading and writing)
_S_IREAD | _S_IWRITE | Reading and writing permitted

When both constants are given, they are joined with the bitwise-OR operator ( | ). In Windows NT, all files are readable, so write-only permission is not available; thus the modes _S_IWRITE and _S_IREAD | _S_IWRITE are equivalent.

Returns

An integer representing a handle to the open file, or -1 if the operation fails.


open_osfhandle

Function: open_osfhandle

Synopsis
#include <io.h>
int open_osfhandle(long osfhandle,int flags);

Description

The open_osfhandle function associates a C run time handle with an existing operating system handle as given by the windows function CreateFile. The <flags> argument can be one of the flags in fcntl.h:

_O_APPEND
_O_RDONLY
_O_TEXT

Returns

The open_osfhandle function returns a file handle usable by the low level i/o functions (read/write) or -1 in case of failure.

Portability

Windows


pclose

Function: pclose

Synopsis
#include <stdio.h>
int pclose(FILE *stream);

Description

The pclose function looks up the process ID of the command processor (CMD.EXE) started by the associated popen call, executes a _cwait call on the new command processor, and closes the stream on the associated pipe.

Returns

The pclose function returns the exit status of the terminating command processor, or 1 if an error occurs. The format of the return value is the same as that for _cwait, except the low-order and high-order bytes are swapped.


_popen

Function: popen

Synopsis
#include <stdio.h>
FILE *popen(const char *command,const char *mode);

Description

The popen function creates a pipe and asynchronously executes a spawned copy of the command processor with the specified string command. The character string mode specifies the type of access requested:

· "r" The calling process can read the spawned commands standard output via the result of popen.

· "w" The calling process can write to the spawned commands standard input via the result of _popen.

· "b" Open in binary mode.

· "t" Open in text mode.

Returns

Returns the communication stream or NULL if an error occurs.

Portability

A similar function exists under the LINUX operating system. (without the leading underscore)


printf

Function: printf

Synopsis
#include <stdio.h>
int printf(const char * restrict format, ...);

Description

The printf function is equivalent to fprintf with the argument stdout interposed

Returns

The printf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.

Format specifications

Printf type specifications table

Printf flags table

Printf precision specification table

Format specifications

A format specification, which consists of optional and required fields, has the following form:

%[flags] [width] [.precision] [modifiers] type of conversion

Each field of the format specification is a single character or a number signifying a particular format option. The simplest format specification contains only the percent sign and a type character (for example, %s). If a percent sign is followed by a character that has no meaning as a format field, the character is copied to stdout. For example, to print a percent-sign character, use %%.

The optional fields, which appear before the type character, control other aspects of the formatting, as follows:

type of conversion Required character that determines whether the associated argument is interpreted as a character, a string, or a number (see the Printf_type_specifications_table).

f lags Optional character or characters that control justification of output and printing of signs, blanks, decimal points, and octal and hexadecimal prefixes (see Printf_flags_table). More than one flag can appear in a format specification.

width Optional number that specifies the minimum number of characters output.

modifiers Letters that change the size of the input argument.

Modifier | Used with | Description
l | d,i,o,u,x, X | The letter l with this formats means long or unsigned long.
l | n | The letter l with the n format means long *.
l | c | Used with the c (character) format, it means the character string is in wide character format.
l | all others | No effect, is ignored
ll | d,i,o,u,x,X | The letters ll mean long long or unsigned long long.
ll | n | With this format, ll means long long *.
h | d,i,o,u,x,X | With this formats, h indicates short or unsigned short.
h | n | Means short *.
hh | d,i,o,u,x,X | Means char or unsigned char.
hh | n | Means char * or unsigned char *.
L | A, a, E, e, F, f, G, g, | Means that the argument is a long double. Notice that the l modifier has no effect with those formats. It is uppercase L.
j | d, i, o, u, x, X | Means the argument is of type intmax_t, i.e. the biggest integer type that an implementation offers. In the case of lcc-win32 this is long long.
q | f,g,e | Means the argument is of type qfloat (350 bits precision). This is an extension of lcc-win32.
t | d, i, o, u, x, X | Means the argument is ptrdiff_t, under lcc-win32 int.
z | d, i, o, u, x, X | Means the argument is size_t, in lcc-win32 unsigned int.

The width argument is a nonnegative decimal integer controlling the minimum number of characters printed. If the number of characters in the output value is less than the specified width, blanks are added to the left or the right of the values depending on whether the flag (for left alignment) is specified until the minimum width is reached. If width is prefixed with 0, zeros are added until the minimum width is reached (not useful for left-aligned numbers).

The width specification never causes a value to be truncated. If the number of characters in the output value is greater than the specified width, or if width is not given, all characters of the value are printed (subject to the precision specification).

If the width specification is an asterisk (*), an int argument from the argument list supplies the value. The width argument must precede the value being formatted in the argument list. A nonexistent or small field width does not cause the truncation of a field; if the result of a conversion is wider than the field width, the field expands to contain the conversion result.

precision Optional number that specifies the maximum number of characters printed for all or part of the output field, or the minimum number of digits printed for integer values See the Printf precision specification table

h | l | L | ' Optional prefixes to type-that specify the size of argument.

Note that the L modifier (for long longs and long doubles) is only supported by the xprintf functions.

The xprintf function family (xprintf, xfprintf, etc) support the thousands separator in the formats d and g. This modifier is the ' character (single quote).

Printf type specifications table

Char | Type | Output
c | int or wint_t | When used with printf functions, specifies a single-byte character; when used with wprintf functions, specifies a wide character
d | int | Signed decimal integer
I | int | Signed decimal integer
o | int | Unsigned octal integer
u | int | Unsigned decimal integer
x | int | Unsigned hexa, using "abcdef"
X | int | Unsigned hexa using ABCDEF
e | double | Signed value having the form [ ]d.dddd e [sign]ddd where d is a single decimal digit, dddd is one or more decimal digits, ddd is exactly three decimal digits, and sign is + or .
E | double | Identical to the previous format, only that the exponent will be written E and not e.
f | double | Signed value having the form [ ]dddd.dddd, where dddd is one or more decimal digits. The number of digits before the decimal point depends on the magnitude of the number, and the number of digits after the decimal point depends on the requested precision.
g | double | Signed value having the form [ ]dddd.dddd, where dddd is one or more decimal digits. The number of digits before the decimal point depends on the magnitude of the number, and the number of digits after the decimal point depends on the requested precision.
G | double | The same as the previous one, only that the exponent will be written as E
n | Pointer to integer | Number of characters successfully written so far to the stream or buffer; this value is stored in the integer whose address is given as the argument
p | Pointer to void | Prints the address pointed to by the argument in the form xxxx:yyyy where xxxx is the segment and yyyy is the offset, and the digits x and y are uppercase hexadecimal digits.
s | String | When used with printf functions, specifies a single-byte character string; when used with wprintf functions, specifies a wide-character string. Characters are printed up to the first null character or until the precision value is reached.
S | String | When used with printf functions, specifies a wide-character string; when used with wprintf functions, specifies a single-bytecharacter string. Characters are printed up to the first null character or until the precision value is reached.

Printf flags table

Flag | Meaning | Default
- | Left align the result within the given field width | default
+ | Prefix the output value with a sign (+ or ) if the output value is of a signed type | Sign appears only for negative signed values
0 | If width is prefixed with 0, zeros are added until the minimum width is reached. If 0 and appear, the 0 is ignored. If 0 is specified with an integer format (i, u, x, X, o, d) the 0 is ignored. | none
blank | Prefix the output value with a blank if the output value is signed and positive; the blank is ignored if both the blank and + flags appear | No blank appears.
# | When used with the o, x, or X format, the # flag prefixes any nonzero output value with 0, 0x, or 0X, respectively | No blank appears
# | When used with the e, E, or f format, the # flag forces the output value to contain a decimal point in all cases | No blank appears.
# | When used with the g or G format, the # flag forces the output value to contain a decimal point in all cases and prevents the truncation of trailing zeros. Ignored when used with c, d, i, u, or s. | Decimal point appears only if digits follow it. Trailing zeros are truncated.
' | When used with the g G or d formats, the digits will be separated by a thousands separator, for instance the number 123456789 will print as 123,456,789. Note that this functionality is only available with xprintf. | No thousands separator is printed by default

Printf precision specification table

Type | Meaning | Default
c,C | The precision has no effect. | Character is printed
d, i, u, o, x, X | The precision specifies the minimum number of digits to be printed. If the number of digits in the argument is less than precision, the output value is padded on the left with zerosThe value is not truncated when the number of digits exceeds precision. | Default precision is 1.
e, E | The precision specifies the number of digits to be printed after the decimal point. The last printed digit is rounded. | Default precision is 6; if precision is 0 or the period (.) appears without a number following it, no decimal point is printed
f | The precision value specifies the number of digits after the decimal point. If a decimal point appears, at least one digit appears before it. The value is rounded to the appropriate number of digits | Default precision is 6; if precision is 0, or if the period (.) appears without a number following it, no decimal point is printed.
g, G | The precision specifies the maximum number of significant digits printed. | Six significant digits are printed, with any trailing zeros truncated.
s, S | The precision specifies the maximum number of characters to be printed. Characters in excess of precision are not printed | Characters are printed until a null character is encountered.


putc

Function: putc

Synopsis
#include <stdio.h>
int putc(int c, FILE *stream);

Description

The putc function is equivalent to fputc, except that if it is implemented as a macro, it may evaluate stream more than once, so that argument should never be an expression with side effects.

Returns

The putc function returns the character written. If a write error occurs, the error indicator for the stream is set and putc returns EOF.


putchar

Function: putchar

Synopsis
#include <stdio.h>
int putchar(int c);

Description

The putchar function is equivalent to putc with the second argument stdout.

Returns

The putchar function returns the character written. If a write error occurs, the error indicator for the stream is set and putchar returns EOF.


puts

Function: puts

Synopsis
#include <stdio.h>
int puts(const char *s);

Description

The puts function writes the string pointed to by s to the stream pointed to by stdout, and appends a new-line character to the output. The terminating null character is not written.

Returns

The puts function returns EOF if a write error occurs; otherwise it returns a nonnegative value.


remove

Function: remove

Synopsis
#include <stdio.h>
int remove(const char *filename);

Description

The remove function causes the file whose name is the string pointed to by filename to be no longer accessible by that name. A subsequent attempt to open that file using that name will fail, unless it is created anew. If the file is open, the behavior of the remove function is implementation-defined.

Returns

The remove function returns zero if the operation succeeds, nonzero if it fails. The error codes are: EACCESS (read only file) or ENOENT (no such a file).

Example
#include <stdio.h>
int main( void )
{
    if( remove( "remove.obj" ) == -1 )
        perror( "Could not delete 'REMOVE.OBJ'" );
    else
        printf( "Deleted 'REMOVE.OBJ'\n" );
}


rename

Function: rename

Synopsis
#include <stdio.h>
int rename(const char *old, const char *new);

Description

The rename function causes the file whose name is the string pointed to by old to be henceforth known by the name given by the string pointed to by new. The file named old is no longer accessible by that name. If a file named by the string pointed to by new exists prior to the call to the rename function, the behavior is implementation-defined.

Returns

The rename function returns zero if the operation succeeds, nonzero if it fails in which case if the file existed previously it is still known by its original name.


rewind

Function: rewind

Synopsis
#include <stdio.h>
void rewind(FILE *stream);

Description

The rewind function sets the file position indicator for the stream pointed to by stream to the beginning of the file. It is equivalent to

(void)fseek(stream, 0L, SEEK_SET)

except that the error indicator for the stream is also cleared.

Returns

The rewind function returns no value.


rmdir

Function: rmdir

Synopsis
#include <direct.h>
int rmdir(const char * directoryName);

Description

This function deletes the indicated directory. In case of error, the values of errno can be one of:

ENOTEMPTY Directory wasnt empty

ENOENT Path doesn't point to an existing directory.

Returns

Zero for success, -1 for failure.

Portability

Windows

Lcc-win32 supports both the _rmdir and the rmdir functions, that point to the same function in CRTDLL.DLL.


scanf

Function: scanf

Synopsis
#include <stdio.h>
int scanf(const char * restrict format, ...);

Description

The scanf function is equivalent to fscanf with the argument stdin interposed before the arguments to scanf.

Returns

The scanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.


setbuf

Function: setbuf

Synopsis
#include <stdio.h>
void setbuf(FILE * restrict stream, char * restrict buf);

Description

Except that it returns no value, the setbuf function is equivalent to the setvbuf function invoked with the values _IOFBF for mode and BUFSIZ for size, or (if buf is a null pointer), with the value _IONBF for mode.

Returns

The setbuf function returns no value.


setmode

Function: setmode

Synopsis
#include <io.h>
#include <fcntl.h>
int semode(int handle, int mode);

Description

This function sets the translation mode (whether the file translates or not the \r \n sequences) to the mode specified by its <mode> argument. This argument should be either _O_TEXT or _O_BINARY, two manifest constants defined in fcntl.h

Returns

Returns the value of the previous translation mode.

Portability

Windows


setvbuf

Function: setvbuf

Synopsis
#include <stdio.h>
int setvbuf(FILE * restrict stream, char * restrict buf, int mode, size_t size);

Description

The setvbuf function may be used only after the stream pointed to by stream has been associated with an open file and before any other operation (other than an unsuccessful call to setvbuf) is performed on the stream. The argument mode determines how stream will be buffered, as follows: _IOFBF causes input/output to be fully buffered; _IOLBF causes input/output to be line buffered; _IONBF causes input/output to be unbuffered. If buf is not a null pointer, the array it points to may be used instead of a buffer allocated by the setvbuf function The buffer has to have a lifetime at least as great as the open stream, so the stream should be closed

before a buffer that has automatic storage duration is deallocated upon block exit. and the argument size specifies the size of the array; otherwise, size may determine the size of a buffer allocated by the setvbuf function. The contents of the array at any time are indeterminate.

Returns

The setvbuf function returns zero on success, or nonzero if an invalid value is given

for mode or if the request cannot be honored.


sopen _wsopen

Function: sopen , _wsopen

Synopsis
int _sopen(const char *filename, int oflag, int shflag [, int pmode ] );
int _wsopen(const wchar_t *filename, int oflag, int shflag [, int pmode ] );

This functions are NOT part of the ANSI C standard library.

Description

This functions open a file in shareable mode determined by the shflag argument. _wsopen is the wide char equivalent of _sopen.

They return a file handle for the opened file. A return value of -1 indicates an error, in which case errno is set to one of the following values:

EACCES Given path is a directory, or file is read-only, but an open-for-writing operation as attempted.

EEXIST _O_CREAT and _O_EXCL flags were specified, but filename already exists.

EINVAL Invalid oflag or shflag argument.

EMFILE No more file handles available.

ENOENT File or path not found.

The argument shflag is a constant expression consisting of one of the following manifest constants, defined in SHARE.H.

_SH_DENYRW Denies read and write access to file

_SH_DENYWR Denies write access to file

_SH_DENYRD Denies read access to file

_SH_DENYNO Permits read and write access

For convenience, lcc-win32 defines this values without underscores too.


sscanf

Function: sscanf

Synopsis
#include <stdio.h>
int sscanf(const char * restrict s,const char * restrict format, ...);
int xsscanf(const char * restrict s,const char * restrict format, ...);

This function is in the native windows C runtime. It does not support long long or long double arguments.

The xsscanf function is the lcc-win32 version of sscanf that supports long longs and long double data. It is based on the trio package.

Description

The sscanf function is equivalent to fscanf,except that input is obtained from a string (specified by the argument s) rather than from a stream. Reaching the end of the string is equivalent to encountering end-of-file for the fscanf function. If copying takes place between objects that overlap, the behavior is undefined.

Returns

The sscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the sscanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.


tempnam

Function: tempnam _tempnam

Synopsis
#include <stdio.h>
char *_tempnam(char *s);

Description

_tempnam creates a temporary filename for use in another directory. This filename is different from that of any existing file. The prefix argument is the prefix to the filename. _tempnam uses malloc to allocate space for the filename; the program is responsible for freeing this space when it is no longer needed. _tempnam looks for the file with the given name in the following directories, listed in order of precedence.

Returns

A pointer to the name generated or NULL if this fails. Note that this function is not an ANSI C library function.

Example
#include <stdio.h>
int main( void )
{
    FILE *stream;
    int i;
    /* Create temporary files. */
    for( i = 1; i <= 4; i++ )
    {
        if( (stream = tmpfile()) == NULL ) {
            perror( "Could not open new temporary file" );
            break;
        }
        else
            printf( "Temporary file %d was created", i );
    }
    /* Remove temporary files. */
    printf( "%d temporary files deleted", _rmtmp() );
return 0;
}


tmpfile

Function: tmpfile

Synopsis
#include <stdio.h>
FILE *tmpfile(void);

Description

The tmpfile function creates a temporary binary file that will automatically be removed when it is closed or at program termination. If the program terminates abnormally, whether an open temporary file is removed is implementation-defined. The file is opened for update with "wb+" mode.

Returns

The tmpfile function returns a pointer to the stream of the file that it created. If the file cannot be created, the tmpfile function returns a null pointer.

Example
#include <stdio.h>
int main( void )
{
    FILE *stream;
    int i;
    /* Create temporary files. */
    for( i = 1; i <= 4; i++ )
    {
        if( (stream = tmpfile()) == NULL ) {
        perror( "Could not open new temporary file" );
        break;
    }
    else
        printf( "Temporary file %d was created", i );
    }
    /* Remove temporary files. */
    printf( "%d temporary files deleted", _rmtmp() );
return 0;
}


tmpnam

Function: tmpnam

Synopsis
#include <stdio.h>
char *tmpnam(char *s);

Description

The tmpnam function generates a string that is a valid file name and that is not the same as the name of an existing file.

The tmpnam function generates a different string each time it is called, up to TMP_MAX times. If it is called more than TMP_MAX times, the behavior is implementation-defined. The implementation shall behave as if no library function calls the tmpnam function. This is untested under lcc-win32

Files created using strings generated by the tmpnam function are temporary only in the sense that their names should not collide with those generated by conventional naming rules for the implementation. It is still necessary to use the remove function to remove such files when their use is ended, and before program termination.

Returns

If the argument is a null pointer, the tmpnam function leaves its result in an internal static object and returns a pointer to that object. Subsequent calls to the tmpnam function may modify the same object. If the argument is not a null pointer, it is assumed to point to an array of at least L_tmpnam chars; the tmpnam function writes its result in that array and returns the argument as its value.

Environmental limits

The value of the macro TMP_MAX is 32767


ungetc

Function: ungetc ungetwc

Synopsis
#include <stdio.h>
int ungetc(int c, FILE *stream);
#include <wchar.h>
wint_t ungetwc(wint_t, FILE *);

Description

The ungetc function pushes the character specified by c (converted to an unsigned char) back onto the input stream pointed to by stream. Pushed-back characters will be returned by subsequent reads on that stream in the reverse order of their pushing. A successful intervening call (with the stream pointed to by stream) to a file positioning function (fseek, fsetpos, or rewind) discards any pushed-back characters for the stream. The external storage corresponding to the stream is unchanged.

One character of pushback is guaranteed. If the ungetc function is called too many times on the same stream without an intervening read or file positioning operation on that stream, the operation may fail.

Under the lcc-win32/windows system results are unpredictable if ungetc is called twice without a read or file-positioning operation between the two calls. After a call to fscanf, a call to ungetc may fail unless another read operation (such as getc) has been performed This is because fscanf itself calls ungetc.

If the value of c equals that of the macro EOF, the operation fails and the input stream is

unchanged.

A successful call to the ungetc function clears the end-of-file indicator for the stream. The value of the file position indicator for the stream after reading or discarding all pushed-back characters shall be the same as it was before the characters were pushed back. For a text stream, the value of its file position indicator after a successful call to the ungetc function is unspecified until all pushed-back characters are read or discarded.

For a binary stream, its file position indicator is decremented by each successful call to the ungetc function; if its value was zero before a call, it is indeterminate after the call.

Returns

The ungetc function returns the character pushed back after conversion, or EOF if the

operation fails.

The ungetwc is the wide character counterpart of ungetc.


vfprintf

Function: vfprintf

Synopsis
#include <stdarg.h>
#include <stdio.h>
int vfprintf(FILE * restrict stream, const char * restrict format, va_list arg);

Description

The vfprintf function is equivalent to fprintf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls).

The vfprintf function does not invoke the va_end macro. As the functions vfprintf, vfscanf, vprintf, vscanf, vsnprintf, vsprintf, and vsscanf invoke the va_arg macro, the value of arg after the return is indeterminate.

Returns

The vfprintf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.

Example

The following shows the use of the vfprintf function in a general error-reporting routine.
#include <stdarg.h>
#include <stdio.h>
void error(char *function_name, char *format, ...)
{
    va_list args;
    va_start(args, format);
    // print out name of function causing error
    fprintf(stderr, "ERROR in %s: ", function_name);
    // print out remainder of message
    vfprintf(stderr, format, args);
    va_end(args);
}


vprintf

Function: vprintf

Synopsis
#include <stdarg.h>
#include <stdio.h>
int vprintf(const char * restrict format, va_list arg);

Description

The vprintf function is equivalent to printf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vprintf function does not invoke the va_end macro.

Returns

The vprintf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.


vscanf

Function: vscanf

Synopsis
#include <stdarg.h>
#include <stdio.h>
int vscanf(const char * restrict format,va_list arg);

Description

The vscanf function is equivalent to scanf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vscanf function does not invoke the va_end macro.

Returns

The vscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the vscanf function returns the number of input items signed, which can be fewer than provided for, or even zero, in the event of an early matching failure.


write

Function: write

Synopsis
#include <io.h>
int write(int handle,const void *buffer,unsigned int count);

Description

The write function writes count bytes from the buffer buffer into the file associated with the handle handle. After the operation, the file pointer is moved by the corresponding amount. When writing in text mode, this function treats the character Ctrl-Z (26) as an EOF indicator. This is a behavior inherited from the CP/M operating system back in the beginning of the micro-computer age.

Returns

The number of bytes actually written. If this is less than count, this means there is no more space in the device for more data.

Portability

Wide, almost universal. The MSDOS features are obviously non-portable.


Memory Funcs

LCC-Win32 Memory Library Functions

_heapchk | bsearch | memchr | memset
_heapmin | calloc | memcmp | qsort
_heapset | free | memcpy | realloc
alloca | malloc | memmove |


_heapchk

Function: _heapchk

Synopsis
#include <malloc.h>
int _heapchk(void);

Description

The _heapchk function tests whether the heap is consistent.

Returns

_heapchk returns one of the following integer manifest constants defined in MALLOC.H

_HEAPBADBEGIN Initial header information is bad or cannot be found

_HEAPBADNODE Bad node has been found or heap is damaged

_HEAPBADPTR Pointer into heap is not valid

_HEAPEMPTY Heap has not been initialized

_HEAPOK Heap appears to be consistent

In addition, if an error occurs, _heapchk sets errno to ENOSYS.

Portability

Windows


_heapmin

Function: _heapmin

Synopsis
#include <malloc.h>
int _heapmin(void);

Description

The _heapmin function releases unused memory in the heap.

Returns

Zero on success, -1 otherwise

Portability

THIS FUNCTION WILL ONLY WORK UNDER WINDOWS NT. It will return -1 if called from another windows platform.


_heapset

Function: _heapset

Synopsis
#include <malloc.h>
int _heapset(int fill);

Description

The _heapset function sets all unused memory locations in the heap to the given value. This helps detect data that was written to a heap block that was already freed.

Returns

_heapset returns one of the following integer manifest constants defined in MALLOC.H:

_HEAPBADBEGIN Initial header information invalid or not found

_HEAPBADNODE Heap damaged or bad node found

_HEAPEMPTY Heap not initialized

_HEAPOK Heap appears to be consistent

In addition, if an error occurs, _heapset sets errno to ENOSYS

Portability

THIS FUNCTION WILL WORK ONLY UNDER WINDOWS NT. It will fail in all other windows platforms.


alloca

Function: alloca _alloca

Synopsis
#include <malloc.h>
void * _alloca(size_t);
void * alloca(size_t);

Description

The _alloca routine returns a void pointer to the allocated space, which is guaranteed to be suitably aligned for storage of any type of object. To get a pointer to a type other than char, use a type cast on the return value. A stack overflow exception is generated if the space cannot be allocated.

Returns

A pointer to the newly allocated memory


bsearch

Function: bsearch

Synopsis

#include <stdlib.h>

void *bsearch(const void *key, const void *base,size_t nmemb, size_t size,int (*compar)(const void *, const void *));

Description

The bsearch function searches an array of nmemb objects, the initial element of which is pointed to by base, for an element that matches the object pointed to by key. The size of each element of the array is specified by size.

The comparison function pointed to by compar is called with two arguments that point to the key object and to an array element, in that order. The function shall return an integer less than, equal to, or greater than zero if the key object is considered, respectively, to be less than, to match, or to be greater than the array element. The array shall consist of: all the elements that compare less than, all the elements that compare equal to, and all the elements that compare greater than the key object, in that order.In practice, the entire array is sorted according to the comparison function.

Returns

The bsearch function returns a pointer to a matching element of the array, or a null pointer if no match is found. If two elements compare as equal, which element is matched is unspecified.


calloc

Function: calloc

Synopsis
#include <malloc.h>
void *calloc(size_t nmemb, size_t size);

Description

The calloc function allocates space for an array of nmemb objects, each of whose size is size. The space is initialized to all bits zero. Note that this need not be the same as the representation of floating-point zero or a null pointer constant in other environments as windows.

Returns

The calloc function returns either a null pointer or a pointer to the allocated space.


free

Function: free

Synopsis
#include <stdlib.h>
void free(void *ptr);

Description

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc,or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

Returns

The free function returns no value.


malloc

Function: malloc

Synopsis
#include <stdlib.h>
void *malloc(size_t size);

Description

The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

Returns

The malloc function returns either a null pointer or a pointer to the allocated space.

Under lcc-win32, the following functions and their wide-character counterparts can also call malloc:

calloc fscanf _getw setvbuf _exec functions fseek _popen _spawn functions fgetc fsetpos printf _strdup _fgetchar _fullpath putc system fgets fwrite putchar _tempnam fprintf getc _putenv ungetc fputc getchar puts vfprintf _fputchar _getcwd _putw vprintf fputs _getdcwd scanf fread gets _searchenv


memchr

Function: memchr

Synopsis
#include <string.h>
void *memchr(const void *s, int c, size_t n);

Description

The memchr function locates the first occurrence of c (converted to an unsigned char) in the initial n characters (each interpreted as unsigned char) of the object pointed to by s.

Returns

The memchr function returns a pointer to the located character, or a null pointer if the character does not occur in the object.


memchr

Function: memshort, memushort

Synopsis
#include <string.h>
short *memshort(const short *s, short c, size_t len);
unsigned short *memshort(const unsigned short *s, unsigned short c, size_t len);

Description

The memshort/memushort functions locate the first occurrence of c in the initial n positions of the table pointed to by s.

Returns

The memshort/memushort function returns a pointer to the located number, or a null pointer if the number does not occur in the object.


memchr

Function: memint, memuint

Synopsis
#include <string.h>
int *memint(const int *s, int c, size_t len);
unsigned int *memuint(const unsigned int *s, unsigned int c, size_t len);

Description

The memint/memuint functions locate the first occurrence of c in the initial n positions of the table pointed to by s.

Returns

The memint/memuint functions return a pointer to the located number, or a null pointer if the number does not occur in the object.


memcmp

Function: memcmp

Synopsis
#include <string.h>
int memcmp(const void *s1, const void *s2, size_t n);

Description

The memcmp function compares the first n characters of the object pointed to by s1 to the first n characters of the object pointed to by s2.

Returns

The memcmp function returns an integer greater than, equal to, or less than zero, accordingly as the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2.


memcpy

Function: memcpy

Synopsis
#include <string.h>
void *memcpy(void * restrict s1, const void * restrict s2, size_t n);

Description

The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.

Returns

The memcpy function returns the value of s1.


memmove

Function: memmove

Synopsis
#include <string.h>
void *memmove(void *s1, const void *s2, size_t n);

Description

The memmove function copies n characters from the object pointed to by s2 into the object pointed to by s1. Copying takes place as if the n characters from the object pointed to by s2 are first copied into a temporary array of n characters that does not overlap the objects pointed to by s1 and s2, and then the n characters from the temporary array are copied into the object pointed to by s1.

Returns

The memmove function returns the value of s1.


memset

Function: memset

Synopsis
#include <string.h>
void *memset(void *s, int c, size_t n);

Description

The memset function copies the value of c (converted to an unsigned char) into each of the first n characters of the object pointed to by s.

Returns

The memset function returns the value of s.


qsort

Function: qsort

Synopsis
#include <stdlib.h>
void qsort(void *base, size_t nmemb, size_t size,int (*compar)(const void *, const void *));

Description

The qsort function sorts an array of nmemb objects, the initial element of which is pointed to by base. The size of each object is specified by size. The contents of the array are sorted into ascending order according to a comparison function pointed to by compar, which is called with two arguments that point to the objects being compared. The function shall return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

If two elements compare as equal, their order in the resulting sorted array is unspecified.


realloc

Function: realloc

Synopsis
#include <stdlib.h>
void *realloc(void *ptr, size_t size);

Description

The realloc function changes the size of the object pointed to by ptr to the size specified by size. The contents of the object shall be unchanged up to the lesser of the new and old sizes. If the new size is larger, the value of the newly allocated portion of the object is indeterminate. If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. If the space cannot be allocated, the object pointed to by ptr is unchanged. If the realloc function returns a null pointer when size is zero and ptr is not a null pointer, the object it pointed to has been freed.

Returns

The realloc function returns either a null pointer or a pointer to the possibly moved allocated space. If the object has moved, ptr is a pointer that refers to freed space.


Math Funcs

LCC-Win32 C99 Math Library Functions

Classification macros

int fpclassify(real-floating x);

int isfinite(real-floating x);

int isinf(real-floating x);

int isnan(real-floating x);

int isnormal(real-floating x);

int signbit(real-floating x);

Trigonometric functions

acos

double acos(double x);

float acosf(float x);

long double acosl(long double x);

asin

double asin(double x);

float asinf(float x);

long double asinl(long double x);

atan

double atan(double x);

float atanf(float x);

long double atanl(long double x);

atanh

double atanh(double x);

float atanhf(float x);

long double atanhl(long double x);

atan2

double atan2(double y, double x);

float atan2f(float y, float x);

long double atan2l(long double y, long double x);

cos

double cos(double x);

float cosf(float x);

long double cosl(long double x);

sin

double sin(double x);

float sinf(float x);

long double sinl(long double x);

tan

double tan(double x);

float tanf(float x);

long double tanl(long double x);

Hyperbolic functions

acosh

double acosh(double x);

float acoshf(float x);

long double acoshl(long double x);

asinh

double asinh(double x);

float asinhf(float x);

long double asinhl(long double x);

cosh

double cosh(double x);

float coshf(float x);

long double coshl(long double x);

sinh

double sinh(double x);

float sinhf(float x);

long double sinhl(long double x);

tanh

double tanh(double x);

float tanhf(float x);

long double tanhl(long double x);

Exponential and logarithmic functions

exp

double exp(double x);

float expf(float x);

long double expl(long double x);

exp2

double exp2(double x);

float exp2f(float x);

long double exp2l(long double x);

expm1

double expm1(double x);

float expm1f(float x);

long double expm1l(long double x);

frexp

double frexp(double value, int *exp);

float frexpf(float value, int *exp);

long double frexpl(long double value, int *exp);

ilogb

int ilogb(double x);

int ilogbf(float x);

int ilogbl(long double x);

ldexp

double ldexp(double x, int exp);

float ldexpf(float x, int exp);

long double ldexpl(long double x, int exp);

log

double log(double x);

float logf(float x);

long double logl(long double x);

log10

double log10(double x);

float log10f(float x);

long double log10l(long double x);

log1p

double log1p(double x);

float log1pf(float x);

long double log1pl(long double x);

log2

double log2(double x);

float log2f(float x);

long double log2l(long double x);

logb

double logb(double x);

float logbf(float x);

long double logbl(long double x);

modf

double modf(double value, double *iptr);

float modff(float value, float *iptr);

long double modfl(long double value, long double *iptr);

scalbn

double scalbn(double x, int n);

float scalbnf(float x, int n);

long double scalbnl(long double x, int n);

scalbln

double scalbln(double x, long int n);

float scalblnf(float x, long int n);

long double scalblnl(long double x, long int n);

cbrt

double cbrt(double x);

float cbrtf(float x);

long double cbrtl(long double x);

fabs

double fabs(double x);

float fabsf(float x);

long double fabsl(long double x);

hypot

double hypot(double x, double y);

float hypotf(float x, float y);

long double hypotl(long double x, long double y);

pow

double pow(double x, double y);

float powf(float x, float y);

long double powl(long double x, long double y);

sqrt

double sqrt(double x);

float sqrtf(float x);

long double sqrtl(long double x);

Error and gamma functions

erf

double erf(double x);

float erff(float x);

long double erfl(long double x);

erfc

double erfc(double x);

float erfcf(float x);

long double erfcl(long double x);

lgamma

double lgamma(double x);

float lgammaf(float x);

long double lgammal(long double x);

tgamma

double tgamma(double x);

float tgammaf(float x);

long double tgammal(long double x);

Nearest integer functions

ceil

double ceil(double x);

float ceilf(float x);

long double ceill(long double x);

floor

double floor(double x);

float floorf(float x);

long double floorl(long double x);

nearbyint

double nearbyint(double x);

float nearbyintf(float x);

long double nearbyintl(long double x);

rint

double rint(double x);

float rintf(float x);

long double rintl(long double x);

long int lrint(double x);

long int lrintf(float x);

long int lrintl(long double x);

long long int llrint(double x);

long long int llrintf(float x);

long long int llrintl(long double x);

round

double round(double x);

float roundf(float x);

long double roundl(long double x);

lround

long int lround(double x);

long int lroundf(float x);

long int lroundl(long double x);

llround

long long int llround(double x);

long long int llroundf(float x);

long long int llroundl(long double x);

trunc

double trunc(double x);

float truncf(float x);

long double truncl(long double x);

fmod

double fmod(double x, double y);

float fmodf(float x, float y);

long double fmodl(long double x, long double y);

Remainder functions

remainder

double remainder(double x, double y);

float remainderf(float x, float y);

long double remainderl(long double x, long double y);

remquo

double remquo(double x, double y, int *quo);

float remquof(float x, float y, int *quo);

long double remquol(long double x, long double y,int *quo);

Manipulation functions

copysign

double copysign(double x, double y);

float copysignf(float x, float y);

long double copysignl(long double x, long double y);

nan

double nan(const char *tagp);

float nanf(const char *tagp);

long double nanl(const char *tagp);

nextafter

double nextafter(double x, double y);

float nextafterf(float x, float y);

long double nextafterl(long double x, long double y);

nexttoward

double nexttoward(double x, long double y);

float nexttowardf(float x, long double y);

long double nexttowardl(long double x, long double y);

fdim

double fdim(double x, double y);

float fdimf(float x, float y);

long double fdiml(long double x, long double y);

Maximum, minimum, and positive difference functions

fmax

double fmax(double x, double y);

float fmaxf(float x, float y);

long double fmaxl(long double x, long double y);

fmin

double fmin(double x, double y);

float fminf(float x, float y);

long double fminl(long double x, long double y);

Floating multiply add

fma

double fma(double x, double y, double z);

float fmaf(float x, float y, float z);

long double fmal(long double x, long double y,long double z);

Comparison macros

The relational and equality operators support the usual mathematical relationships between numeric values. For any ordered pair of numeric values exactly one of the relationships less, greater, and equal is true. Relational operators may raise the invalid floating-point exception when argument values are NaNs. For a NaN and a numeric value, or for two NaNs, just the unordered relationship is true. The following subclauses provide macros that are quiet (non floating-point exception raising) versions of the relational operators, and other comparison macros that facilitate writing efficient code that accounts for NaNs without suffering the invalid floating-point exception. In the synopses in this subclause, real-floating indicates that the argument shall be an expression of real floating type.

int isgreater(real-floating x, real-floating y);

int isgreaterequal(real-floating x, real-floating y);

int isless(real-floating x, real-floating y);

int islessequal(real-floating x, real-floating y);

int islessgreater(real-floating x, real-floating y);

int isunordered(real-floating x, real-floating y);

Complex arithmetic

Trigonometric functions

Only the long double complex functions are documented here since lcc-win32 implements all three complex types (long double complex, double complex and float complex) as the same type.

long double complex cacos(long double complex);

long double complex casin(long double complex);

long double complex catan(long double complex);

long double complex ccos(long double complex);

long double complex csin(long double complex);

long double complex ctan(long double complex);

Hyperbolic functions

long double complex cacosh(long double complex);

long double complex casinh(long double complex);

long double complex catanh(long double complex);

long double complex ccosh(long double complex);

long double complex csinh(long double complex);

long double complex ctanh(long double complex);

Exponential and logarithmic functions

long double complex cexp(long double complex);

long double complex clog(long double complex);

Power and absolute value functions

long double cabs(long double complex);

long double complex cpow(long double complex,long double complex);

long double complex csqrt(long double complex);

Manipulation functions

long double carg(long double complex);

long double cimag(long double complex);

long double complex conj(long double complex);

long double complex cproj(long double complex);

long double creal(long double complex);

Additional functions provided by lcc-win32

This functions are not part of the C standard, but some of them are widely used with the same definitions.

Changing the machine precision

int DoublePrecision(void);

int FloatPrecision(void);

int FullPrecision(void);

Bessel functions

long double y0(long double);

long double y1(long double);

long double yn(long double int);

long double j0(long double);

long double jn(long double);


_fpclass

Function: _fpclass

Synopsis
#include <float.h>
int _fpclass(double n);

Description

The _fpclass function returns an integer that represent the different forms of classifying the given double precision value.

This values (defined in float.h) are:

_FPCLASS_SNAN | Signaling NaN
_FPCLASS_QNAN | Quiet NaN
_FPCLASS_NINF | Negative infinity (-INF)
_FPCLASS_NN | Negative normalized non-zero
_FPCLASS_ND | Negative denormalized
_FPCLASS_NZ | Negative zero (-0)
_FPCLASS_PZ | Positive 0 (+0)
_FPCLASS_PD | Positive denormalized
_FPCLASS_PN | Positive normalized non-zero
_FPCLASS_PINF | Positive infinity (+INF)

Returns

The classification of its argument x.

Portability

Windows (x86 specific). Note that lcc-win32 supports both _fpclass and fpclass.


_fpreset

Function: _fpreset

Synopsis
#include <float.h>
int _fpreset(void);

Description

This function resets the numerical coprocessor and its associated run time variables.

Returns

This function returns no value.


_j0

Function: _j0 _j1 _jn jnl

Synopsis
#include <math.h>
double _j0(double x);
long double j0l(long double x);
double _j1(double x);
double _jn(int n, double x);
long double jnl(int n, long double x);

Description

This functions compute the Bessel functions of the first kind for their arguments, orders 0, 1, and N respectively.

Returns

The bessel function value


_statusfp

Function: _statusfp

Synopsis
#include <float.h>
unsigned int _statusfp(void);

This function is NOT part of the ANSI C library.

Description

The bits in the value returned indicate the floating-point status. See the FLOAT.H include file for a complete definition of the bits returned by this function.


abs

Function: cabs

Synopsis
#include <complex.h>
long double cabsl(long double complex x);
double complex cabs(double complex x);
float complex cabsf(float complex x);
#include <qfloat.h>
qfloat complex cabsq(qfloat complex x);

Description

The abs, functions compute the absolute value of an integer j.If the result cannot be represented, the behavior is undefined.The absolute value of the most negative number cannot be represented in twos complement.

Returns

Returns the absolute value

Example
#include <stdlib.h>
int main(void)
{
    int i = -4;
    printf("The absolute value of %d is %d",i,abs(i));
}

The absolute value of -4 is 4


acos

Function: acos

Synopsis
#include <math.h>
qfloat acosq(qfloat x);
long double acosl(long double x);
double acos(double x);
float acosf(float x);

Description

The acos family functions compute the principal value of the arc cosine of x. A domain error occurs for arguments not in the range [-1, +1].

The generic function acos will accept any floating argument.

The inverse cosine can be defined as

Returns

The acos functions return the arc cosine in the range [0, PI] radians.

Example

/* ASINCOS.C: This program prompts for a value in the range
 * -1 to 1, the allowed range for asin and acos.
   The program prints the arcsine and the arccosine of that value.
   A value outside the allowed range will produce a NAN.
 */

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

int main( void )
{
   double x, y;

   printf( "Enter a real number between -1 and 1: " );
   scanf( "%lf", &x );
   y = asin( x );
   printf( "Arcsine of %.15f = %.15f\n", x, y );
   y = acos( x );
   printf( "Arccosine of %.15f = %.15f\n", x, y );
}

See also:


acosh

Function: acosh

Synopsis
#include <math.h>
qfloat acoshq(qfloat x);
long double acoshl(long double x);
double acosh(double x);
float acoshf(float x);

Description

The acosh functions compute the (nonnegative) arc hyperbolic cosine of x. A domain error occurs for arguments less than 1.

The generic function acosh will accept any floating argument.

Returns

The acosh functions return the arc hyperbolic cosine in the range [0, +INF].


asin

Function: asin

Synopsis
#include <math.h>
qfloat asinq(qfloat x);
long double asinl(long double x);
double asin(double x);
float asinf(float x);

Description

The asin functions compute the principal value of the arc sine of x. A domain error occurs for arguments not in the range [1, +1].

The generic function asin will accept any floating argument.

Definition

Returns

The asin functions return the arc sine in the range [ p/2, + p/2] radians.

See also:

acos, acosh, cos, cosh

Example
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 1.0
#define MIN -1.0
int main(void)
{
    double x, y;
    printf("Enter x");
    scanf("%lf", &x);
    /* Output error if not in range */
    if (x > MAX) {
        printf("Error: %lf too large for asin", x);
    }
    else if (x < MIN) {
        printf("Error: %lf is too small for asin", x);
    }
    else {
        y = asin(x);
        printf("asin ( %lf ) = %lf", x, y);
    }
}
D:>asin
Enter x
0.765
asin ( 0.765000 ) = 0.871041
D:>asin
Enter x
5.9
Error: 5.900000 too large for asin


asinh

Function: asinh

Synopsis
#include <math.h>
double asinh(double x);
long double asinhl(long double x);
qfloat asinhq(qfloat x);

Description

The asinh functions compute the arc hyperbolic sine of x.

The generic function asinh will accept any floating argument.

Returns

The asinh functions return the arc hyperbolic sine value.


atan

Function: atan atan2

Synopsis
#include <math.h>

double atan(double x);
float atanf(float x);
long double atanl(long double x);
qfloat atanq(qfloat &x);

double atan2(double y, double x);
long double atan2l(long double);

Description

atan returns the arctangent of x. atan2 returns the arctangent of y/x. If x is 0, atan returns 0. If both parameters of atan2 are 0, the function returns 0. You can modify error handling by using the _matherr routine.

atan returns a value in the range p/2 to p/2 radians; atan2 returns a value in the range p to p radians, using the signs of both parameters to determine the quadrant of the return value.

The generic function atan will accept any floating argument.


atanh

Function: atanh

Synopsis
#include <math.h>

float atanhf(float x);
double atanh(double x);
long double atanhl(long double x);
qfloat atanhq(qfloat &x);

Description

The atanh functions compute the arc hyperbolic tangent of x. A domain error occurs for arguments not in the range [-1, +1]. A range error may occur if the argument equals -1 or +1.

Returns

The atanh functions return the arc hyperbolic tangent value.


abs

Function: cabs

Synopsis
#include <complex.h>
long double cabsl(long double complex x);
double complex cabs(double complex x);
float complex cabsf(float complex x);
#include <qfloat.h>
qfloat complex cabsq(qfloat complex x);

Description

The cabs functions compute the complex absolute value (also called norm, modulus, or magnitude) of x.

Returns

Returns the absolute value

Example
#include <math.h>
#include <stdio.h>
#include <complex.h>
#include <qfloat.h>

int main(void)
{
qfloat complex qc = 1.5+2.3i;
long double _Complex ldc = 1.5+2.3i;
double _Complex dc = 1.5+2.3i;

printf("%-12s:\n%38.35qe\n%23.18Le\n%19.16e\n","cabs(1.5+2.3i)",cabs(qc),cabs(ldc),cabs(dc));
return 0;
}
Output:
cabs(1.5+2.3i):
2.74590604354919616754324801378837197e+00
2.745906043549196168e+00
2.7459060435491960e+00


cos

Function: cacos

Synopsis
#include <complex.h>
float complex cacosf(float complex x);
double complex cacos(double complex x);
long double complex cacosl(long double complex x);
qfloat complex cacosq(qfloat complex x);

Description

The cacos functions compute the arc cosine of x (measured in radians). The generic function cacos can be used instead of this functions.

Returns

The cacos functions returns the complex arc cosine value.

Example

#include <math.h>
#include <complex.h>
#include <qfloat.h>
void printComplex(char *which,qfloat _Complex &qcr,long double _Complex &ldr,double _Complex &dcr)
{
    printf("%s(1.5+2.3i)= %.25qf %.25qf qfloat\n",which,creal(qcr),cimag(qcr));
    printf("%s(1.5+2.3i)= %.25Lf %.25Lf long double\n",which,creal(ldr),cimag(ldr));
    printf("%s(1.5+2.3i)= %.15f %.15f double\n\n",which,creal(dcr),cimag(dcr));
}

int main(void)
{
    qfloat complex qc = 1.5+2.3i;
    long double _Complex ldc = 1.5+2.3i;
    double _Complex dc = 1.5+2.3i;

    printComplex("cacos(1.5+2.3i)",cacos(qc),cacos(ldc),cacos(dc));
    return 0;
}

Output

cacos(1.5+2.3i)(1.5+2.3i)= 1.0219907918490058021031844 -1.7176259509302463967644605 qfloat
cacos(1.5+2.3i)(1.5+2.3i)= 1.0219907918490058020000000 -1.7176259509302463970000000 long double
cacos(1.5+2.3i)(1.5+2.3i)= 1.021990791849006 -1.717625950930247 double


cos

Function: cacosh

Synopsis
#include <complex.h>
float complex cacoshf(float complex x);
double complex cacosh(double complex x);
long double complex cacoshl(long double complex x);
qfloat complex cacoshq(qfloat complex x);

Description

The cacosh functions compute the hyperbolic arc cosine of x (measured in radians). The generic function cacosh can be used instead of this functions.

Returns

The cacosh functions returns the complex arc cosine value.

Example

#include <math.h>
#include <complex.h>
#include <qfloat.h>
void printComplex(char *which,qfloat _Complex &qcr,long double _Complex &ldr,double _Complex &dcr)
{
    printf("%s(1.5+2.3i)= %.25qf %.25qf qfloat\n",which,creal(qcr),cimag(qcr));
    printf("%s(1.5+2.3i)= %.25Lf %.25Lf long double\n",which,creal(ldr),cimag(ldr));
    printf("%s(1.5+2.3i)= %.15f %.15f double\n\n",which,creal(dcr),cimag(dcr));
}

int main(void)
{
    qfloat complex qc = 1.5+2.3i;
    long double _Complex ldc = 1.5+2.3i;
    double _Complex dc = 1.5+2.3i;

    printComplex("cacosh(1.5+2.3i)",cacosh(qc),cacosh(ldc),cacosh(dc));
    return 0;
}

Output

cacosh(1.5+2.3i)(1.5+2.3i)= 1.7176259509302463967644605 1.0219907918490058021031844 qfloat
cacosh(1.5+2.3i)(1.5+2.3i)= 1.7176259509302463970000000 1.0219907918490058020000000 long double
cacosh(1.5+2.3i)(1.5+2.3i)= 1.717625950930247 1.021990791849006 double


asin

Function: casin

Synopsis
#include <complex.h>
long double _Complex casinl(long double _Complex x);
double _Complex casin(double _Complex x);
float _Complex casinf(float _Complex x);
qfloat _Complex casinq(qfloat _Complex x);

Description

The casin functions compute the complex arc sine of x.

Returns

The casin functions return the arc sine of the complex argument.

Remarks

Link with math.lib


asin

Function: casinh

Synopsis
#include <complex.h>
long double _Complex casinhl(long double _Complex x);
double _Complex casinh(double _Complex x);
float _Complex casinhf(float _Complex x);
qfloat _Complex casinhq(qfloat _Complex x);

Description

The casinh functions compute the complex hyperbolic arc sine of x.

Returns

The casin functions return the hyperbolic arc sine of the complex argument.


tan

Function: catan

Synopsis
#include <math.h>
double complex catan(double complex x);
long double complex catanl( long double complex x);
float complex catanf(float complex x);
#include <qfloat.h>
qfloat complex catanq(qfloat complex x);

Description

The catan functions return the arc tangent of x (measured in radians). They can be replaced by the generic function catan.

Returns

The catan function returns the hyperbolic arc tangent value.

Example:

#include <math.h>
#include <complex.h>
#include <qfloat.h>
void printComplex(char *which,qfloat _Complex &qcr,long double _Complex &ldr,double _Complex &dcr)
{
    printf("%s(1.5+2.3i)= %.25qf %.25qf qfloat\n",which,creal(qcr),cimag(qcr));
    printf("%s(1.5+2.3i)= %.25Lf %.25Lf long double\n",which,creal(ldr),cimag(ldr));
    printf("%s(1.5+2.3i)= %.15f %.15f double\n\n",which,creal(dcr),cimag(dcr));
}

int main(void)
{
qfloat complex qc = 1.5+2.3i;
long double _Complex ldc = 1.5+2.3i;
double _Complex dc = 1.5+2.3i;

printComplex("catanh(1.5+2.3i)",catan(qc),catan(ldc),catan(dc));
return 0;
}

Output

catan(1.5+2.3i)(1.5+2.3i)= 1.3557572592669653458113962 0.3011200724366555012774094 qfloat
catan(1.5+2.3i)(1.5+2.3i)= 1.3557572592669653310000000 0.3011200724366555010000000 long double
catan(1.5+2.3i)(1.5+2.3i)= 1.355757259266965 0.301120072436656 double


tan

Function: catanh

Synopsis
#include <math.h>
double complex catanh(double complex x);
long double complex catanhl( long double complex x);
float complex catanhf(float complex x);
#include <qfloat.h>
qfloat complex catanhq(qfloat complex x);

Description

The catanh functions return the hyperbolic arc tangent of x (measured in radians). They can be replaced by the generic function catanh.

Returns

The catanh function returns the hyperbolic arc tangent value.

Example:

#include <math.h>
#include <complex.h>
#include <qfloat.h>
void printComplex(char *which,qfloat _Complex &qcr,long double _Complex &ldr,double _Complex &dcr)
{
    printf("%s(1.5+2.3i)= %.25qf %.25qf qfloat\n",which,creal(qcr),cimag(qcr));
    printf("%s(1.5+2.3i)= %.25Lf %.25Lf long double\n",which,creal(ldr),cimag(ldr));
    printf("%s(1.5+2.3i)= %.15f %.15f double\n\n",which,creal(dcr),cimag(dcr));
}

int main(void)
{
qfloat complex qc = 1.5+2.3i;
long double _Complex ldc = 1.5+2.3i;
double _Complex dc = 1.5+2.3i;

printComplex("catanh(1.5+2.3i)",catanh(qc),catanh(ldc),catanh(dc));
return 0;
}

Output

catanh(1.5+2.3i)(1.5+2.3i)= 0.0028943424439431970564545115 1.0200983821235149579584802 qfloat
catanh(1.5+2.3i)(1.5+2.3i)= 0.0028943424439431970000000 1.0200983821235149580000000 long double
catanh(1.5+2.3i)(1.5+2.3i)= 0.002894342443943 1.020098382123515 double


cbrt

Function: cbrt

Synopsis
#include <math.h>
double cbrt(double);
long double cbrtl(long double);
qfloat cbrtq(qfloat);

Description

The cbrt function computes the real cube root of x.

Returns

The cbrt function returns the value of the cubic root of x.


cos

Function: ccos

Synopsis
#include <complex.h>
float complex ccosf(float complex x);
double complex ccos(double complex x);
long double complex ccosl(long double complex x);
qfloat complex ccosq(qfloat complex x);

Description

The ccos functions compute the cosine of x (measured in radians). The generic function ccos can be used instead of this functions.

Returns

The ccos functions returns the complex cosine value.

Example

#include <math.h>
#include <complex.h>
#include <qfloat.h>
void printComplex(char *which,qfloat _Complex &qcr,long double _Complex &ldr,double _Complex &dcr)
{
    printf("%s(1.5+2.3i)= %.25qf %.25qf qfloat\n",which,creal(qcr),cimag(qcr));
    printf("%s(1.5+2.3i)= %.25Lf %.25Lf long double\n",which,creal(ldr),cimag(ldr));
    printf("%s(1.5+2.3i)= %.15f %.15f double\n\n",which,creal(dcr),cimag(dcr));
}

int main(void)
{
    qfloat complex qc = 1.5+2.3i;
    long double _Complex ldc = 1.5+2.3i;
    double _Complex dc = 1.5+2.3i;

    printComplex("ccos(1.5+2.3i)",ccos(qc),ccos(ldc),ccos(dc));
    return 0;
}

Output

ccos(1.5+2.3i)(1.5+2.3i)= 0.3563188929120418236267563 -4.9245946500877942532322978 qfloat
ccos(1.5+2.3i)(1.5+2.3i)= 0.3563188929120418240000000 -4.9245946500877942530000000 long double
ccos(1.5+2.3i)(1.5+2.3i)= 0.356318892912042 -4.924594650087793 double


cos

Function: ccosh

Synopsis
#include <complex.h>
float complex ccoshf(float complex x);
double complex ccosh(double complex x);
long double complex ccoshl(long double complex x);
qfloat complex ccoshq(qfloat complex x);

Description

The ccosh functions compute the complex hyperbolic cosine of x.

The generic function ccosh can be used instead of this functions.

Returns

The ccosh functions returns the complex hyperbolic cosine value.

Example

#include <math.h>
#include <complex.h>
#include <qfloat.h>
void printComplex(char *which,qfloat _Complex &qcr,long double _Complex &ldr,double _Complex &dcr)
{
    printf("%s(1.5+2.3i)= %.25qf %.25qf qfloat\n",which,creal(qcr),cimag(qcr));
    printf("%s(1.5+2.3i)= %.25Lf %.25Lf long double\n",which,creal(ldr),cimag(ldr));
    printf("%s(1.5+2.3i)= %.15f %.15f double\n\n",which,creal(dcr),cimag(dcr));
}

int main(void)
{
    qfloat complex qc = 1.5+2.3i;
    long double _Complex ldc = 1.5+2.3i;
    double _Complex dc = 1.5+2.3i;

    printComplex("ccos(1.5+2.3i)",ccosh(qc),ccosh(ldc),ccosh(dc));
    return 0;
}

Output

ccosh(1.5+2.3i)(1.5+2.3i)= -1.5673541188646728981939636 1.5878147878450120046471793 qfloat
ccosh(1.5+2.3i)(1.5+2.3i)= -1.5673541188646728980000000 1.5878147878450120050000000 long double
ccosh(1.5+2.3i)(1.5+2.3i)= -1.567354118864673 1.587814787845012 double


ceil

Function: ceil

Synopsis
#include <math.h>
float ceilf(float x);
double ceil(double x);
qfloat ceilq(qfloat x);
long double ceill(long double x);

Description

The ceil functions compute the smallest integer value not less than x

Returns

The ceil functions return the smallest integer value not less than x, expressed as a floating-point number.

Example
#include <math.h>
#include <stdio.h>
int main( void )
{
    double y;
    y = floor( 2.644 );
    printf( "The floor of 2.644 is %f", y );
    y = floor( -2.644 );
    printf( "The floor of -2.644 is %f", y );
    y = ceil( 2.955 );
    printf( "The ceil of 2.955 is %f", y );
    y = ceil( -2.955 );
    printf( "The ceil of -2.955 is %f", y );
}
The floor of 2.644 is 2.000000
The floor of -2.644 is -3.000000
The ceil of 2.955 is 3.000000
The ceil of -2.955 is -2.000000


copysign

Function: copysign

Synopsis
#include <math.h>
double copysign(double x, double y);

Description

The copysign function produces a value with the magnitude of x and the sign of y. They produce a NaN (with the sign of y) if x is a NaN. On implementations that represent a signed zero but do not treat negative zero consistently in arithmetic operations, the copysign functions regards the sign of zero as positive.

Returns

The copysign functions return a value with the magnitude of x and the sign of y.

Example
#include <stdio.h>
#include <math.h>
int main(void)
{
    double value = 45.98;
    double sign = -10.0;
    printf("The sign of %g times the magnitude of %g is %g", sign,
        value, copysign(value,-1.0));
}
The sign of -10 times the magnitude of 45.98 is -45.98


cos

Function: cos

Synopsis
#include <math.h>
float cosf(float x);
double cos(double x);
long double cosl(long double x);
#include <qfloat.h>
qfloat cosq(qfloat x);

Description

The cos family functions compute the cosine of x (measured in radians). The generic function cos will accept any floating argument.

Returns

The cos function returns the cosine value.


cosh

Function: cosh

Synopsis
#include <math.h>
double cosh(double x);
long double coshl(long
    double x);
float coshf(float x);
#include <qfloat.h>
qfloat coshq(qfloat &x);

Description

The cosh family functions compute the hyperbolic cosine of x. A range error occurs if the magnitude of x is too large.

The generic function cosh will accept any floating argument.

Returns

The cosh functions return the hyperbolic cosine value.

cosh x = (ex + ex) / 2

Example
#include <math.h>
#include <stdio.h>
int main( void )
{
    double pi = 3.1415926535;
    double x, y;
    x = pi / 2;
    y = sin( x );
    printf( "sin( %f ) = %f", x, y );
    y = sinh( x );
    printf( "sinh( %f ) = %f",x, y );
    y = cos( x );
    printf( "cos( %f ) = %f", x, y );
    y = cosh( x );
    printf( "cosh( %f ) = %f",x, y );
}


pow

Function: cpow

Synopsis
#include <math.h>
double complex cpow(double complex x, double complex y);
long double complex cpowl(long double complex x,long double complex y);
float complex cpowf(float complex x,float complex y);
#include <qfloat.h>
qfloat complex cpowq(qfloat complex x,qfloat complex y);

Description

The cpow functions compute x raised to the power y.

Returns

The cpow(x,y) macro can be used in place of the above functions.


sqrt

Function: csqrt

Synopsis
#include <complex.h>
double complex csqrt(double _Complex x);
long double complex csqrtl(long double complex x);
float complex csqrtf(float complex x);
#include <qfloat.h>
qfloat csqrtq(qfloat complex x);

The csqrt(x) generic function can be used instead of the above functions.

Description

The csqrt functions compute the complex square root of x.

Returns

The csqrt functions return the value of the complex square root.


sin

Function: csin

Synopsis
#include <complex.h>
double complex csin(double complex x);
long double complex csinl(long double complex x);
float complex csinf(float complex x);
#include <qfloat.h>
qfloat complex csinq(qfloat complex x);

Description

The csin function computes the complex sine of x (measured in radians).

Returns

The csin functions return the sine value. Note that the generic function csin() can be used instead of the above functions.

Example

#include <math.h>
#include <complex.h>
#include <qfloat.h>

// Help function to print a complex chain
void printComplex(char *which,qfloat _Complex &qcr,long double _Complex &ldr,double _Complex &dcr)
{
    printf("%s(1.5+2.3i)= %.25qf %.25qf qfloat\n",which,creal(qcr),cimag(qcr));
    printf("%s(1.5+2.3i)= %.25Lf %.25Lf long double\n",which,creal(ldr),cimag(ldr));
    printf("%s(1.5+2.3i)= %.15f %.15f double\n\n",which,creal(dcr),cimag(dcr));
}

int main(void)
{
qfloat complex qc = 1.5+2.3i;
long double _Complex ldc = 1.5+2.3i;
double _Complex dc = 1.5+2.3i;

    printComplex("csin(1.5+2.3i)",csin(qc),csin(ldc),csin(dc));
    return 0;
}

Output:

csin(1.5+2.3i)(1.5+2.3i)= 5.0246023440640103502861832 0.3492268628646511459142503 qfloat
csin(1.5+2.3i)(1.5+2.3i)= 5.0246023440640103510000000 0.3492268628646511460000000 long double
csin(1.5+2.3i)(1.5+2.3i)= 5.024602344064010 0.349226862864651 double


tan

Function: ctan

Synopsis
#include <math.h>
double complex ctan(double complex x);
long double complex ctanl( long double complex x);
float complex ctanf(float complex x);
#include <qfloat.h>
qfloat complex ctanq(qfloat complex x);

Description

The ctan functions return the tangent of x (measured in radians). They can be replaced by the generic function ctan.

Returns

The ctan function returns the tangent value.

Example:

#include <math.h>
#include <complex.h>
#include <qfloat.h>
void printComplex(char *which,qfloat _Complex &qcr,long double _Complex &ldr,double _Complex &dcr)
{
    printf("%s(1.5+2.3i)= %.25qf %.25qf qfloat\n",which,creal(qcr),cimag(qcr));
    printf("%s(1.5+2.3i)= %.25Lf %.25Lf long double\n",which,creal(ldr),cimag(ldr));
    printf("%s(1.5+2.3i)= %.15f %.15f double\n\n",which,creal(dcr),cimag(dcr));
}

int main(void)
{
qfloat complex qc = 1.5+2.3i;
long double _Complex ldc = 1.5+2.3i;
double _Complex dc = 1.5+2.3i;

printComplex("ctan(1.5+2.3i)",ctan(qc),ctan(ldc),ctan(dc));
return 0;
}

Output

ctan(1.5+2.3i)(1.5+2.3i)= 0.0028943424439431970564545115 1.0200983821235149579584802 qfloat
ctan(1.5+2.3i)(1.5+2.3i)= 0.0028943424439431970000000 1.0200983821235149580000000 long double
ctan(1.5+2.3i)(1.5+2.3i)= 0.002894342443943 1.020098382123515 double


tan

Function: ctanh

Synopsis
#include <math.h>
double complex ctanh(double complex x);
long double complex ctanhl( long double complex x);
float complex ctanhf(float complex x);
#include <qfloat.h>
qfloat complex ctanhq(qfloat complex x);

Description

The ctanh functions return the hyperbolic tangent of x. They can be replaced by the generic function ctanh.

Returns

The ctanh function returns the tangent value.

Example:

#include <math.h>
#include <complex.h>
#include <qfloat.h>
void printComplex(char *which,qfloat _Complex &qcr,long double _Complex &ldr,double _Complex &dcr)
{
    printf("%s(1.5+2.3i)= %.25qf %.25qf qfloat\n",which,creal(qcr),cimag(qcr));
    printf("%s(1.5+2.3i)= %.25Lf %.25Lf long double\n",which,creal(ldr),cimag(ldr));
    printf("%s(1.5+2.3i)= %.15f %.15f double\n\n",which,creal(dcr),cimag(dcr));
}

int main(void)
{
qfloat complex qc = 1.5+2.3i;
long double _Complex ldc = 1.5+2.3i;
double _Complex dc = 1.5+2.3i;

printComplex("ctanh(1.5+2.3i)",ctanh(qc),ctanh(ldc),ctanh(dc));
return 0;
}

Output

ctanh(1.5+2.3i)(1.5+2.3i)= 1.0062644165788172679928578 -0.099813174478249691487056104 qfloat
ctanh(1.5+2.3i)(1.5+2.3i)= 1.0062644165788172680000000 -0.0998131744782496910000000 long double
ctanh(1.5+2.3i)(1.5+2.3i)= 1.006264416578817 -0.099813174478250 double


asin

Function: cubic

Synopsis
#include <math.h>
void cubic(double a,double b,double c,double d,int *nbsolutions,double *x)

Description

This function will solve the equation

ax3 + bx2 + cx + d = 0

In the int pointer nbsolutions will be written the number of solutions that was found, in the vector "x" will be written the value of the solutions. It should be a length 3 vector.

Returns

No return value


div

Function: div, lldiv

Synopsis
#include <stdlib.h>
div_t div(int numer, int denom);
ldiv_t div(long numer, long denom);
lldiv_t lldiv(long long numer, long long denom);

Description

The div, ldiv, and lldiv, functions compute numer (numerator) / denom (denominator) and numer % denom in a single operation.

Returns

The div functions return a structure of type div_t, ldiv_t comprising both the quotient and the remainder.

The structures shall contain (in either order) the members quot (the quotient) and rem (the remainder), each of which have the same type as the arguments numer and denom. If either part of the result cannot be represented, the behavior is undefined.

typedef struct {
    int quot; /* quotient */
    int rem; /* remainder */
} div_t;

typedef struct {
    long quot; /* quotient */
    long rem; /* remainder */
} ldiv_t;

typedef struct {
    long long quot; /* quotient */
    long long rem; /* remainder */
} lldiv_t;


DoublePrecision

Function: DoublePrecision

Synopsis
#include <fenv.h>
int DoublePrecision(void);

Description

Sets the FPU precision bits to 53 bits (Double precision)

Returns

Returns the old settings of the precision flags.

See also

FloatPrecision

FullPrecision


erf

Function: erf erfc

Synopsis
#include <math.h>
#include <qfloat.h>
double erf(double x);
long double erfl(long double x);
qfloat erfq(qfloat x);
qfloat erfcq(qfloat x);
long double erfcl(double x);
double erf(double x);
float erfcf(float x);

Description

A range error occurs if x is too large.

Returns

The function's value.


exp

Function: exp

Synopsis
#include <math.h>
#include <qfloat.h>
qfloat expq(qfloat x);
double exp(double x);
float expf(float x);
long double expl(long double x);

Description

The exp functions compute the base-e exponential of x: e^x . A range error occurs if the magnitude of x is too large.

Lcc-win32 defines the exp function as a generic function: the argument can be float, double, long double, qfloat or a bignum. This way, the user can redefine this function to cater for new numeric types. The type specific functions are available separatedly too.

Returns

The exp function returns the exponential value. The type of the return value depends on the arguments given.

Example

#include <math.h>
#include <stdio.h>

int main( void )
{
   double x = 1.877665544, y;

   y = exp( x );
   printf( "exp( %f ) = %.15f\n", x, y );
}

Output:

exp( 1.877666 ) = 6.538223836824980


exp

Function: exp10

Synopsis
#include <math.h>
#include <qfloat.h>
qfloat exp10q(qfloat x);
double exp10(double x);
float exp10f(float x);
long double exp10l(long double x);

Description

The exp10 functions compute the base-10 exponential of x: 10^x . A range error occurs if the magnitude of x is too large.

Lcc-win32 defines the exp10 function as a generic function: the argument can be float, double, long double, qfloat or a bignum. This way, the user can redefine this function to cater for new numeric types. The type specific functions are available separatedly too.

Returns

The exp10 function returns the exponential value. The type of the return value depends on the arguments given.

Example

#include <math.h>
#include <stdio.h>

int main( void )
{
   double x = 1.877665544, y;

   y = exp10( x );
   printf( "exp10( %f ) = %.15f\n", x, y );
}

Output:

exp10( 1.877666 ) = 75.451094487833700


expm1

Function: expm1

Synopsis
#include <math.h>
double expm1(double x);
long double expm1l(long double);
#include <qfloat.h>
qfloat expm1q(qfloat x);

Description

The expm1 functions compute the base-e exponential of x minus 1. (e^x-1)

Returns

The expm1 functions returns the value of exp(x) - 1. With a small magnitude of the input data it is expected to be more accurate than exp(x) - 1.


fabs

Function: fabs

Synopsis
#include <math.h>
double fabs(double x);
float fabsf(float x);
long double fabsl(long double x);
#include <qfloat.h>
qfloat fabsq(qfloat x);

Description

The fabs functions compute the absolute value of a floating-point number x.

Returns

The fabs functions return the absolute value of x.

Example
/* ABS.C: This program computes and displays the absolute values of several
* numbers, using fabs and abs
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main( void )
{
    int ix = -5, iy;
    long lx = -62458L, ly;
    double dx = -4.966321, dy;
    long double ldx = -144.966321, ldy;
    iy = abs( ix );
    printf( "The absolute value of %d is %d\n", ix, iy);
    ly = abs( lx );
    printf( "The absolute value of %ld is %ld\n", lx, ly);
    dy = fabsd( dx );
    printf( "The absolute value of %f is %f\n", dx, dy );
    ldy = fabsl( ldx );
    xprintf( "The absolute value of %Lf is %Lf\n", ldx, ldy );
    return 0;
}
Output:
The absolute value of -5 is 5
The absolute value of -62458 is 62458
The absolute value of -4.966321 is 4.966321
The absolute value of -144.966321 is 14 4.966321


asin

Function: fcmp fcmpl

Synopsis
#include <math.h>
int fcmp(double x,double y,double epsilon);
int fcmpl(long double x,long double y,long double epsilon);

Description

Floating point numbers are inherently inexact, and comparisons between them are also inexact. Equality or `==' comparisons are particularly unreliable. In the following code snippet, x is unlikely to be exactly equal to y, even if both variable nominally have the same value. This is due to sources of error such as truncation error and rounding error.

float x; float y;

/* calculations */

if (x == y) { /* unlikely to work! */ /* code to be executed if x == y */ }

For example, the following program (from Priest [3]) may produce the output "Equal" or "Not Equal", depending on the platform, compiler, and compile-time options that are used:

#include <stdio.h>

int main()
{
    double q;

    q = 3.0/7.0;
    if (q == 3.0/7.0)
        printf("Equal\n");
    else printf("Not Equal\n");
    return 0;
}

The same problem holds for `<', `>', `<=', `>=', and `!=' comparisons. Since equality cannot be exactly determined with floating point numbers, inequality cannot either.

What is needed is a comparison operator that takes into account a certain amount of uncertainty:

if (fabs(x - y) <= epsilon) { /* code to be executed if x == y */ }

if (x - y > epsilon) { /* code to be executed if x > y */ }

if (x - y < -epsilon) { /* code to be executed if x < y */ }

In the above code, a neighborhood is defined that extends a distance epsilon to either side of y on the real number line. If x falls within epsilon of y, x is declared to be equal to y (the first case, above). If x is greater than y by an amount that is greater than epsilon, x is declared to be greater than y (the second case, above). If x is less than y by an amount that is greater than epsilon, x is declared to be less than y (the third case, above).

The problem then becomes to determine an appropriate value of epsilon. A fixed value of epsilon would not work for all x and y; epsilon should be scaled larger or smaller depending on the magnitudes of the numbers to be compared.

A floating point number is represented by two numbers, the significand (also called the fraction or mantissa) and the exponent, and a sign, where

0 <= significand < 1

and

number = sign * significand * pow(2, exponent).

Knuth's suggestion is to scale epsilon by the exponent of the larger of the two floating point numbers to be compared:

delta = epsilon * maxExponent,

where maxExponent is the exponent of max(x, y). Delta can then be substituted for epsilon in the code snippets above.

The routine fcmp() in this package implements Knuth's comparison operators. Given a value for epsilon, and two float or double numbers x and y, it returns 1 if x is determined to be greater than y, 0 if x equals y, and -1 if x is less than y. (The routine automatically converts floats to doubles, since there is no single-precision equivalent for the standard C routines frexp() and ldexp(). However, it works for both floats and doubles, without modification.)

DETERMINING EPSILON

Now that we have found a way to scale epsilon to work with a wide range of x and y, we still need to choose an appropriate epsilon, before scaling.

If the number of binary digits of error, e, is known, then epsilon can be calculated as follows:

epsilon = (pow(2, e) - 1) * FLT_EPSILON (for floats) epsilon = (pow(2, e) - 1) * DBL_EPSILON (for doubles)

FLT_EPSILON and DBL_EPSILON are equivalent to 1 ulp for single- and double-precision numbers, respectively; they are defined in the standard C header file <float.h>. (An ulp is one unit in the last place of the significand, or fraction part, of a floating point number; see Knuth[1] for more details.)

Returns

-1 if x <  y
 0 if x == y
 1 if x >  y

Copyright

Copyright (c) 1998-2000 Theodore C. Belding
University of Michigan Center for the Study of Complex Systems

Bibliography

[1] Knuth, Donald E. (1998). The Art of Computer Programming. Volume 2: Seminumerical Algorithms. Third edition. Section 4.2.2, p. 233. Reading, MA: Addison-Wesley. ISBN 0-201-89684-2.


fdim

Function: fdim

Synopsis
#include <math.h>
long double fdiml(long double,long double);
double fdim(double,double);
float fdimf(float,float);
#include <qfloat.h>
qfloat fdimq(qfloat,qfloat);

Description

The fdim functions determine the positive difference between their arguments.

fdim(x, y)
{
    if (x > y)
        return x - y;
    return 0.0;
}


feclearexcept

Function: feclearexcept

Synopsis
#include <fenv.h>
int feclearexcept(int);

Description

The feclearexcept function clears the supported floating point exceptions represented by its argument. The result value is one if the int argument is different than zero, zero otherwise.

Several exceptions can be cleared in one call by using the OR operator between them.

Example:

feclearexcept(FE_INVALID);


fegetenv

Function: fegetenv

Synopsis
#include <fenv.h>
void fegetenv(fenv_t *envp);

The fegetenv function stores the current floating-point environment in the object pointed to by envp.

The layout of the fenv_t type is described in fpenv.h


fegetenv

Function: feholdexcept

Synopsis
#include <fenv.h>
int feholdexcept(fenv_t *envp);

The feholdexcept function saves the current floating-point environment in the object pointed to by envp, clears the floating-point status flags, and then installs a non-stop (continue on floating-point exceptions) mode, for all floating-point
exceptions.

Returns

The feholdexcept function returns zero.


fegetenv

Function: feraiseexcept

Synopsis
#include <fenv.h>
int feraiseexcept(int mask);

the feraiseexcept function raises the indicated exception given by its integer argument mask. The result is always zero.


fesetenv

Function: fesetenv

Synopsis
#include <fenv.h>
void fesetenv(fenv_t *envp);

Description

The fesetenv function establishes the floating-point environment represented by the object pointed to by envp. The argument envp shall point to an object set by a call to fegetenv or feholdexcept. Note that fesetenv merely installs the state of the floating-point status flags represented through its argument, and does not raise these floating-point exceptions.

The layout of the fenv_t type is described in fpenv.h


fegetenv

Function: fesetexceptflag

Synopsis
#include <fenv.h>
int fesetexceptflag(int mask);

The feraiseexcept function raises the indicated exception given by its integer argument mask. The result is always zero.

This function only sets the flags, and it doesn't execute an FWAIT instruction to test if there was a pending exception.

To set the flags and test for a pending exception use the feraiseexcept function


fesetround

Function: fesetround

Synopsis

#include <fenv.h>

void fesetround(int);

Description

The fesetround function establishes the rounding direction represented by its argument round. If the argument is not equal to the value of a rounding direction macro, the rounding direction is not changed.

The rounding directions are:

#define FE_DOWNWARD 1

#define FE_TONEAREST 0

#define FE_TOWARDZERO 3

#define FE_UPWARD 2

Returns

The fesetround function returns a zero value if and only if the argument is equal to a rounding direction macro (that is, if and only if the requested rounding direction was established).


finite

Function: finite

Synopsis
#include <math.h>
int finite(double x);

Description

The finite function computes if the double value x is finite.

Returns

The finite function returns 1 if x is finite, zero otherwise.


FloatPrecision

Function: FloatPrecision

Synopsis
#include <fenv.h>
int FloatPrecision(void);

Description

Sets the precision of the FPU to single precision (23 bits).

Returns

Returns the old setting of the precision flags.

See also:

DoublePrecision

FullPrecision


floor

Function: floor

Synopsis
#include <math.h>
long double floorl(long
    double x);
double floord(double x);
float floorf(float x);
double floor(double x);
double floori(int x);
#include <qfloat.h>
qfloat floorq(qfloat x);

Description

The floor functions compute the largest integer value not greater than x:

Returns

The floor functions return the largest integer value not greater than x, expressed as a floating-point number.

The macro floor(x) will compute the largest integer value not greater than x for any of the three floating point types, float, double and long double and integer type.


fmax

Function: fmax fmaxl fmaxf fmaxq

Synopsis
#include <math.h>
long double fmaxl(long
    double x, long double y);
double fmax(double x, double y);
float fmaxf(float x, float y);
qfloat fmaxq(qfloat &x,qfloat &y);

Description

The fmax functions determine the maximum numeric value of their arguments.

Returns

The fmax functions return the maximum numeric value of their arguments.

Note: NaN arguments are treated as missing data: if one argument is a NaN and the other numeric, then the fmax functions choose the numeric value.


fmod

Function: fmod

Synopsis
#include <math.h>
double fmod(double x, double y);
long double fmodl(long double x, long double y);
float fmodf(float x, float y);
qfloat fmodq(qfloat x,qfloat y);

Description

The fmod functions compute the floating-point remainder of x / y.

Returns

The fmod functions return the value x # ny, for some integer n such that, if y is nonzero, the result has the same sign as x and magnitude less than the magnitude of y. If y is zero, whether a domain error occurs or the fmod functions return zero is implementation-defined.

Under lcc-win32 the result is a quiet NAN.


fpclassify

Function: fpclassify

Synopsis
#include <math.h>
int fpclassl(long double x);
int fpclassd(double x);
int fpclassf(float x);
int fpclassify(x);

Description

The fpclassify function returns an integer that represents the different forms of classifying the given floating point value.

This values (defined in math.h) are:

FPCLASS_NAN | NaN Not a number
FPCLASS_PDENORMAL | Positive denormal number
FPCLASS_NDENORMAL | Negative denormal number
FPCLASS_NZERO | Negative zero (-0)
FPCLASS_ZERO | Positive zero (+0)
FPCLASS_PNORMAL | Positive normal number
FPCLASS_NNORMAL | Negative normal number
FPCLASS_NINFINITY | Negative infinity (-INF)
FPCLASS_PINFINITY | Positive infinity (+INF)

Returns

The classification of its argument x.

Portability

Windows (x86 specific).


rand

Function: frand

Synopsis
#include <stdlib.h>
double frand(void);

Description

The frand function computes a sequence of pseudo-random numbers in the range from 0 to 1.

Returns

The frand function returns a pseudo-random number.

See also:

rand

Credits:

The author of this implementation is George Marsaglia. Here is the message he published in sci.math.num-analysis presenting his work:

To produce, in the unit interval 0<=x<1, a double precision random variable x under the IEEE 754 standard, you need to provide, in effect, the floating point version of a ratio k/2^53 for some random k of 53 or fewer bits.

It is possible, as in the version I reported here, (Nov 18) based on ``The 64-bit universal RNG", (2004) Statistics and Probability Letters v.66 No. 2, 183-187, to do this using only floating point addition and subtraction so that exactly the same results are produced for a variety of platforms and programming languages.

But if you have a good routine for producing random integers, it is relatively easy to use them to produce IEEE double precision x's: For example, if rand() produces unsigned 32-bit integers, then

x=(2097152.*rand( )+(rand( )>>11))/9007199254740992.;

will work in C.

(The floating point constants above are 2.^21, 2.^53 and 2.^22.)

Of course, if you want a good x from this method, you need a good source of 31- or 32-bit random integers. The rand( ) functions available with most C compilers are not very good.

My favorite, unless I want to use one of the MWC or CMWC RNGs with massive periods, but requiring hundreds to thousands of seeds, is KISS( ), the Keep It Simple Stupid RNG that combines congruential, xorshift and lag-1 multiply-with-carry sequences:

unsigned long KISS(void)
{
    static unsigned long x=123456789,y=362436000,z=521288629,c=7654321;
    unsigned long long t, a=698769069LL;
    x=69069*x+12345;
    y^=(y<<13); y^=(y>>17); y^=(y<<5);
    t=a*z+c; c=(t>>32);
    return x+y+(z=t);
}

Tke KISS RNG requires four seeds, the initial x,y,z and c. It has period > 2^124 and passes all the tests I have put to it, particularly the newer version of the Diehard battery with some tough new tests, http://www.csis.hku.hk/~diehard/

George Marsaglia


frexp

Function: frexp

Synopsis
#include <math.h>
double frexp(double value, int *exp);
long double frexpl(long double value,int *exp);
qfloat frexpq(qfloat value,int *exp);

Description

The frexp functions break a floating-point number into a normalized fraction and an integral power of 2. They store the integer in the int object pointed to by exp.

Returns

The frexp functions return the value x, such that x has a magnitude in the interval [1/2, 1] or zero, and value equals x * 2^exp. If value is zero, both parts of the result are zero.


FullPrecision

Function: FullPrecision

Synopsis
#include <fenv.h>
int FullPrecision(void);

Description

Sets the precision of the FPU to long double precision (64 bits).

Returns

Returns the old setting of the precision flags.

See also:

DoublePrecision

FloatPrecision


hypot

Function: hypot

Synopsis
#include <math.h>
long double hypotl(long double x,long double y);
double hypot(double x, double y);
float hypotf(float x, float y);
qfloat hypotq(qfloat x,qfloat y);

Description

The hypot functions compute the square root of the sum of the squares of x and y, without undue overflow or underflow. A range error may occur.

To maintain compatibility with Microsoft's compilers, lcc-win32 defines _hypot as an alternative equivalent name for hypot.

Returns

The hypot functions return the value of the square root of the sum of the squares.

Example
#include <math.h>
#include <stdio.h>
int main( void )
{
    double x = 6.0, y = 4.0;
    printf( "If a right triangle has sides %2.1f and %2.1f, "
        "its hypotenuse is %2.1f\n", x, y, hypot( x, y ) );
}
Output:
If a right triangle has sides 6.0 and 4.0, its hypotenuse is 7.2


ilogb

Function: ilogb

Synopsis
#include <math.h>
int ilogb(double x);

Description

The ilogb functions extract the exponent of x as a signed int value.

If x is zero they compute the value FP_ILOGB0; if x is infinite they compute the value INT_MAX; if x is a NaN they compute the value FP_ILOGBNAN; otherwise, they are equivalent to calling the corresponding logb function and casting the returned value to type int.

A range error may occur if x is 0.

Returns

The ilogb function returns the exponent of x as a signed int value.


imaxdiv

Function: imaxdiv

Synopsis
#include <inttypes.h>
imaxdiv_t imaxdiv(intmax_t numer,intmax_t denom);

Description:

The imaxdiv function computes numer / denom and numer % denom in a single operation.

Under lcc-win32 the type intmax_t is a long long, and the result is a structure of two 64 bit integers.


isfinite

Function: isfinite

Synopsis
#include <math.h>
int isfinted(double x);
int isfinitef(float x);
int isfinitel(long double x);

Description

The isfinite functions determine if the floating point value x is a finite value. (zero, subnormal, or normal, and not infinite or NaN).

Returns

The isfinite functions return a nonzero value if and only if its argument has a finite value.

The isfinite(x) macro takes any of the three floating point types as its argument.


tanh

Function: isgreater

Synopsis
#include <math.h>
int isgreater(long double x,long double y);

Description

The isgreater macro returns 1 if x > y, zero otherwise. This macro doesn't raise the "invalid" floating point exception when one of its arguments is a NAN

Returns

This macro returns 1 if x > Y


isinf

Function: isinf

Synopsis
#include <math.h>
int isinf(double x);

Description

The isinf function determine if the floating point value x is an infinite value.

Returns

The isinf function returns a nonzero value if and only if its argument has an infinite value.


tanh

Function: isless

Synopsis
#include <math.h>
int isless(long double x,long double y);

Description

The isless macro returns 1 if x < y, zero otherwise. This macro doesn't raise the "invalid" floating point exception when one of its arguments is a NAN

Returns

This macro returns 1 if x < Y


tanh

Function: islessequal

Synopsis
#include <math.h>
int islessequal(long double x,long double y);

Description

The islessequal macro returns 1 if x <= y, zero otherwise. This macro doesn't raise the "invalid" floating point exception when one of its arguments is a NAN

Returns

This macro returns 1 if x <= Y


tanh

Function: islessgreater

Synopsis
#include <math.h>
int islessgreater(long double x,long double y);

Description

The islessgreater macro returns 1 if x != y, zero otherwise. This macro doesn't raise the "invalid" floating point exception when one of its arguments is a NAN

Returns

This macro returns 1 if x != Y


isnan

Function: isnan

Synopsis
#include <math.h>
int isnand(double x);
int isnanl(long double x);
int isnanf(float x);

Description

The isnan functions determine if the floating point value x is a Nan value. (not a number)

Returns

The isnan functions return a nonzero value if and only if its argument is a NaN.

The isnan(x) macro takes any of the three floating point types as its argument.


isnormal

Function: isnormal

Synopsis
#include <math.h>
int isnormal(x);

Description

The isnormal macro determines whether its argument value is normal (neither zero, subnormal, infinite, nor NaN).

Returns

First, an argument represented in a format wider than its semantic type is converted to its semantic type. Then determination is based on the type of the argument.

Returns

The isnormal macro returns a nonzero value if and only if its argument has a normal value.


iso646.h

Function: iso646.h

The header <iso646.h> defines the following eleven macros
#define and &&
#define and_eq &=
#define bitand &
#define bitor |
#define compl ~
#define not !
#define not_eq !=
#define or ||
#define or_eq |=
#define xor ^
#define xor_eq ^=


tanh

Function: isunordered

Synopsis
#include <math.h>
int isunordered(long double x,long double y);

Description

The isunordered macro returns 1 if x is a NAN or y is a NAN, zero otherwise. This macro doesn't raise the "invalid" floating point exception when one of its arguments is a NAN

Returns

This macro returns 1 if x ==NAN || y == NAN


ldexp

Function: ldexp

Synopsis
#include <math.h>
double ldexp(double x, int exp);
long double ldexpl(long double x, int exp);
#include <qfloat.h>
qfloat ldexpq(qfloat x, int exp);

Description

The ldexp functions multiply a floating-point number by an integral power of 2. A range error may occur.

Returns

The ldexp functions return the value of x * 2^exp .

Example
#include <math.h>
#include <stdio.h>
int main( void )
{
    double x = 3.0, y;
    int p = 4;
    y = ldexp( x, p );
    printf( "%2.1f times two to the power of %d is %2.1f\n", x, p, y );
}

3.0 times two to the power of 4 is 48.0


ldtoa

Function: ldtoa

Synopsis
#include <math.h>
void ldtoa(long double value, char * str);

Description

The ldtoa function converts the digits of the given long double value argument to a null-terminated character string and stores the result in str.

 Returns

No return value


lgamma

Function: lgamma

Synopsis
#include <math.h>
double lgamma(double x);
long double lgammal(long double x);
float lgammaf(float x);
#include <qfloat.h>
qfloat lgammaq(qfloat x);

Description

The lgamma functions compute the natural logarithm of the absolute value of gamma of x. An error occurs if x is too large or if x is a negative number or zero.

Returns

The lgamma function returns the value of the natural logarithm of the absolute value of gamma of x.


log

Function: clog

Synopsis
#include <complex.h>
double complex clog(double complex x);
long double complex clogl(long double complex x);
float complex clogf(float complex x);
#include <qfloat.h>
qfloat complex clogq(qfloat complex x);

Description

The clog function compute the complex base-e (natural) logarithm of x.

Returns

The log function return the base-e logarithm value.

The clog(x) generic function takes any of the three floating point types or an integer argument.


log10

Function: log10

Synopsis
#include <math.h>
double log10(double x);
long double log10l(long double x);
float log10f(float);

Description

The log10 functions compute the base-10 (common) logarithm of x. A domain error occurs if the argument is negative. A range error may occur if the argument is zero.

Returns

The log10 functions return the base-10 logarithm value.

Example
#include <math.h>
#include <stdio.h>
int main( void )
{
    double x = 9000.0;
    double y;
    y = log( x );
    printf( "log( %.2f ) = %f\n", x, y );
    y = log10( x );
    printf( "log10( %.2f ) = %f\n", x, y );
}

log( 6000.00 ) = 8.699515
log10( 6000.00 ) = 3.778151


log

Function: log1p

Synopsis
#include <math.h>
float log1pf(float x);
long double log1pl(long double x);
double log1p(double x);
#include <qfloat.h>
qfloat log1pq(qfloat x);

Description

The log1p functions compute the logarithm of 1+x. A domain error occurs if the argument is negative. A range error may occur if the argument is 1.

Returns

The log function returns log(1+ x) calculated in such a way to be accurate when x is near zero.


log

Function: log2

Synopsis
#include <math.h>
double log2(double x);
long double log2l(long double);
float log2f(float);

Description

The log2 function compute the base-2 logarithm of x. A domain error occurs if the argument is negative. A range error may occur if the argument is zero.

Returns

The log function returns 2 ** x

Example
#include <math.h>
#include <stdio.h>
int main( void )
{
    double x = 9000.0;
    double y;
    y = log2( x );
    printf( "log2( %.2f ) = %f\n", x, y );
}

log2( 9000.00 ) = 13.135709


logb

Function: logb logbf logbl

Synopsis
#include <math.h>
double logb(double x);
long double logbl(long double x);
float logbf(float x);

Description

The logb functions extract the exponent of x, as a signed integer value in floating-point format. If x is subnormal it is treated as though it were normalized; thus, for positive finite x,

1 <= x * FLT_RADIX to the power of -logb(x) < FLT_RADIX

A domain error may occur if the argument is zero.

Returns

The logb functions return the signed exponent of x.


ilogb

Function: _lrotl

Synopsis
#include <stdlib.h>
int _stdcall _lrotl(unsigned int a,unsigned bits);
#include <intrinsics.h>
int _stdcall _lrotl(unsigned a,unsigned bits);

Description

The _lrotl function rotates the given integer a the number of specified bits to the left. Bits that overflow the 32 bits are reintroduced at the lower end.

This function is an intrinsic function, meaning that actually no function call is generated. Instead, a single assembly instruction will be emitted that performs the required operation.

Returns

The _lrotl function returns the rotated integer


ilogb

Function: _lrotr

Synopsis
#include <stdlib.h>
int _stdcall _lrotr(unsigned int a,unsigned bits);

Description

The _lrotr function rotates the given integer a the number of specified bits to the right. Bits that overflow the 32 bits are reintroduced at the upper end.

This function is an intrinsic function, meaning that actually no function call is generated. Instead, a single assembly instruction will be emitted that performs the required operation.

Returns

The _lrotr function returns the rotated integer.


matherr

Function: matherr

Synopsis
#include <math.h>
int matherr(struct exception *except);

Description

The matherr function processes errors generated by the floating-point functions of the math library. These functions call matherr when an error is detected.

For special error handling, you can provide a different definition of matherr.

If you use the dynamically linked version of the C run-time library (CRTDLL.DLL), you can NOT replace the default matherr routine in a client executable with a user-defined version. To replace it you should link with the "fdlibm" math library, i.e. you should use the statically linked math library.

When an error occurs in a math routine, matherr is called with a pointer to an exception type structure (defined in MATH.H) as an argument. The exception structure contains the following elements:

struct exception
{
    int type;
    char *name;
    double arg1;
    double arg2;
    double retval;
    int err;
};

int type                Exception type

char *name              Name of function where error occurred

double arg1, arg2       First and second (if any) arguments to function

double retval           Value to be returned by function. The type specifies
                      the type of math error. It is one of the following
                      values, defined in MATH.H:

    DOMAIN         Argument domain error.

    SING           Argument singularity.

    OVERFLOW       Overflow range error.

    PLOSS          Partial loss of significance.

    TLOSS          Total loss of significance.

The structure member name is a pointer to a null-terminated string containing the name of the function that caused the error. The structure members arg1 and arg2 specify the values that caused the error. (If only one argument is given, it is stored in arg1.)

The default return value for the given error is retval. If you change the return value, it must specify whether an error actually occurred.

Returns

matherr returns 0 to indicate an error or a non-zero value to indicate success.

If matherr returns 0, an error message can be displayed, and errno is set to an appropriate error value. If matherr returns a nonzero value, no error message is displayed, and errno remains unchanged.


modf

Function: modf

Synopsis
#include <math.h>
double modf(double value, double *iptr);
long double modfl(long double value, long double *iptr);
#include <qfloat.h>
qfloat modfq(qfloat value, qfloat *iptr);

Description

The modf functions break the argument value into integral and fractional parts, each of which has the same type and sign as the argument. It stores the integral part (in floating-point format) in the object pointed to by iptr.

Returns

The modf functions return the value of the signed fractional part of value.

Example
/* MODF.C */
#include <math.h>
#include <stdio.h>
int main( void )
{
    double x, y, n;
    x = -23.97766553; /* Divide x into its fractional */
    y = modf( x, &n ); /* and integer parts */
    printf( "For %f, the fraction is %f and the integer is %.f\n",
            x, y, n );
}

Output

For -23.977666, the fraction is -0.977666 and the integer is 23


nan

Function: nan

Synopsis
#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);

Description

The call nan("n-char-sequence") is equivalent to strtod("NAN(n-char-sequence)", (char**) NULL); the call nan("") is equivalent to strtod("NAN()", (char**) NULL). If tagp does not point to an n-char sequence or an empty string, the call is equivalent to strtod("NAN", (char**) NULL). Calls to nanf and nanl are equivalent to the corresponding calls to strtof and strtold.

Returns

The nan functions return a quiet NaN, if available, with content indicated through tagp.

If the implementation does not support quiet NaNs, the functions return zero.


nearbyint

Function: nearbyint

Synopsis
#include <math.h>
double nearbyint(double x);
long double nearbyintl(long double x);
float nearbyintf(float x);

Description

The nearbyint functions use IEC 60559 rounding according to the current rounding direction. They do not raise the inexact floating-point exception if the result differs in value from the argument.

Returns

The nearbyint functions return the nearest int value according to the current rounding direction.


nextafter

Function: nextafter

Synopsis
#include <math.h>
double nextafter(double x, double y);

Description

The nextafter function determines the next representable value, in the type of the function, after x in the direction of y, where x and y are first converted to the type of the function. The nextafter functions return y if x equals y. A range error may occur if the magnitude of x is the largest finite value representable in the type and the result is infinite or not representable in the type.

Returns

The nextafter functions return the next representable value in the specified format after x in the direction of y.


pow

Function: pow

Synopsis
#include <math.h>
double pow(double x, double y);
long double powl(long double x,long double y);
double powd(double x,double y);
long double powlli(long double x, int y);
double powdi(double x, int y);
double powii(int x, int y);
long double powlld(long double x, double y);
long double powlli(long double x, int y);
long double powdll(double x, long double y);
long double powill(int x, long double y);
double powid(int x, double y);
#include <qfloat.h>
qfloat powq(qfloat x,qfloat y);

Description

The pow functions compute x raised to the power y. A domain error occurs if x is negative and y is finite and not an integer value. A domain error occurs if the result cannot be represented when x is zero and y is less than or equal to zero. A range error may occur.

Returns

The pow functions return the value of x raised to the power y.

The pow(x,y) macro can be used in place of the above functions.

Example
#include <math.h>
#include <stdio.h>
int main( void )
{
    double x = 2.0, y = 32.0, z;
    z = pow( x, y );
    printf( "%.1f to the power of %.1f is %.1f\n", x, y, z );
}

Output:
2.0 to the power of 32.0 is 4294967296.0


rand

Function: rand

Synopsis
#include <stdlib.h>
int rand(void);

Description

The rand function computes a sequence of pseudo-random integers in the range 0 to RAND_MAX.Lcc-win32 defines RAND_MAX to 0xFFFF in stdlib.h

Returns

The rand function returns a pseudo-random integer.

See also:

The Mersenne twister random number generator.

frand, floating point random numbers


abs

Function: remquo remquof remquol

Synopsis
#include <math.h>
float remquof(float x,float y,int *prem);
double remquo(double x,double y,int *prem);
long double remquol(long
    double x,long double y,int *prem);
#include <qfloat.h>
qfloat remquoq(qfloat &,qfloat &,int *prem);

Description

The remquo, functions compute the same remainder as the remainder functions. In the object pointed to by quo they store a value whose sign is the sign of x/y and whose magnitude is the magnitude of the integral quotient of x/y.

Returns

Returns x REM y

Example
#include <stdio.h>
#include <math.h>
int main(void)
{
    int i;
    double d;
    long double ld;
    d = remquo(81.3,5.755,&i);
    printf("remquo(81.3,5.755) = %g %d\n",d,i);
    return 0;
}

produces

remquo(81.3, 5.755) = 0.73 3


rint

Function: rint

Synopsis
#include <math.h>
double rint(double x);
long double rintl(long double);
float rintf(float);

Description

The rint functions round its argument to an integer value in floating-point format, using the current rounding direction. Under lcc-win32 this function is implemented as an intrinsic macro.

Returns

The rint functions returns the rounded integer value.

Example
#include <math.h>
#include <stdio.h>
int main(void)
{
    double value = 8.677;
    printf("The rounded value of %g is %g\n",value,rint(value));
}

The rounded value of 8.677 is 9


scalbn

Function: scalbn

Synopsis
#include <math.h>
float scalbnf(float x,int n);
double scalbn(double x, int n);
long double scalbnl(long double,int n);
qfloat scalbnq(qfloat x,int n);

Description

The scalbn functions compute x times FLT_RADIX to the nth power efficiently, not normally by computing FLT_RADIX to the nth power explicitly. A range error may occur.

Returns

The scalbn function returns the value of x times FLT_RADIX to the nth power.

Example
#include <math.h>
#include <stdio.h>
int main(void)
{
    double d = 3.0;
    double r;
    int i;
    for (i=0; i<5;i++) {
        r = scalbn(d,i);
        printf("%g",r);
    }
    return 0;
}

This program will output:
3
6
12
24
48


signbit

Function: signbit

Synopsis
#include <math.h>
int signbit(double x);
int signbitq(qfloat x);

Description

The signbit function determines whether the sign of its argument value is negative.

Returns

The signbit function returns a nonzero value if and only if the sign of its argument value is negative.


sin

Function: sin sinl sinf sinq

Synopsis
#include <math.h>
double sin(double x);
long double sinl(long double x);
float sinf(float x);
qfloat sinq(qfloat &x);

Description

The sin function computes the sine of x (measured in radians).

Returns

The sin functions return the sine value.

If you use the optimization option within lcc-win32 this function will be always inlined.


sinh

Function: sinh

Synopsis
#include <math.h>
double sinh(double x);
long double sinhl(long double x);
#include <qfloat.h>
qfloat sinhq(qfloat x);

Description

The sinh functions compute the hyperbolic sine of x. A range error occurs if the magnitude of x is too large.

sinh x = (ex - ex) / 2

Returns

The sinh functions return the hyperbolic sine value.


sqrt

Function: sqrt

Synopsis
#include <math.h>
double sqrt(double x);
double sqrtd(double x);
double sqrtid(int x);
float sqrtf(float x);
double sqrt(double x);
double sqrti(int x);
long double sqrtl(long double x);
#include <qfloat.h>
qfloat sqrtq(qfloat x);

The sqrt(x) generic function can be used instead of the above functions.

Description

The sqrt functions compute the non-negative square root of x. A domain error occurs if the argument is less than zero.

Returns

The sqrt functions return the value of the square root.

Example
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
    double input = 78.23, answer;
    answer = sqrt( input );
    if( input < 0 )
        printf( "Error: sqrt returns %.2f\n, answer" );
    else
    printf( "The square root of %.2f is %.2f\n", input, answer );
}
The square root of 78.23 is 8.84


srand

Function: srand

Synopsis
#include <stdlib.h>
void srand(unsigned int seed);

Description

The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand.Ifsrand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.

Returns

The srand function returns no value.

See also:

The Mersenne Twister random number generator.


tan

Function: tan tanl tanf tanq

Synopsis
#include <math.h>
double tan(double x);
long double tanl( long double x);
float tanf(float x);
#include <qfloat.h>
qfloat tanq(qfloat x);

Description

The tan functions return the tangent of x (measured in radians).

Returns

The tan function returns the tangent value.


tanh

Function: tanh

Synopsis
#include <math.h>
double tanh(double x);
long double tanhl(long double);
#include <qfloat.h>
qfloat tanhq(qfloat x);

Description

The tanh functions compute the hyperbolic tangent of x.

Returns

The tanh functions return the hyperbolic tangent value.

tanh x = sinh(x) / cosh(x)


Advanced mathematical functions

This set of functions aren't included in the C standard, but they are useful in many engineering contexts. When necessary, the mathematical formula for those functions is included.


scalbn

Function: airy

Synopsis
#include <math.h>
int airy(double x,double *ai,double *aip,double *bi,double *bip);
int airyq(qfloat &x,qfloat &ai,qfloat &aip,qfloat &bi,qfloat &bip);

Description

Solution of the differential equation

y"(x) = xy.

The function returns the two independent solutions Ai, Bi and their first derivatives Ai'(x), Bi'(x).

Returns

Returns zero if OK, -1 if x is bigger than 25.77.

Example

#include <math.h>
#include <stdio.h>
int main(void)
{
    double ai,aip,bi,bip;
    qfloat x=1.6Q,aiq,aipq,biq,bipq;
    airy(1.6,&ai,&aip,&bi,&bip);
    airyq(x,aiq,aipq,biq,bipq);
    printf("AiryAi(1.6)=%18.15g\n %70.68qg\n",ai,aiq);
    printf("AiryBi(1.6)=%18.15g\n %70.68qg\n",bi,biq);
    printf("AiryAiPrime(1.6)=%18.15g\n %70.68qg\n",aip,aipq);
    printf("AiryBiPrime(1.6)=%18.15g\n %70.68qg\n",bip,bipq);
}

Output:

AiryAi(1.6)= 0.06253690796893
0.0625369079689319603258386961740431655509807023207210257365559293785407
AiryBi(1.6)= 2.08247417125411
2.08247417125411188974284208737288212028761947167121303202886918597387
AiryAiPrime(1.6)= -0.0869959084481
-0.0869959084481041318083989233031482700546359536650151102642783498096191
AiryBiPrime(1.6)= 2.19299543725377
2.19299543725376537136452165484038009499766829774670793020408864908738

Credits

Stephen L Moshier. Cephes mathematical library.


cos

Function: dbesi0

Synopsis
#include <math.h>
double dbesi0(double x);

Description

Computes the hyperbolic Bessel function of the first kind of order zero.

Returns

Returns the hyperbolic bessel function first kind, order zero.


cos

Function: dbesi1

Synopsis
#include <math.h>
double dbesi1(double x);

Description

Computes the hyperbolic Bessel function of the first kind of order one.

Returns

Returns the hyperbolic bessel function first kind, order one.


asinh

Function: ellipticEl

Synopsis
#include <math.h>
long double ellipticEl(long double x,long double v);

Description

The ellipticE function compute the incomplete elliptic integral of the second kind.

The incomplete elliptic integral of the second kind E is

Equivalently, using alternate notation,

Additional relations include

Returns

The evaluation of the integral.

Example:

#include <math.h>
#include <stdio.h>

int main(void)
{
  printf("x           0.2              0.4             0.6             0.8            1.0");
  for(double x=0.1; x<1.0; x+=0.1)
  {
    printf("\n%3.1lf|",x);
    for(double v=0.2;v<=1.0;v+=0.2)
      printf(" %16.12Lf", ellipticEl(x,v));
  }
  return 0;
}

Output:

x           0.2              0.4             0.6             0.8            1.0
0.1|   0.099966723310   0.099933426673   0.099900110045   0.099866773384   0.099833416647
0.2|   0.199735143707   0.199469654125   0.199203525812   0.198936753241   0.198669330795
0.3|   0.299113719130   0.298222693068   0.297326829772   0.296426033905   0.295520206661
0.4|   0.397924309134   0.395828999590   0.393713392128   0.391576763538   0.389418342309
0.5|   0.496008565751   0.491958744671   0.487847363876   0.483670922408   0.479425538604
0.6|   0.593233925648   0.586327087837   0.579268421596   0.572045170254   0.564642473395
0.7|   0.689499027770   0.678705356003   0.667587549814   0.656107429902   0.644217687238
0.8|   0.784738348076   0.768931915835   0.752504126836   0.735356205180   0.717356090900
0.9|   0.878925809810   0.856922357007   0.833824464229   0.809404117842   0.783326909627
1.0|   0.972077101536   0.942678364952   0.911481631071   0.878007790698   0.841470984808

Credits:

Stephen Moshier and his CEPHES Mathematical Library.

The equations are from the free encyclopedia Wikipedia:

http://en.wikipedia.org/wiki/Elliptic_integral


abs

Function: ellipticK

Synopsis
#include <stats.h>
long double ellipticKl(long double z);
double ellipticK(double z);
qfloat ellipticKq(qfloat &z);

Description

Calculates the complete elliptic integral of the first kind. Its formula is:

Returns

The evaluated integral.

Notes:

The implementation of this function is derived from the one in the Cephes mathematical library.


lgamma

Function: igamma

Synopsis
#include <math.h>
double igamma(long double a, long double x);
#include <qfloat.h>
qfloat igammaq(qfloat &x);

Description

The gamma functions compute the value of the incomplete gamma function at a, of x.

Both a and x must be positive.

Returns

The igamma function returns the value of the incomplete gamma function at a of x.


frexp

Function: hypergeom

Synopsis
#include <math.h>
double hypergeom(double a, double b, double x);
qfloat hypergeomq(qfloat &a,qfloat &b,qfloat &x);

Description

The hypergeom functions compute the confluent hypergeometric function for

Returns

The value of the series


frexp

Function: hypergeom2f1

Synopsis
#include <math.h>
long double hypergeom2f1(long double a,long double b,long double x);
qfloat hypergeom2f1(qfloat &a,qfloat &b,qfloat &x);

Description

The hypergeom2f1 function computes the confluent hypergeometric function for

Some special values of this function:

hypergeom2f1(0.5,0.5,1.5,x*x) == asin(x)/x

Returns

The value of the series


asinh

Function: j0

Synopsis
#include <math.h>
#include <qfloat.h>
long double j0l(long double x);
double j0(double x);
qfloat j0q(qfloat x);

Description

The j0 functions compute the Bessel functions of the first kind of x of order zero.

Returns

The bessel function of the first kind of x order zero.


asinh

Function: j1

Synopsis
#include <math.h>
#include <qfloat.h>
long double j1l(long double x);
double j1(double x);
qfloat j1q(qfloat x);

Description

The j1 functions compute the Bessel functions of the first kind of x of order one.

Returns

The bessel function of the first kind of x order one.


asinh

Function: jn

Synopsis
#include <math.h>
#include <qfloat.h>
long double jnl(int n,long double x);
double jn(int n,double x);
qfloat jnq(qfloat n,qfloat x);

Description

The jn functions compute the Bessel functions of the first kind of x of order n.

Returns

The bessel function of the first kind of x order n.


scalbn

Function: jv

Synopsis
#include <math.h>
double jv(double n,double z);

Description

Bessel function of noninteger order.

Returns

Returns Bessel function of order v of the argument, where v is real. Negative z is allowed if v is an integer.

Credits

Stephen L Moshier. Cephes mathematical library.


scalbn

Function: psi

Synopsis
#include <math.h>
int psi(double x);
qfloat psiq(qfloat);

Description

The psi function is defined by

One formula is:

Returns

The value of the psi function or HUGE_VAL if the argument is a negative integer or zero.

Example

#include <math.h>
#include <stdio.h>
int main(void)
{
    double d = psi(1.6);

    printf("psi(1.6)=%18.15f\n",d);
}

Output:
psi(1.6)= 0.126047452773480

Credits

Stephen L Moshier. Cephes mathematical library.


scalbn

Function: struve

Synopsis
#include <math.h>
double struve(double v,double x);
qfloat struveq(qfloat v,qfloat x);

Description

Computes the Struve function Hv(z) of order v, argument z.
Negative z is rejected unless v is an integer.

Returns

The value of the Struve function.

Credits

Stephen L. Moshier. Cephes Mathematical Library


asinh

Function: y0

Synopsis
#include <math.h>
#include <qfloat.h>
long double y0(long double x);
qfloat y0q(qfloat x);

Description

The y0 functions compute the Bessel functions of the second kind of x of order zero.

Returns

The bessel function of the second kind of x.


asinh

Function: y1

Synopsis
#include <math.h>
#include <qfloat.h>
long double y1(long double x);
qfloat y1q(qfloat x);

Description

The y1 functions compute the Bessel functions of the second kind of x of order one.

Returns

The bessel function of the second kind of x, order one.


asinh

Function: yn

Synopsis
#include <math.h>
#include <qfloat.h>
long double yn(int n,long double x);
qfloat ynq(qfloat n,qfloat x);

Description

The yn functions compute the Bessel functions of the second kind of x of order n.

Returns

The bessel function of the second kind of x, order n.


asin

Linear algebra functions

In the descriptions below, matrices are represented by capital letters, vectors by lower case letters and scalars by alpha.

Function      Description

band2mat      Convert band matrix to dense matrix
bd_free       Deallocate (destroy) band matrix
bd_get        Allocate and initialize band matrix
bd_transp     Transpose band matrix
bd_resize     Resize band matrix
bdLDLfactor   Band LDL^T factorization
bdLDLsolve    Solve Ax=b using band LDL^T factors
bdLUfactor    Band LU factorization
bdLUsolve     Solve Ax=b using band LU factors
bisvd         SVD of bi-diagonal matrix
BKPfactor     Bunch-Kaufman-Parlett factorization
BKPsolve      Bunch-Kaufman-Parlett solver
catch()       Catch a raised error (macro)
catchall()    Catch any raised error (macro)
catch_FPE()   Catch floating point error (sets flag)
CHfactor      Dense Cholesky factorization
CHsolve       Cholesky solver
d_save        Save real in MATLAB format
Dsolve        Solve Dx=y , D diagonal
ERRABORT()    Abort on error (sets flag, macro)
ERREXIT()     Exit on error (sets flag, macro)
error()       Raise an error (macro, see ev_err())
err_list_attach Attach new list of errors
err_list_free Discard list of errors
err_is_list_attached Checks for an error list
ev_err        Raise an error (function)
fft           Computes Fast Fourier Transform
finput        Input a simple data item from a stream
fprompter     Print prompt to stderr
get_col       Extract a column from a matrix
get_row       Extract a row from a matrix
givens        Compute Givens parameters
hhtrcols      Compute AP^T where P is a Householder matrix
hhtrrows      Compute PA where P is a Householder matrix
hhtrvec       Compute Px where P is a Householder matrix
hhvec         Compute parameters for a Householder matrix
ifft          Computes inverse FFT
in_prod       Inner product of vectors
input         Input a simple data item from stdin (macro)
iter_arnoldi  Arnoldi iterative method
iter_arnoldi_iref Arnoldi iterative method with refinement
iter_ATx      Set A^T in ITER structure
iter_Ax       Set A in ITER structure
iter_Bx       Set preconditioner in ITER structure
iter_cg       Conjugate gradients iterative method
iter_cgne     Conjugate gradients for normal equations
iter_cgs      CGS iterative method
iter_copy     Copy ITER data structures
iter_copy2    Shallow copy of ITER data structures
iter_dump     Dump ITER data structure to a stream
iter_free     Free (deallocate) ITER structure
iter_get      Allocate ITER structure
iter_gmres    GMRES iterative method
iter_lsqr     LSQR iterative method
iter_mgcr     MGCR iterative method
iter_resize   Resize vectors in an ITER data structure
iter_spcg     Sparse matrix CG method
iter_spcgne   Sparse matrix CG method for normal equations
iter_spcgs    Sparse matrix CGS method
iter_spgmres  Sparse matrix GMRES method
iter_splsqr   Sparse matrix LSQR method
iter_spmgcr   Sparse matrix MGCR method
iv_add        Add integer vectors
iv_copy       Copy integer vector
iv_dump       Dump integer vector to a stream
iv_finput     Input integer vector from a stream
iv_foutput    Output integer vector to a stream
IV_FREE       Free (deallocate) an integer vector (macro)
iv_free       Free (deallocate) integer vector (function)
iv_free_vars  Free a list of integer vectors
iv_get        Allocate and initialise an integer vector
iv_get_vars   Allocate list of integer vectors
iv_input      Input integer vector from stdin (macro)
iv_output     Output integer vector to stdout (macro)
iv_resize     Resize an integer vector
iv_resize_vars Resize a list of integer vectors
iv_sub        Subtract integer vectors
LDLfactor     LDL^T factorization
LDLsolve      LDL^T solver
LDLupdate     Update LDL^T factorization
Lsolve        Solve Lx=y , L lower triangular
LTsolve       Solve L^Tx=y , L lower triangular
LUcondest     Estimate a condition number using LU factors
LUfactor      Compute LU factors with implicit scaled partial pivoting
LUsolve       Solve Ax=b using LU factors
LUTsolve      Solve A^Tx=b usng LU factors
m_add         Add matrices
makeQ         Form Q matrix for QR factorization
makeR         Form R matrix for QR factorization
mat2band      Extract band matrix from dense matrix
MCHfactor     Modified Cholesky factorization
m_copy        Copy dense matrix
m_dump        Dump matrix data structure to a stream
m_exp         Computes matrix exponential
_m_exp        Matrix exponential
m_finput      Input matrix from a stream
m_foutput     Output matrix to a stream
M_FREE        Free (deallocate) a matrix (macro)
m_free        Free (deallocate) matrix (function)
m_free_vars   Free a list of matrices
m_get         Allocate and initialize a matrix
m_get_vars    Allocate list of matrices
m_ident       Sets matrix to identity matrix
m_input       Input matrix from stdin (macro)
m_inverse     Invert matrix
m_load        Load matrix in MATLAB format
m_mlt         Multiplies matrices
mmtr_mlt      Computes AB^T
m_norm1       Computes ||A||_1 of a matrix
m_norm_frob   Computes the Frobenius norm of a matrix
m_norm_inf    Computes ||A||_inf of a matrix
m_ones        Set matrix to all 1's
m_output      Output matrix to stdout (macro)
m_poly        Computes a matrix polynomial
m_pow         Computes integer power of a matrix
mrand         Generates pseudo-random real number
m_rand        Randomise entries of a matrix
mrandlist     Generates array of pseudo-random numbers
m_resize      Resize matrix
m_resize_vars Resize a list of matrices
m_save        Save matrix in MATLAB format
m_sub         Subtract matrices
m_transp      Transpose matrix
mtrm_mlt      Computes A^TB
mv_mlt        Computes Ax
mv_mltadd     Computes y <- Ax+y
m_zero        Zero a matrix
ON_ERROR()    Error handler (macro)
prompter      Print prompt message to stdout
px_cols       Permute the columns of a matrix
px_copy       Copy permutation
px_dump       Dump permutation data structure to a stream
px_finput     Input permutation from a stream
px_foutput    Output permutation to a stream
PX_FREE       Free (deallocate) a permutation (macro)
px_free       Free (deallocate) permutation (function)
px_free_vars  Free a list of permutations
px_get        Allocate and initialize a permutation
px_get_vars   Allocate a list of permutations
px_ident      Sets permutation to identity
px_input      Input permutation from stdin (macro)
px_inv        Invert permutation
pxinv_vec     Computes P^Tx where P is a permutation matrix
pxinv_zvec    Computes P^Tx where P is a permutation matrix (complex)
px_mlt        Multiply permutations
px_output     Output permutation to stdout (macro)
px_resize     Resize a permutation
px_resize_vars Resize a list of permutations
px_rows       Permute the rows of a matrix
px_sign       Returns the sign of the permutation
px_transp     Transpose a pair of entries
px_vec        Computes Px where P is a permutation matrix
px_zvec       Computes Px where P is a permutation matrix (complex)
QRCPfactor    QR factorization with column pivoting
QRfactor      QR factorization
QRCPsolve     Solve Ax=b
QRsolve       Solve Ax=b using QR factorization
QRTsolve      Solve A^Tx=b using QR factorization
QRupdate      Update explicit QR factors
rot_cols      Apply Givens rotation to the columns of a matrix
rot_rows      Apply Givens rotation to the rows of a matrix
rot_vec       Apply Givens rotation to a vector
rot_zvec      Apply complex Givens rotation to a vector
schur         Compute real Schur form
schur_evals   Compute eigenvalues from the real Schur form
schur_vecs    Compute eigenvectors from the real Schur form
set_col       Set the column of a matrix to a given vector
set_err_flag  Control behavior of ev_err()
set_row       Set the row of a matrix to a given vector
sm_mlt        Scalar-matrix multiplication
smrand        Set seed for mrand()
spBKPfactor   Sparse symmetric indefinite factorization
spBKPsolve    Sparse symmetric indefinite solver
spCHfactor    Sparse Cholesky factorization
spCHsolve     Sparse Cholesky solver
spCHsymb      Symbolic sparse Cholesky factorization (no floating point operations)
sp_col_access Sets up column access paths for a sparse matrix
sp_compact    Eliminates zero entries in a sparse matrix
sp_copy       Copies a sparse matrix
sp_copy2      Copies a sparse matrix into another
sp_diag_access Sets up diagonal access paths for a sparse matrix
sp_dump       Dump sparse matrix data structure to a stream
sp_finput     Input sparse matrix from a stream
sp_foutput    Output a sparse matrix to a stream
sp_free       Free (deallocate) a sparse matrix
sp_get        Allocate and initialize a sparse matrix
sp_get_val    Get the (i,j) entry of a sparse matrix
spICHfactor   Sparse incomplete Cholesky factorization
sp_input      Input a sparse matrix form stdin
spLUfactor    Sparse LU factorization using partial pivoting
spLUsolve     Solves Ax=b using sparse LU factors
spLUTsolve    Solves A^Tx=b using sparse LU factors
sp_mv_mlt     Computes Ax for sparse A
sp_output     Outputs a sparse matrix to a stream (macro)
sp_resize     Resize a sparse matrix
sprow_add     Adds a pair of sparse rows
sprow_foutput Output sparse row to a stream
sprow_get     Allocate and initialize a sparse row
sprow_idx     Get location of an entry in a sparse row
sprow_merge   Merge two sparse rows
sprow_mltadd  Sparse row vector multiply-and-add
sprow_set_val Set an entry in a sparse row
sprow_smlt    Multiplies a sparse row by a scalar
sprow_sub     Subtracts a sparse row from another
sprow_xpd     Expand a sparse row
sp_set_val    Set the (i,j) entry of a sparse matrix
sp_vm_mlt     Compute x^TA for sparse A
sp_zero       Zero (but do not remove) all entries of a sparse matrix
svd           The SVD of a matrix
sv_mlt        Scalar-vector multiply
symmeig       Eigenvalues/vectors of a symmetric matrix
tracecatch()  Catch and re-raise errors (macro)
trieig        Eigenvalues/vectors of a symmetric tridiagonal matrix
Usolve        Solve Ux=b where U is upper triangular
UTsolve       Solve U^Tx=b where U is upper triangular
v_add         Add vectors
v_conv        Convolution product of vectors
v_copy        Copy vector
v_dump        Dump vector data structure to a stream
v_finput      Input vector from a stream
v_foutput     Output vector to a stream
V_FREE        Free (deallocate) a vector (macro)
v_free        Free (deallocate) vector (function)
v_free_vars   Free a list of vectors
v_get         Allocate and initialize a vector
v_get_vars    Allocate list of vectors
v_input       Input vector from stdin (macro)
v_lincomb     Compute sum of a_i x_i for an array of vectors
v_linlist     Compute sum of a_i x_i for a list of vectors
v_map         Apply function component wise to a vector
v_max         Computes max vector entry and index
v_min         Computes min vector entry and index
v_mltadd      Computes y <- alpha*x+y for vectors x , y
vm_mlt        Computes x^TA
vm_mltadd     Computes y^T <- y^T+x^TA
v_norm1       Computes ||x||_1 for a vector
v_norm2       Computes ||x||_2 (the Euclidean norm) of a vector
v_norm_inf    Computes ||x||_inf for a vector
v_ones        Set vector to all 1's
v_output      Output vector to stdout (macro)
v_pconv       Periodic convolution of two vectors
v_rand        Randomize entries of a vector
v_resize      Resize a vector
v_resize_vars Resize a list of vectors
v_save        Save a vector in MATLAB format
v_slash       Computes component wise ratio of vectors
v_sort        Sorts vector components
v_star        Component wise vector product
v_sub         Subtract two vectors
v_sum         Sum of components of a vector
v_zero        Zero a vector
z_finput      Read complex number from file or stream
z_foutput     Prints complex number to file or stream
zgivens       Compute complex Givens' rotation
zhhtrcols     Apply Householder transformation: PA (complex)
zhhtrrows     Apply Householder transformation: AP (complex)
zhhtrvec      Apply Householder transformation: Px (complex)
zhhvec        Compute Householder transformation
zin_prod      Complex inner product
z_input       Read complex number from stdin
zLAsolve      Solve L^*x=b , L complex lower triangular
zLsolve       Solve Lx=b , L complex lower triangular
zLUAsolve     Solve A^*x=b using complex LU factorization
              (A^* - adjoin of A, A is complex)
zLUcondest    Complex LU condition estimate
zLUfactor     Complex LU factorization
zLUsolve      Solve Ax=b using complex LU factorization
zm_add        Add complex matrices
zm_adjoint    Computes adjoin of complex matrix
zmakeQ        Construct Q matrix for complex QR
zmakeR        Construct R matrix for complex QR
zmam_mlt      Computes A^*B (complex)
zm_dump       Dump complex matrix to stream
zm_finput     Input complex matrix from stream
ZM_FREE       Free (deallocate) complex matrix (macro)
zm_free       Free (deallocate) complex matrix (function)
zm_free_vars  Free a list of complex matrices
zm_get        Allocate complex matrix
zm_get_vars   Allocate a list of complex matrices
zm_input      Input complex matrix from stdin
zm_inverse    Compute inverse of complex matrix
zm_load       Load complex matrix in MATLAB format
zmma_mlt      Computes AB^* (complex)
zm_mlt        Multiply complex matrices
zm_norm1      Complex matrix 1-norm
zm_norm_frob  Complex matrix Frobenius norm
zm_norm_inf   Complex matrix infinity-norm
zm_rand       Randomize complex matrix
zm_resize     Resize complex matrix
zm_resize_vars Resize a list of complex matrices
zm_save       Save complex matrix in MATLAB format
zm_sub        Subtract complex matrices
zmv_mlt       Complex matrix-vector multiply
zmv_mltadd    Complex matrix-vector multiply and add
zm_zero       Zero complex matrix
zQRCPfactor   Complex QR factorization with column pivoting
zQRCPsolve    Solve Ax = b using complex QR factorization
zQRfactor     Complex QR factorization
zQRAsolve     Solve A^*x = b using complex QR factorization
zQRsolve      Solve Ax = b using complex QR factorization
zrot_cols     Complex Givens' rotation of columns
zrot_rows     Complex Givens' rotation of rows
z_save        Save complex number in MATLAB format
zschur        Complex Schur factorization
zset_col      Set column of complex matrix
zset_row      Set row of complex matrix
zsm_mlt       Complex scalar-matrix product
zUAsolve      Solve U^*x=b , U complex upper triangular
zUsolve       Solve Ux=b , U complex upper triangular
zv_add        Add complex vectors
zv_copy       Copy complex vector
zv_dump       Dump complex vector to a stream
zv_finput     Input complex vector from a stream
ZV_FREE       Free (deallocate) complex vector (macro)
zv_free       Free (deallocate) complex vector (function)
zv_free_vars  Free a list of complex vectors
zv_get        Allocate complex vector
zv_get_vars   Allocate a list of complex vectors
zv_input      Input complex vector from a stdin
zv_lincomb    Compute sum of a_i x_i for an array of vectors
zv_linlist    Compute sum of a_i x_i for a list of vectors
zv_map        Apply function to each element of a complex vector
zv_mlt        Complex scalar-vector product
zv_mltadd     Complex scalar-vector multiply and add
zvm_mlt       Computes A^*x (complex)
zvm_mltadd    Computes A^*x+y (complex)
zv_norm1      Complex vector 1-norm vnorm1()
zv_norm2      Complex vector 2-norm (Euclidean norm)
zv_norm_inf   Complex vector infinity- (or supremum) norm
zv_rand       Randomise complex vector
zv_resize     Resize complex vector
zv_resize_vars Resize a list of complex vectors
zv_save       Save complex vector in MATLAB format
zv_slash      Componentwise ratio of complex vectors
zv_star       Componentwise product of complex vectors
zv_sub        Subtract complex vectors
zv_sum        Sum of components of a complex vector
zv_zero       Zero complex vector


MESCHACH VERSION 1

MESCHACH VERSION 1.2A

In this manual the basic data structures are introduced, and some of the more basic operations are illustrated. Then some examples of how to use the data structures and procedures to solve some simple problems are given. The first example program is a simple 4th order Runge-Kutta solver for ordinary differential equations. The second is a general least squares equation solver for over-determined equations. The third example illustrates how to solve a problem involving sparse matrices. These examples illustrate the use of matrices, matrix factorizations and solving systems of linear equations. The examples described in this manual are implemented in tutorial.c.

While the description of each aspect of the system is brief and far from comprehensive, the aim is to show the different aspects of how to set up programs and routines and how these work in practice, which includes I/O and error-handling issues.

THE DATA STRUCTURES AND SOME BASIC OPERATIONS

The three main data structures are those describing vectors, matrices and permutations. These have been used to create data structures for simplex tableaus for linear programming, and used with data structures for sparse matrices etc. To use the system reliably, you should always use pointers to these data structures and use library routines to do all the necessary initialization.

In fact, for the operations that involve memory management (creation, destruction and resizing), it is essential that you use the routines provided.

For example, to create a matrix A of size 34 , a vector x of dimension 10, and a permutation p of size 10, use the following code:

#include "matrix.h"
..............
int main(void)
{
    MAT *A;
    VEC *x;
    PERM *p;
    ..........
    A = m_get(3,4);
    x = v_get(10);
    p = px_get(10);
    ..........
}

This initializes these data structures to have the given size. The matrix A and the vector x are initially all zero, while p is initially the identity permutation.

They can be disposed of by calling M_FREE(A), V_FREE(x) and PX_FREE(p) respectively if you need to re-use the memory for something else. The elements of each data structure can be accessed directly using the members (or fields) of the corresponding structures. For example the (i,j) component of A is accessed by A->me[i][j], x_i by x->ve[i] and p_i by
p->pe[i].

Their sizes are also directly accessible: A->m and A->n are the number of rows and columns of A respectively, x->dim is the dimension of x , and size of p is p->size.

Note that the indexes are zero relative just as they are in ordinary C, so that the index i in x->ve[i] can range from 0 to x->dim -1 . Thus the total number of entries of a vector is exactly x->dim.

While this alone is sufficient to allow a programmer to do any desired operation with vectors and matrices it is neither convenient for the programmer, nor efficient use of the CPU. A whole library has been implemented to reduce the burden on the programmer in implementing algorithms with vectors and matrices. For instance, to copy a vector from
x to y it is sufficient to write y = v_copy(x,VNULL). The VNULL is the NULL vector, and usually tells the routine called to create a vector for output.

Thus, the v_copy function will create a vector which has the same size as x and all the components are equal to those of x. If y has already been created then you can write y = v_copy(x,y); in general, writing ``v_copy(x,y);'' is not enough! If y is NULL, then it is created (to have the correct size, i.e. the same size as x), and if it is the wrong size, then it is resized to have the correct size (i.e. same size as x). Note that for all the following functions, the output value is returned, even if
you have a non-NULL value as the output argument. This is the standard across the entire library.

Addition, subtraction and scalar multiples of vectors can be computed by calls to library routines: v_add(x,y,out), v_sub(x,y,out), sv_mlt(s,x,out) where x and y are input vectors (with data type VEC *), out is the output vector (same data type) and s is a double precision number (data type double). There is also a special combination routine, which computes out=v_1+s,v_2 in a single routine: v_mltadd(v1,v2,s,out). This is not only extremely useful, it is also more efficient than using the scalar-vector multiply and vector addition routines separately.

Inner products can be computed directly: in_prod(x,y) returns the inner product of x and y. Note that extended precision evaluation is not guaranteed. The standard installation options uses double precision operations throughout the library.

Equivalent operations can be performed on matrices: m_add(A,B,C) which returns C=A+B , and sm_mlt(s,A,C) which returns C=sA . The data types of A, B and C are all MAT *, while that of s is type double as before. The matrix NULL is called MNULL.

Multiplying matrices and vectors can be done by a single function call: mv_mlt(A,x,out) returns out=A*x while vm_mlt(A,x,out) returns out=A^T*x , or equivalently, out^T=x^T*A . Note that there is no distinction between row
and column vectors unlike certain interactive environments such as MATLAB or MATCALC.

Permutations are also an essential part of the package. Vectors can be permuted by using px_vec(p,x,p_x), rows and columns of matrices can be permuted by using px_rows(p,A,p_A), px_cols(p,A,A_p), and permutations can be multiplied using px_mlt(p1,p2,p1_p2) and inverted using px_inv(p,p_inv).
The NULL permutation is called PXNULL.

There are also utility routines to initialize or re-initialize these data structures: v_zero(x), m_zero(A), m_ident(A) (which sets A=I of the correct size), v_rand(x), m_rand(A) which sets the entries of x and A respectively to be randomly and uniformly selected between zero and one, and px_ident(p) which sets p to be an identity permutation.

Input and output are accomplished by library routines v_input(x), m_input(A), and px_input(p). If a null object is passed to any of these input routines, all data will be obtained from the input file, which is stdin. If input is taken from a keyboard then the user will be prompted for all the data items needed; if input is taken from a file, then the input will have to be of the same format as that produced by the output routines, which are: v_output(x), m_output(A) and px_output(p). This output is both human and machine readable!

If you wish to send the data to a file other than the standard output device stdout, or receive input from a file or device other than the standard input device stdin, take the appropriate routine above, use the foutpout' suffix instead of just output', and add a file pointer as the first argument. For example, to send a matrix A to a file called
``fred'', use the following:

#include "matrix.h"
.............
main()
{
    FILE *fp;
    MAT *A;
    .............
    fp = fopen("fred","w");
    m_foutput(fp,A);
    .............
}

These input routines allow for the presence of comments in the data. A comment in the input starts with a ``hash'' character ``#'', and continues to the end of the line. For example, the following is valid input for a 3-dimensional vector:

# The initial vector must not be zero
# x =
Vector: dim: 3
-7 0 3

For general input/output which conforms to this format, allowing comments in the input files, use the input() and finput() macros. These are used to print out a prompt message if stdin is a terminal (or ``tty'' in Unix jargon), and to skip over any comments if input is from a non-interactive device. An example of the usage of these macros is:

input("Input number of steps:
","%d",&steps);
fp = stdin;
finput(fp,"Input number of steps: ","%d",&steps);
fp = fopen("fred","r");
finput(fp,"Input number of steps: ","%d",&steps);

The "%d" is one of the format specifiers which are used in fscanf(); the last argument is the pointer to the variable (unless the variable is a string) just as for scanf() and fscanf(). The first two macro calls read input from stdin, the last from the file fred. If, in the first two calls, stdin is a keyboard (a ``tty'' in Unix jargon) then the prompt string "Input number of steps: "
is printed out on the terminal.

The second part of the library contains routines for various factorisation methods. It contains factorisation and solution routines for LU, Cholesky and QR-factorisation methods, as well as update routines for Cholesky and QR factorisations. Supporting these are a number of Householder transformation and Givens' rotation routines. Also there is a routine for generating the Q matrix for a QR-factorisation, if it is needed explicitly, as it often is. There are routines for band factorisation and solution for LU and LDL^T
factorisations.

The routines contained in the library include routines for creating, destroying, initialising and updating sparse matrices, and also routines for sparse matrix-dense vector multiplication, sparse LU factorisation and sparse Cholesky factorisation.

There are also routines for applying iterative methods such as pre-conditioned conjugate gradient methods to sparse matrices.

And if you use the standard maths library (sin(), cos(), tan(), exp(), log(), sqrt(), acos() etc.) don't forget to include the standard mathematics header:

#include <math.h>

This file is not automatically included by any of the Meschach header files.

2. HOW TO MANAGE MEMORY

Unlike many other numerical libraries, Meschach allows you to allocate, deallocate and resize the vectors, matrices and permutations that you are using. To gain maximum benefit from this it is sometimes necessary to think a little about where memory is allocated and deallocated. There are two reasons for this.

Memory allocation, deallocation and resizing takes a significant amount of time compared with (say) vector operations, so it should not be done too frequently. Allocating memory but not deallocating it means that it cannot be used by any other data structure. Data structures that are no longer needed should be explicitly deallocated, or kept as static variables for
later use. Unlike other interpreted systems (such as Lisp) there is no implicit ``garbage collection'' of no-longer-used memory.

There are three main strategies that are recommended for deciding how to allocate, deallocate and resize objects. These are ``no deallocation'' which is really only useful for demonstration programs, ``allocate and deallocate'' which minimises overall memory requirements at the expense of speed, and ``resize on demand'' which is useful for routines that are
called repeatedly. A new technique for static workspace arrays is to ``register workspace variables''.

2.1 NO DEALLOCATION

This is the strategy of allocating but never deallocating data structures. This is only useful for demonstration programs run with small to medium size data structures. For example, there could be a line

QR = m_copy(A,MNULL); /* allocate memory for QR */

to allocate the memory, but without the call M_FREE(QR); in it. This can be acceptable if QR = m_copy(A,MNULL) is only executed once, and so the allocated memory never needs to be explicitly deallocated.

This would not be acceptable if QR = m_copy(A,MNULL) occurred inside a for loop. If this were so, then memory would be ``lost'' as far as the program is concerned until there was insufficient space for allocating the next matrix for QR. The next subsection shows how to avoid this.

2.2 ALLOCATE AND DEALLOCATE

This is the most straightforward way of ensuring that memory is not lost. With the example of allocating QR it would work like this: for ( ... ; ... ; ... )
{
    QR = m_copy(A,MNULL); /* allocate memory for QR */
    /* could have been allocated by m_get() */
    /* use QR */
    ......
    ......
    /* no longer need QR for this cycle */
    M_FREE(QR); /* deallocate QR so memory can be reused */
}

The allocate and deallocate statements could also have come at the beginning and end of a function or procedure, so that when the function returns, all the memory that the function has allocated has been deallocated.

This is most suitable for functions or sections of code that are called repeatedly but involve fairly extensive calculations (at least a matrix-matrix multiply, or solving a system of equations).

2.3 RESIZE ON DEMAND

This technique reduces the time involved in memory allocation for code that is repeatedly called or used, especially where the same size matrix or vector is needed. For example, the vectors v1, v2, etc. in the Runge-Kutta routine rk4() are allocated according to this strategy:

rk4(...,x,...)
{
    static VEC *v1=VNULL, *v2=VNULL, *v3=VNULL, *v4=VNULL, *temp=VNULL;
    .......
    v1 = v_resize(v1,x->dim);
    v2 = v_resize(v2,x->dim);
    v3 = v_resize(v3,x->dim);
    v4 = v_resize(v4,x->dim);
    temp = v_resize(temp,x->dim);
    .......
}

The intention is that the rk4() routine is called repeatedly with the same size x vector. It then doesn't make as much sense to allocate v1, v2 etc. whenever the function is called. Instead, v_resize() only performs memory allocation if the memory already allocated to v1, v2 etc. is smaller than x->dim.

The vectors v1, v2 etc. are declared to be static to ensure that their values are not lost between function calls. Variables that are declared static are set to NULL or zero by default. So the declaration of v1, v2, etc., could be

static VEC *v1, *v2, *v3, *v4, *temp;

This strategy of resizing static workspace variables is not so useful if the object being allocated is extremely large. The previous ``allocate and deallocate'' strategy is much more efficient for memory in those circumstances. However, the following section shows how to get the best of both worlds.

2.4 REGISTRATION OF WORKSPACE

From version 1.2 onwards, workspace variables can be registered so that the memory they reference can be freed up on demand. To do this, the function containing the static workspace variables has to include calls to MEM_STAT_REG(var,type) where var is a pointer to a Meschach data type (such as VEC or MAT). This call should be placed after the call to the appropriate resize function. The type parameter should be a TYPE_... macro where the ``...'' is the name of a Meschach type such as VEC or MAT. For example,

rk4(...,x,...)
{
    static VEC *v1, *v2, *v3, *v4, *temp;
    .......
    v1 = v_resize(v1,x->dim);
    MEM_STAT_REG(v1,TYPE_VEC);
    v2 = v_resize(v2,x->dim);
    MEM_STAT_REG(v2,TYPE_VEC);
    ......
}

Normally, these registered workspace variables remain allocated. However, to implement the ``deallocate on exit'' approach, use the following code:

......
mem_stat_mark(1);
rk4(...,x,...)
mem_stat_free(1);
......

To keep the workspace vectors allocated for the duration of a loop, but then deallocated, use

......
mem_stat_mark(1);
for (i = 0; i < N; i++ )
    rk4(...,x,...);
mem_stat_free(1);
......

The number used in the mem_stat_mark() and mem_stat_free() calls is the workspace group number. The call mem_stat_mark(1) designates 1 as the current workspace group number; the call mem_stat_free(1) deallocates (and
sets to NULL) all static workspace variables registered as belonging to workspace group 1.

3. SIMPLE VECTOR OPERATIONS: AN RK4 ROUTINE

The main purpose of this example is to show how to deal with vectors and to compute linear combinations.

The problem here is to implement the standard 4th order Runge-Kutta method for the ODE

x'=f(t,x), x(t_0)=x_0

for x(t_i), i=1,2,3, where t_i=t_0+i*h and h is the step size.

The formulae for the 4th order Runge-Kutta method are:

x_i+1 = x_i+ h/6*(v_1+2*v_2+2*v_3+v_4),
where
v_1 = f(t_i,x_i)
v_2 = f(t_i+h, x_i+h*v_1)
v_3 = f(t_i+h, x_i+h*v_2)
v_4 = f(t_i+h, x_i+h*v_3)

where the v_i are vectors.

The procedure for implementing this method (rk4()) will be passed (a pointer to) the function f. The implementation of f could, in this system, create a vector to hold the return value each time it is called. However, such a scheme is memory intensive and the calls to the memory allocation functions could easily dominate the time performed doing numerical
computations. So, the implementation of f will also be passed an already allocated vector to be filled in with the appropriate values.

The procedure rk4() will also be passed the current time t, the step size h, and the current value for x. The time after the step will be returned by rk4().

The code that does this follows.

#include "matrix.h"

/* rk4 - 4th order Runge-Kutta method */
double rk4(f,t,x,h)
double t, h;
VEC *(*f)(), *x;
{
    static VEC *v1=VNULL, *v2=VNULL, *v3=VNULL, *v4=VNULL;
    static VEC *temp=VNULL;

    /* do not work with NULL initial vector */
    if ( x == VNULL )
        error(E_NULL,"rk4");

    /* ensure that v1, ..., v4, temp
are of the correct size */
v1 = v_resize(v1,x->dim);
v2 = v_resize(v2,x->dim);
v3 = v_resize(v3,x->dim);
v4 = v_resize(v4,x->dim);
temp = v_resize(temp,x->dim);

    /* register workspace variables
*/
MEM_STAT_REG(v1,TYPE_VEC);
MEM_STAT_REG(v2,TYPE_VEC);
MEM_STAT_REG(v3,TYPE_VEC);
MEM_STAT_REG(v4,TYPE_VEC);
MEM_STAT_REG(temp,TYPE_VEC);
/* end of memory allocation */

    (*f)(t,x,v1); /* most compilers
allow: f(t,x,v1); */
v_mltadd(x,v1,0.5*h,temp); /* temp = x+.5*h*v1 */
(*f)(t+0.5*h,temp,v2);
v_mltadd(x,v2,0.5*h,temp); /* temp = x+.5*h*v2 */
(*f)(t+0.5*h,temp,v3);
v_mltadd(x,v3,h,temp); /* temp = x+h*v3 */
(*f)(t+h,temp,v4);

    /* now add: v1+2*v2+2*v3+v4 */
    v_copy(v1,temp); /* temp = v1 */
    v_mltadd(temp,v2,2.0,temp); /* temp = v1+2*v2 */
    v_mltadd(temp,v3,2.0,temp); /* temp = v1+2*v2+2*v3 */
    v_add(temp,v4,temp); /* temp = v1+2*v2+2*v3+v4 */

    /* adjust x */
    v_mltadd(x,temp,h/6.0,x); /* x = x+(h/6)*temp */

    return t+h; /* return the new time */
}

Note that the last parameter of f() is where the output is placed. Often this can be NULL in which case the appropriate data structure is allocated and initialised. Note also that this routine can be used for problems of arbitrary size, and the dimension of the problem is determined directly from the data given. The vectors v_1,...,v_4 are created to have
the correct size in the lines ....
v1 = v_resize(v1,x->dim);
v2 = v_resize(v2,x->dim);
....

Here v_resize(v,dim) resizes the VEC structure v to hold a vector of length dim. If v is initially NULL, then this creates a new vector of dimension dim, just as v_get(dim) would do. For the above piece of code to work correctly, v1, v2 etc., must be initialised to be NULL vectors. This is done by the declaration

static VEC *v1=VNULL, *v2=VNULL, *v3=VNULL, *v4=VNULL;

or

static VEC *v1, *v2, *v3, *v4;

The operations of vector addition and scalar addition are really the only vector operations that need to be performed in rk4. Vector addition is done by v_add(v1,v2,out), where out=v1+v2, and scalar multiplication by sv_mlt(scale,v,out), where out=scale*v.

These can be combined into a single operation v_mltadd(v1,v2,scale,out), where out=v1+scale*v2. As many operations in numerical mathematics involve accumulating scalar multiples, this is an extremely useful operation, as we
can see above. For example:

v_mltadd(x,v1,0.5*h,temp); /* temp = x+0.5*h*v1 */

We also need a number of ``utility'' operations. For example v_copy(in, out) copies the vector in to out. There is also v_zero(v) to zero a vector v.

Here is an implementation of the function f for simple harmonic motion:

/* f - right-hand side of ODE solver */
    VEC *f(t,x,out)
    VEC *x, *out;
    double t;
    {
    if ( x == VNULL || out == VNULL )
        error(E_NULL,"f");
    if ( x->dim != 2 || out->dim != 2 )
        error(E_SIZES,"f");

    out->ve[0] = x->ve[1];
    out->ve[1] = - x->ve[0];

    return out;
}

As can be seen, most of this code is error checking code, which, of course, makes the routine safer but a little slower. For a procedure like f() it is probably not necessary, although then the main program would have to perform checking to ensure that the vectors involved have the correct size etc. The ith component of a vector x is x->ve[i], and indexing is zero-relative (i.e., the ``first'' component is component 0). The ODE described above is for simple harmonic motion:

x_0'=x_1 , x_1'=-x_0 , or equivalently, x_0''+ x_0 = 0 .

Here is the main program:

#include <stdio.h>
#include "matrix.h"

int main(void)
{
    VEC *x;
    VEC *f();
    double h, t, t_fin;
    double rk4();

    input("Input initial time:
", "%lf", &t);
input("Input final time: ", "%lf", &t_fin);
x = v_get(2); /* this is the size needed by f() */
prompter("Input initial state:\n"); x =
v_input(VNULL);
input("Input step size: ", "%lf",
&h);

    printf("# At time %g, the
state is\n",t);
v_output(x);
while ( t < t_fin )
{
t = rk4(f,t,x,min(h,t_fin-t)); /* new t is
returned */
printf("# At time %g, the state is\n",t);
v_output(x);
t += h;
}
}

The initial values are entered as a vector by v_input(). If v_input() is passed a vector, then this vector will be used to store the input, and this vector has the size that x had on entry to v_input(). The original values of x are also used as a prompt on input from a tty. If a NULL is passed to v_input() then v_input() will return a vector of whatever size the user inputs. So, to ensure that only a two-dimensional vector is used for the initial conditions (which is what f() is expecting) we use

x = v_get(2); x = v_input(x);

To compile the program under the command line, if it is in a file tutorial.c:

lc tutorial.c

Here is a sample session with the above program:

tutorial

Input initial time: 0
Input final time: 1
Input initial state:
Vector: dim: 2
entry 0: -1
entry 1: b
entry 0: old -1 new: 1
entry 1: old 0 new: 0
Input step size: 0.1
At time 0, the state is
Vector: dim: 2
1 0
At time 0.1, the state is
Vector: dim: 2
0.995004167 -0.0998333333
.................
At time 1, the state is
Vector: dim: 2
0.540302967 -0.841470478

By way of comparison, the state at t=1 for the true solution is x_0(1)=0.5403023058 , x_1(1)=-0.8414709848 .
The ``b'' that is typed in entering the x vector allows the user to alter previously entered components. In this case once this is done, the user is prompted with the old values when entering the new values. The user can also type in ``f'' for skipping over the vector's components, which are then unchanged. If an incorrectly sized initial value vector x is given, the error handler comes into action:

Input initial time: 0
Input final time: 1
Input initial state:
Vector: dim: 3
entry 0: 3
entry 1: 2
entry 2: -1
Input step size: 0.1
At time 0, the state is
Vector: dim: 3
3 2 -1

"tutorial.c", line 79: sizes of objects don't match in function f()
Sorry, aborting program

The error handler prints out the error message giving the source code file and line number as well as the function name where the error was raised. The relevant section of f() in file tutorial.c is:

if ( x->dim != 2 || out->dim != 2 )
error(E_SIZES,"f"); /* line 79 */

The standard routines in this system perform error checking of this type, and also checking for undefined results such as division by zero in the routines for solving systems of linear equations. There are also error messages for incorrectly formatted input and end-of-file conditions.

To round off the discussion of this program, note that we have seen interactive input of vectors. If the input file or stream is not a tty (e.g., a file, a pipeline or a device) then it expects the input to have the same form as the output for each of the data structures. Each of the input routines (v_input(), m_input(), px_input()) skips over ``comments'' in the input data, as do the macros input() and finput(). Anything from a `#' to the end of the line (or EOF) is considered to be a comment. For
example, the initial value problem could be set up in a file ivp.dat as:

# Initial time
0
# Final time
1
# Solution is x(t) = (cos(t),-sin(t))
# x(0) =
Vector: dim: 2
1 0
# Step size
0.1

The output of the above program with the above input (from a file) gives essentially the same output as shown above, except that no prompts are sent to the screen.

4. USING ROUTINES FOR LISTS OF ARGUMENTS

Some of the most common routines have variants that take a variable number of arguments. These are the routines .._get_vars(), .._resize_vars() and .._free_vars(). These correspond to the the basic routines .._get(), .._resize() and .._free() respectively. Also there is the mem_stat_reg_vars() routine which registers a list of static workspace variables. This corresponds to mem_stat_reg_list() for a single variable.

Here is an example of how to use these functions. This example also uses the routine v_linlist() to compute a linear combination of vectors. Note that the code is much more compact, but don't forget that these ``..._vars()'' routines usually need the address-of operator ``&'' and NULL termination of the arguments to work correctly.

#include "matrix.h"

/* rk4 - 4th order Runge-Kutta method */
double rk4(VEC *(f)(),double t,VEC *x,double h)
{
    static VEC *v1, *v2, *v3, *v4, *temp;

    /* do not work with NULL initial vector */
    if ( x == VNULL )
        error(E_NULL,"rk4");

    /* ensure that v1, ..., v4, temp are of the correct size */
    v_resize_vars(x->dim, &v1, &v2, &v3, &v4, &temp, NULL);

    /* register workspace variables */
    mem_stat_reg_vars(0, TYPE_VEC, &v1, &v2, &v3, &v4, &temp, NULL);
    /* end of memory allocation */

    (*f)(t,x,v1); v_mltadd(x,v1,0.5*h,temp);
    (*f)(t+0.5*h,temp,v2); v_mltadd(x,v2,0.5*h,temp);
    (*f)(t+0.5*h,temp,v3); v_mltadd(x,v3,h,temp);
    (*f)(t+h,temp,v4);

    /* now add: temp =
v1+2*v2+2*v3+v4 */
v_linlist(temp, v1, 1.0, v2, 2.0, v3, 2.0, v4, 1.0, VNULL);
/* adjust x */
v_mltadd(x,temp,h/6.0,x); /* x = x+(h/6)*temp */

    return t+h; /* return the new time */
}

5. A LEAST SQUARES PROBLEM

Here we need to use matrices and matrix factorisations (in particular, a QR factorisation) in order to find the best linear least squares solution to some data. Thus in order to solve the (approximate) equations A*x = b, where A is an m x n matrix (m > n) we really need to solve the optimisation problem
min_x ||Ax-b||^2.

If we write A=QR where Q is an orthogonal m x m matrix and R is an upper triangular m x n matrix then (we use 2-norm)

||A*x-b||^2 = ||R*x-Q^T*b||^2 = || R_1*x - Q_1^T*b||^2 + ||Q_2^T*b||^2

where R_1 is an n x n upper triangular matrix. If A has full rank then R_1 will be an invertible matrix, and the best least squares solution of A*x=b is x= R_1^{-1}*Q_1^T*b .

These calculations can be be done quite easily as there is a QRfactor() function available with the system. QRfactor() is declared to have the prototype

MAT *QRfactor(MAT *A, VEC *diag);

The matrix A is overwritten with the factorisation of A ``in compact form''; that is, while the upper triangular part of A is indeed the R matrix described above, the Q matrix is stored as a collection of Householder vectors in the strictly lower triangular part of A and in the diag vector. The QRsolve() function knows and uses this compact form and solves Q*R*x=b with the call QRsolve(A,diag,b,x), which also returns x.

Here is the code to obtain the matrix A, perform the QR factorisation, obtain the data vector b, solve for x, and determine what the norm of the errors ( ||Ax-b||_2 ) is.

#include "matrix.h"

int main(void)
{
    MAT *A, *QR;
    VEC *b, *x, *diag;

    /* read in A matrix */
    printf("Input A matrix:");

    A = m_input(MNULL); /* A has whatever size is input */

    if ( A->m < A->n )
{
printf("Need m >= n to obtain
least squares fit");
exit(0);
}
printf("# A ="); m_output(A);
diag = v_get(A->m);

    /* QR is to be the QR factorisation of A */
    QR = m_copy(A,MNULL);
    QRfactor(QR,diag);

    /* read in b vector */
    printf("Input b vector:");
    b = v_get(A->m);
    b = v_input(b);
    printf("# b ="); v_output(b);

    /* solve for x */
    x = QRsolve(QR,diag,b,VNULL);
    printf("Vector of best fit parameters is");
    v_output(x);

    /* ... and work out norm of
errors... */
printf("||A*x-b|| = %g\n",
v_norm2(v_sub(mv_mlt(A,x,VNULL),b,VNULL)));
}

Note that as well as the usual memory allocation functions like m_get(), the I/O functions like m_input() and m_output(), and the factorise-and-solve functions QRfactor() and QRsolve(), there are also functions for matrix-vector multiplication:
mv_mlt(MAT *A, VEC *x, VEC *out)
and also vector-matrix multiplication (with the vector on the left):
vm_mlt(MAT *A, VEC *x, VEC *out),
with out=x^T A. There are also functions to perform matrix arithmetic -matrix addition m_add(), matrix-scalar multiplication sm_mlt(), matrix-matrix multiplication m_mlt().

Several different sorts of matrix factorisation are supported: LU factorisation (also known as Gaussian elimination) with partial pivoting, by LUfactor() and LUsolve(). Other factorisation methods include Cholesky factorisation CHfactor() and CHsolve(), and QR factorisation with column pivoting QRCPfactor().

Pivoting involve permutations which have their own PERM data structure. Permutations can be created by px_get(), read and written by px_input() and px_output(), multiplied by px_mlt(), inverted by px_inv() and applied to vectors by px_vec().

The above program can be put into a file leastsq.c and compiled using

lc leastsq.c meschach.lib

A sample session using leastsq follows:

Input A matrix:
Matrix: rows cols:5 3
row 0:
entry (0,0): 3
entry (0,1): -1
entry (0,2): 2
Continue:
row 1:
entry (1,0): 2
entry (1,1): -1
entry (1,2): 1
Continue: n
row 1:
entry (1,0): old 2 new: 2
entry (1,1): old -1 new: -1
entry (1,2): old 1 new: 1.2
Continue:
row 2:
entry (2,0): old 0 new: 2.5
....
.... (Data entry)
....
# A =
Matrix: 5 by 3
row 0: 3 -1 2
row 1: 2 -1 1.2
row 2: 2.5 1 -1.5
row 3: 3 1 1
row 4: -1 1 -2.2
Input b vector:
entry 0: old 0 new: 5
entry 1: old 0 new: 3
entry 2: old 0 new: 2
entry 3: old 0 new: 4
entry 4: old 0 new: 6
# b =
Vector: dim: 5
5 3 2 4 6
Vector of best fit parameters is
Vector: dim: 3
1.47241555 -0.402817858 -1.14411815
||A*x-b|| = 6.78938

The Q matrix can be obtained explicitly by the routine makeQ(). The Q matrix can then be used to obtain an orthogonal basis for the range of A .An orthogonal basis for the null space of A can be obtained by finding the QR-factorisation of A^T .

6. A SPARSE MATRIX EXAMPLE

To illustrate the sparse matrix routines, consider the problem of solving Poisson's equation on a square using finite differences, and incomplete Cholesky factorisation. The actual equations to solve are

u_{i,j+1} + u_{i,j-1} + u_{i+1,j} + u_{i-1,j} - 4*u_{i,j} = h^2*f(x_i,y_j),

for i,j=1,...,N

where u_{0,j} = u_{i,0} = u_{N+1,j} = u_{i,N+1} = 0 for i,j=1,...,N and h is the common distance between grid points.

The first task is to set up the matrix describing this system of linear equations. The next is to set up the right-hand side. The third is to form the incomplete Cholesky factorisation of this matrix, and finally to use the sparse matrix conjugate gradient routine with the incomplete Cholesky factorisation as preconditioner.

Setting up the matrix and right-hand side can be done by the following code:

#define N 100
#define index(i,j) (N*((i)-1)+(j)-1)
......
A = sp_get(N*N,N*N,5);
b = v_get(N*N);
h = 1.0/(N+1); /* for a unit square */
......

for ( i = 1; i <= N; i++ )
    for ( j = 1; j <= N; j++ )
    {
        if ( i < N )
            sp_set_val(A,index(i,j),index(i+1,j),-1.0);
        if ( i > 1 )
            sp_set_val(A,index(i,j),index(i-1,j),-1.0);
        if ( j < N )
            sp_set_val(A,index(i,j),index(i,j+1),-1.0);
        if ( j > 1 )
            sp_set_val(A,index(i,j),index(i,j-1),-1.0);
        sp_set_val(A,index(i,j),index(i,j),4.0);
        b->ve[index(i,j)] = -h*h*f(h*i,h*j);
    }

Once the matrix and right-hand side are set up, the next task is to compute the sparse incomplete Cholesky factorisation of A. This must be done in a different matrix, so A must be copied.

LLT = sp_copy(A);
spICHfactor(LLT);

Now when that is done, the remainder is easy:

out = v_get(A->m);
......
iter_spcg(A,LLT,b,1e-6,out,1000,&num_steps);
printf("Number of iterations = %d\n",num_steps);
......

and the output can be used in whatever way desired.

For graphical output of the results, the solution vector can be copied into a square matrix, which is then saved in MATLAB format using m_save(), and graphical output can be produced by MATLAB.

7. HOW DO I ....?

For the convenience of the user, here a number of common tasks that people need to perform frequently, and how to perform the computations using Meschach.

7.1 .... SOLVE A SYSTEM OF LINEAR EQUATIONS ?

If you wish to solve Ax=b for x given A and b (without destroying A), then the following code will do this:

VEC *x, *b;
MAT *A, *LU;
PERM *pivot;
......
LU = m_get(A->m,A->n);
LU = m_copy(A,LU);
pivot = px_get(A->m);
LUfactor(LU,pivot);
/* set values of b here */
x = LUsolve(LU,pivot,b,VNULL);

7.2 .... SOLVE A LEAST-SQUARES PROBLEM ?

To minimise ||Ax-b||_2^2 = sum_i ((Ax)_i-b_i)^2, the most reliable method is based on the QR-factorisation. The following code performs this calculation assuming that A is m x n with m > n :

MAT *A, *QR;
VEC *diag, *b, *x;
......
QR = m_get(A->m,A->n);
QR = m_copy(A,QR);
diag = v_get(A->n);
QRfactor(QR,diag);
/* set values of b here */
x = QRsolve(QR,diag,b,x);

7.3 FIND ALL THE EIGENVALUES (AND EIGENVECTORS) OF A GENERAL MATRIX ?

The best method is based on the Schur decomposition. For symmetric matrices, the eigenvalues and eigenvectors can be computed by a single call to symmeig(). For non-symmetric matrices, the situation is more complex and the problem of finding eigenvalues and eigenvectors can become quite ill-conditioned. Provided the problem is not too ill-conditioned, the
following code should give accurate results:

/* A is the matrix whose eigenvalues and eigenvectors are sought */
MAT *A, *T, *Q, *X_re, *X_im;
VEC *evals_re, *evals_im;
......
Q = m_get(A->m,A->n);
T = m_copy(A,MNULL);

/* compute Schur form: A = Q*T*Q^T */
schur(T,Q);

/* extract eigenvalues */
evals_re = v_get(A->m);
evals_im = v_get(A->m);
schur_evals(T,evals_re,evals_im);

/* Q not needed for eiegenvalues */
X_re = m_get(A->m,A->n);
X_im = m_get(A->m,A->n);
schur_vecs(T,Q,X_re,X_im);
/* k'th eigenvector is k'th column of (X_re + i*X_im) */

7.4 .... SOLVE A LARGE, SPARSE, POSITIVE DEFINITE SYSTEM OF EQUATIONS ?

An example of a large, sparse, positive definite matrix is the matrix obtained from a finite-difference approximation of the Laplacian operator. If an explicit representation of such a matrix is available, then the following code is suggested as a reasonable way of computing solutions:

/* A*x == b is the system to be solved */
SPMAT *A, *LLT;
VEC *x, *b;
int num_steps;
......
/* set up A and b */
......
x = m_get(A->m);
LLT = sp_copy(A);

/* preconditioning using the incomplete Cholesky factorisation */
spICHfactor(LLT);

/* now use pre-conditioned conjugate gradients */
x = iter_spcg(A,LLT,b,1e-7,x,1000,&num_steps);
/* solution computed to give a relative residual of 10^-7 */

If explicitly storing such a matrix takes up too much memory, then if you can write a routine to perform the calculation of A*x for any given x , the following code may be more suitable (if slower):

VEC *mult_routine(user_def,x,out)
void *user_def;
VEC *x, *out;
{
    /* compute out = A*x */
    ......
    return out;
}

int main(void)
{
    ITER *ip;
    VEC *x, *b;
    ......
    b = v_get(BIG_DIM); /* right-hand side */
    x = v_get(BIG_DIM); /* solution */

    /* set up b */
    ......
    ip = iter_get(b->dim, x->dim);
    ip->b = v_copy(b,ip->b);
    ip->info = NULL; /* if you don't want information
    about solution process */
    v_zero(ip->x); /* initial guess is zero */
    iter_Ax(ip,mult_routine,user_def);
    iter_cg(ip);
    printf("# Solution is:\n"); v_output(ip->x);
    ......
    ITER_FREE(ip); /* destroy ip */
}

The user_def argument is for a pointer to a user-defined structure (possibly NULL, if you don't need this) so that you can write a common function for handling a large number of different circumstances.

8. MORE ADVANCED TOPICS

Read this if you are interested in using Meschach library as a base for applications. As an example we show how to implement a new type for 3 dimensional matrices and incorporate this new type into the Meschach system. Usually this part of Meschach is transparent to a user. But a more advanced user can take advantage of these routines. We do not describe the routines in detail here, but we want to give a rather broad picture of what can be done. By the system we mainly mean the system of delivering information on the number of bytes of allocated memory and routines for
deallocating static variables by mem_stat_... routines.

First we introduce a concept of a list of types. By a list of types we mean a set of different types with corresponding routines for creating these types, destroying and resizing them. Each type list has a number. The list 0 is a list of standard Meschach types such as MAT or VEC. Other lists can be defined by a user or a application (based on Meschach). The
user can attach his/her own list to the system by the routine mem_attach_list(). Sometimes it is worth checking if a list number is already used by another application. It can be done by mem_is_list_attached(ls_num), which returns TRUE if the number ls_num is used. And such a list can be removed from the system by mem_free_list(ls_num) if necessary.

We describe arguments required by mem_attach_list(). The prototype of this function is as follow

int mem_attach_list(int ls_num, int ntypes, char *type_names[],
int (*free_funcs[])(), MEM_ARRAY sum[]);

where the structure MEM_ARRAY has two members: "bytes" of type long and "numvar" of type int. The frst argument is the list number. Note that you cannot overwrite another list. To do this remove first the old list (by mem_free_list()) or choose another number. The next argument is the number of types which are on the list. This number cannot be changed during
running a program. The third argument is an array containing the names of types (these are character strings). The fourth one is an array of functions deallocating variables of the corresponding type. And the last argument is the local array where information about the number of bytes of allocated/deallocated memory (member bytes) and the number of allocated
variables (member numvar) are gathered. The functions which send information to this array are mem_bytes_list() and mem_numvar_list().

Example: The routines described here are in the file tutadv.c.
Firstly we define some macros and a type for 3 dimensional matrices.

#include "matrix.h"
#define M3D_LIST 3 /* list number */
#define TYPE_MAT3D 0 /* the number of a type */
/* type for 3 dimensional matrices */
typedef struct {
    int l,m,n; /* actual dimensions */
    int max_l, max_m, max_n; /* maximal dimensions */
    Real ***me; /* pointer to matrix elements */
    /* we do not consider segmented memory */
    Real *base, **me2d; /* me and me2d are additional pointers to base */
} MAT3D;

Now we need two routines: one for allocating memory for 3 dimensional matrices and the other for deallocating it. It can be useful to have a routine for resizing 3 dimensional matrices but we do not use it here. Note the use of mem_bytes_list() and mem_numvar_list() to notify the change in the number of structures and bytes in use.

/* function for creating a variable of MAT3D type */

MAT3D *m3d_get(l,m,n)
int l,m,n;
{
MAT3D *mat;
....
/* alocate memory for structure */
if ((mat = NEW(MAT3D)) == (MAT3D *)NULL)
error(E_MEM,"m3d_get");
else if (mem_info_is_on()) {
/* record how many bytes are allocated to
structure */
mem_bytes_list(TYPE_MAT3D,0,sizeof(MAT3D),M3D_LIST);
/* record a new allocated variable */
mem_numvar_list(TYPE_MAT3D,1,M3D_LIST);
}
....
/* allocate memory for 3D array */
if ((mat->base = NEW_A(l*m*n,Real)) == (Real *)NULL)
error(E_MEM,"m3d_get");
else if (mem_info_is_on())
mem_bytes_list(TYPE_MAT3D,0,l*m*n*sizeof(Real),M3D_LIST);
....
return mat;
}

/* deallocate a variable of type MAT3D */

int m3d_free(mat)
MAT3D *mat;
{
    /* do not try to deallocate the NULL pointer */
    if (mat == (MAT3D *)NULL)
    return -1;
    ....
    /* first deallocate base */
    if (mat->base != (Real *)NULL) {
        if (mem_info_is_on())
        /* record how many bytes is deallocated */
        mem_bytes_list(TYPE_MAT3D,mat->max_l*mat->max_m*mat->max_n*sizeof(Real),
        0,M3D_LIST);
        free((char *)mat->base);
    }
    ....
    /* deallocate MAT3D structure */
    if (mem_info_is_on()) {
        mem_bytes_list(TYPE_MAT3D,sizeof(MAT3D),0,M3D_LIST);
        mem_numvar_list(TYPE_MAT3D,-1,M3D_LIST);
    }
    free((char *)mat);

    ....
    free((char *)mat);

    return 0;
}

We can now create the arrays necessary for mem_attach_list(). Note that m3d_sum can be static if it is in the same file as main(), where mem_attach_list is called. Otherwise it must be global.

char *m3d_names[] = { "MAT3D" };

#define M3D_NUM (sizeof(m3d_names)/sizeof(*m3d_names))

int (*m3d_free_funcs[M3D_NUM])() = {
m3d_free
}

static MEM_ARRAY m3d_sum[M3D_NUM];

The last thing is to attach the list to the system.

int main(void)
{
    MAT3D *M;
    ....

    mem_info_on(TRUE); /* switch memory info on */
    /* attach the new list */
    mem_attach_list(M3D_LIST,M3D_NUM,m3d_names,m3d_free_funcs,m3d_sum);
    ....
    M = m3d_get(3,4,5);
    ....
    /* making use of M->me[i][j][k], where i,j,k are non-negative and
    i < 3, j < 4, k < 5 */
    ....
    mem_info_file(stdout,M3D_LIST); /* info on the number of allocated
            bytes of memory for types on the list M3D_LIST */
    ....
    m3d_free(M); /* if M is not necessary */
    ....
}

We can now use the function mem_info_file() for getting information about the number of bytes of allocated memory and number of allocated variables of type MAT3D; mem_stat_reg_list() for registering variables of this type and mem_stat_mark() and mem_stat_free_list() for deallocating static variables of this type.

In the similar way you can create you own list of errors and attach it to the system. See the functions:

int err_list_attach(int list_num, int list_len, char **err_ptr,
    int warn); /* for attaching a list of errors */

int err_is_list_attached(int list_num); /* checking if a list is attached */

extern int err_list_free(int list_num); /* freeing a list of errors */

where list_num is the number of the error list, list_len is the number of errors on the list, err_ptr is the character string explaining the error and warn can be TRUE if this is only a warning (the program continues to run) or it can be FALSE if it is an error (the program stops).

The examples are the standard errors (error list 0) and warnings (error list 1) which are in the file err.c

David Stewart and Zbigniew Leyk,


Copyright

Copyright (C) 1993 David E. Steward & Zbigniew Leyk, all rights reserved.

Meschach Library

This Meschach Library is provided "as is" without any express or implied warranty of any kind with respect to this software. In particular the authors shall not be liable for any direct, indirect, special, incidental or consequential damages arising in any way from use of the software.

Everyone is granted permission to copy, modify and redistribute this Meschach Library, provided:
1. All copies contain this copyright notice.
2. All modified copies shall carry a notice stating who made the last modification and the date of such modification.
3. No charge is made for this software or works derived from it.
This clause shall not be construed as constraining other software distributed on the same medium as this software, nor is a distribution fee considered a charge.

The library has been adapted to lcc-win32 by Jacob Navia in 2004.

The full source code of the lcc-win32 version can be obtained with the "Professional" distribution of lcc-win32.


Band matrix functions

band2mat      Convert band matrix to dense matrix
bd_free       Deallocate (destroy) band matrix
bd_get        Allocate and initialize band matrix
bd_transp     Transpose band matrix
bd_resize     Resize band matrix
bdLDLfactor   Band LDL^T factorization
bdLDLsolve    Solve Ax=b using band LDL^T factors
bdLUfactor    Band LU factorization
bdLUsolve     Solve Ax=b using band LU factors
mat2band      Extract band matrix from dense matrix


Complex matrix functions

z_finput      Read complex number from file or stream
z_foutput     Prints complex number to file or stream
zgivens       Compute complex Givens' rotation
zhhtrcols     Apply Householder transformation: PA (complex)
zhhtrrows     Apply Householder transformation: AP (complex)
zhhtrvec      Apply Householder transformation: Px (complex)
zhhvec        Compute Householder transformation
zin_prod      Complex inner product
z_input       Read complex number from stdin
zLAsolve      Solve L^*x=b , L complex lower triangular
zLsolve       Solve Lx=b , L complex lower triangular
zLUAsolve     Solve A^*x=b using complex LU factorization
              (A^* - adjoin of A, A is complex)
zLUcondest    Complex LU condition estimate
zLUfactor     Complex LU factorization
zLUsolve      Solve Ax=b using complex LU factorization
zm_add        Add complex matrices
zm_adjoint    Computes adjoin of complex matrix
zmakeQ        Construct Q matrix for complex QR
zmakeR        Construct R matrix for complex QR
zmam_mlt      Computes A^*B (complex)
zm_dump       Dump complex matrix to stream
zm_finput     Input complex matrix from stream
ZM_FREE       Free (deallocate) complex matrix (macro)
zm_free       Free (deallocate) complex matrix (function)
zm_free_vars  Free a list of complex matrices
zm_get        Allocate complex matrix
zm_get_vars   Allocate a list of complex matrices
zm_input      Input complex matrix from stdin
zm_inverse    Compute inverse of complex matrix
zm_load       Load complex matrix in MATLAB format
zmma_mlt      Computes AB^* (complex)
zm_mlt        Multiply complex matrices
zm_norm1      Complex matrix 1-norm
zm_norm_frob  Complex matrix Frobenius norm
zm_norm_inf   Complex matrix infinity-norm
zm_rand       Randomize complex matrix
zm_resize     Resize complex matrix
zm_resize_vars Resize a list of complex matrices
zm_save       Save complex matrix in MATLAB format
zm_sub        Subtract complex matrices
zmv_mlt       Complex matrix-vector multiply
zmv_mltadd    Complex matrix-vector multiply and add
zm_zero       Zero complex matrix
zQRCPfactor   Complex QR factorization with column pivoting
zQRCPsolve    Solve Ax = b using complex QR factorization
zQRfactor     Complex QR factorization
zQRAsolve     Solve A^*x = b using complex QR factorization
zQRsolve      Solve Ax = b using complex QR factorization
zrot_cols     Complex Givens' rotation of columns
zrot_rows     Complex Givens' rotation of rows
z_save        Save complex number in MATLAB format
zschur        Complex Schur factorization
zset_col      Set column of complex matrix
zset_row      Set row of complex matrix
zsm_mlt       Complex scalar-matrix product
zUAsolve      Solve U^*x=b , U complex upper triangular
zUsolve       Solve Ux=b , U complex upper triangular


Complex vector functions

zv_add        Add complex vectors
zv_copy       Copy complex vector
zv_dump       Dump complex vector to a stream
zv_finput     Input complex vector from a stream
ZV_FREE       Free (deallocate) complex vector (macro)
zv_free       Free (deallocate) complex vector (function)
zv_free_vars  Free a list of complex vectors
zv_get        Allocate complex vector
zv_get_vars   Allocate a list of complex vectors
zv_input      Input complex vector from a stdin
zv_lincomb    Compute sum of a_i x_i for an array of vectors
zv_linlist    Compute sum of a_i x_i for a list of vectors
zv_map        Apply function to each element of a complex vector
zv_mlt        Complex scalar-vector product
zv_mltadd     Complex scalar-vector multiply and add
zvm_mlt       Computes A^*x (complex)
zvm_mltadd    Computes A^*x+y (complex)
zv_norm1      Complex vector 1-norm vnorm1()
zv_norm2      Complex vector 2-norm (Euclidean norm)
zv_norm_inf   Complex vector infinity- (or supremum) norm
zv_rand       Randomise complex vector
zv_resize     Resize complex vector
zv_resize_vars Resize a list of complex vectors
zv_save       Save complex vector in MATLAB format
zv_slash      Componentwise ratio of complex vectors
zv_star       Componentwise product of complex vectors
zv_sub        Subtract complex vectors
zv_sum        Sum of components of a complex vector
zv_zero       Zero complex vector


Matrix functions

bisvd         SVD of bi-diagonal matrix
BKPfactor     Bunch-Kaufman-Parlett factorization
BKPsolve      Bunch-Kaufman-Parlett solver
CHfactor      Dense Cholesky factorization
CHsolve       Cholesky solver
Dsolve        Solve Dx=y , D diagonal
get_col       Extract a column from a matrix
get_row       Extract a row from a matrix
givens        Compute Givens parameters
hhtrcols      Compute AP^T where P is a Householder matrix
hhtrrows      Compute PA where P is a Householder matrix
hhtrvec       Compute Px where P is a Householder matrix
hhvec         Compute parameters for a Householder matrix
LDLfactor     LDL^T factorization
LDLsolve      LDL^T solver
LDLupdate     Update LDL^T factorization
Lsolve        Solve Lx=y , L lower triangular
LTsolve       Solve L^Tx=y , L lower triangular
LUcondest     Estimate a condition number using LU factors
LUfactor      Compute LU factors with implicit scaled partial pivoting
LUsolve       Solve Ax=b using LU factors
LUTsolve      Solve A^Tx=b usng LU factors
m_add         Add matrices
makeQ         Form Q matrix for QR factorization
makeR         Form R matrix for QR factorization
MCHfactor     Modified Cholesky factorization
QRCPfactor    QR factorization with column pivoting
QRfactor      QR factorization
QRCPsolve     Solve Ax=b
QRsolve       Solve Ax=b using QR factorization
QRTsolve      Solve A^Tx=b using QR factorization
QRupdate      Update explicit QR factors
rot_cols      Apply Givens rotation to the columns of a matrix
rot_rows      Apply Givens rotation to the rows of a matrix
rot_vec       Apply Givens rotation to a vector
rot_zvec      Apply complex Givens rotation to a vector
schur         Compute real Schur form
schur_evals   Compute eigenvalues from the real Schur form
schur_vecs    Compute eigenvectors from the real Schur form
QRCPfactor    QR factorization with column pivoting
QRfactor      QR factorization
QRCPsolve     Solve Ax=b
QRsolve       Solve Ax=b using QR factorization
QRTsolve      Solve A^Tx=b using QR factorization
QRupdate      Update explicit QR factors
rot_cols      Apply Givens rotation to the columns of a matrix
rot_rows      Apply Givens rotation to the rows of a matrix
rot_vec       Apply Givens rotation to a vector
rot_zvec      Apply complex Givens rotation to a vector
schur         Real Schur form
schur_evals   Eigenvalues from the real Schur form
schur_vecs    Eigenvectors from the real Schur form
svd           The SVD of a matrix
symmeig       Eigenvalues/vectors of symmetric matrix
trieig        Eigenvalues/vectors of symmetric tridiagonal matrix


Matrix utilities

m_copy        Copy dense matrix
m_dump        Dump matrix data structure to a stream
m_exp         Computes matrix exponential
_m_exp        Matrix exponential
m_finput      Input matrix from a stream
m_foutput     Output matrix to a stream
M_FREE        Free (deallocate) a matrix (macro)
m_free        Free (deallocate) matrix (function)
m_free_vars   Free a list of matrices
m_get         Allocate and initialize a matrix
m_get_vars    Allocate list of matrices
m_ident       Sets matrix to identity matrix
m_input       Input matrix from stdin (macro)
m_inverse     Invert matrix
m_load        Load matrix in MATLAB format
m_mlt         Multiplies matrices
mmtr_mlt      Computes AB^T
m_norm1       Computes ||A||_1 of a matrix
m_norm_frob   Computes the Frobenius norm of a matrix
m_norm_inf    Computes ||A||_inf of a matrix
m_ones        Set matrix to all 1's
m_output      Output matrix to stdout (macro)
m_poly        Computes a matrix polynomial
m_pow         Computes integer power of a matrix
mrand         Generates pseudo-random real number
m_rand        Randomise entries of a matrix
mrandlist     Generates array of pseudo-random numbers
m_resize      Resize matrix
m_resize_vars Resize a list of matrices
m_save        Save matrix in MATLAB format
m_sub         Subtract matrices
m_transp      Transpose matrix
mtrm_mlt      Computes A^TB
mv_mlt        Computes Ax
mv_mltadd     Computes y <- Ax+y
m_zero        Zero a matrix


Permutations

px_cols       Permute the columns of a matrix
px_copy       Copy permutation
px_dump       Dump permutation data structure to a stream
px_finput     Input permutation from a stream
px_foutput    Output permutation to a stream
PX_FREE       Free (deallocate) a permutation (macro)
px_free       Free (deallocate) permutation (function)
px_free_vars  Free a list of permutations
px_get        Allocate and initialize a permutation
px_get_vars   Allocate a list of permutations
px_ident      Sets permutation to identity
px_input      Input permutation from stdin (macro)
px_inv        Invert permutation
pxinv_vec     Computes P^Tx where P is a permutation matrix
pxinv_zvec    Computes P^Tx where P is a permutation matrix (complex)
px_mlt        Multiply permutations
px_output     Output permutation to stdout (macro)
px_resize     Resize a permutation
px_resize_vars Resize a list of permutations
px_rows       Permute the rows of a matrix
px_sign       Returns the sign of the permutation
px_transp     Transpose a pair of entries
px_vec        Computes Px where P is a permutation matrix
px_zvec       Computes Px where P is a permutation matrix (complex)


Sparse matrix functions

spBKPfactor   Sparse symmetric indefinite factorization
spBKPsolve    Sparse symmetric indefinite solver
spCHfactor    Sparse Cholesky factorization
spCHsolve     Sparse Cholesky solver
spCHsymb      Symbolic sparse Cholesky factorization (no floating point operations)
sp_col_access Sets up column access paths for a sparse matrix
sp_compact    Eliminates zero entries in a sparse matrix
sp_copy       Copies a sparse matrix
sp_copy2      Copies a sparse matrix into another
sp_diag_access Sets up diagonal access paths for a sparse matrix
sp_dump       Dump sparse matrix data structure to a stream
sp_finput     Input sparse matrix from a stream
sp_foutput    Output a sparse matrix to a stream
sp_free       Free (deallocate) a sparse matrix
sp_get        Allocate and initialize a sparse matrix
sp_get_val    Get the (i,j) entry of a sparse matrix
spICHfactor   Sparse incomplete Cholesky factorization
sp_input      Input a sparse matrix form stdin
spLUfactor    Sparse LU factorization using partial pivoting
spLUsolve     Solves Ax=b using sparse LU factors
spLUTsolve    Solves A^Tx=b using sparse LU factors
sp_mv_mlt     Computes Ax for sparse A
sp_output     Outputs a sparse matrix to a stream (macro)
sp_resize     Resize a sparse matrix
sprow_add     Adds a pair of sparse rows
sprow_foutput Output sparse row to a stream
sprow_get     Allocate and initialize a sparse row
sprow_idx     Get location of an entry in a sparse row
sprow_merge   Merge two sparse rows
sprow_mltadd  Sparse row vector multiply-and-add
sprow_set_val Set an entry in a sparse row
sprow_smlt    Multiplies a sparse row by a scalar
sprow_sub     Subtracts a sparse row from another
sprow_xpd     Expand a sparse row
sp_set_val    Set the (i,j) entry of a sparse matrix
sp_vm_mlt     Compute x^TA for sparse A
sp_zero       Zero (but do not remove) all entries of a sparse matrix


Vector functions

v_add         Add vectors
v_conv        Convolution product of vectors
v_copy        Copy vector
v_dump        Dump vector data structure to a stream
v_finput      Input vector from a stream
v_foutput     Output vector to a stream
V_FREE        Free (deallocate) a vector (macro)
v_free        Free (deallocate) vector (function)
v_free_vars   Free a list of vectors
v_get         Allocate and initialize a vector
v_get_vars    Allocate list of vectors
v_input       Input vector from stdin (macro)
v_lincomb     Compute sum of a_i x_i for an array of vectors
v_linlist     Compute sum of a_i x_i for a list of vectors
v_map         Apply function component wise to a vector
v_max         Computes max vector entry and index
v_min         Computes min vector entry and index
v_mltadd      Computes y <- alpha*x+y for vectors x , y
vm_mlt        Computes x^TA
vm_mltadd     Computes y^T <- y^T+x^TA
v_norm1       Computes ||x||_1 for a vector
v_norm2       Computes ||x||_2 (the Euclidean norm) of a vector
v_norm_inf    Computes ||x||_inf for a vector
v_ones        Set vector to all 1's
v_output      Output vector to stdout (macro)
v_pconv       Periodic convolution of two vectors
v_rand        Randomize entries of a vector
v_resize      Resize a vector
v_resize_vars Resize a list of vectors
v_save        Save a vector in MATLAB format
v_slash       Computes component wise ratio of vectors
v_sort        Sorts vector components
v_star        Component wise vector product
v_sub         Subtract two vectors
v_sum         Sum of components of a vector
v_zero        Zero a vector


Statistics functions

Only long double versions are shown, overloads for float and double will also be provided.

Based on "TR-2 proposal C/C++ Math functions for Statistics" by Paul Bristow.
Implementation according to the CEPHES mathematical library.

#include <stats.h>

Beta distribution function.
long double beta_distribution(long double a,long double b, long double x);

Incomplete beta integral.
double beta_incomplete(double a, double b, double x);

Inverse of incomplete beta integral.
double beta_incomplete_inv(double a, double b, double y);

Binomial distribution function.
long double binomial(unsigned int k, unsigned int n, long double p);

Binomial distribution function complemented.
long double binomial_c(unsigned int k, unsigned int n, long double p);

Binomial distribution function inverse
long double binomial_inv(unsigned int k, unsigned int n , long double y);

Negative binomial distribution .
double binomial_neg_distribution(unsigned int k, unsigned int n, double p);

Negative binomial distribution complement.
double binomial_neg_distribution_c(unsigned int k, unsigned int n, double p);

Inverse of negative binomial distribution.
double binomial_neg_distribution_inv(unsigned int k, unsigned int n, double p);

Evaluate Chebyshev polynomial.
double chebyshev_poly(double x, double* coefficient, unsigned int n);

Chi-squared distribution function.
long double chi_sqr_distribution(long double df,long double x);

Chi-squared distribution function complemented.
long double chi_sqr_distribution_c(long double df, long double x);

Inverse of Chi-squared distribution function complemented.
long double chi_sqr_distribution_cinv(long double df,long  double p);

Psi or digamma function.
long double digamma(long double x);

Fisher F distribution
long double fisher_distribution(unsigned int a, unsigned int b,long  double c);

Fisher F distribution complemented.
double fisher_distribution_c(unsigned int ia, unsigned int ib, double c);

Inverse of complemented Fisher F distribution.
long double fisher_distribution_cinv(long double dfn,long  double dfd, long double y);

Gamma probability distribution function.
long double gamma_distribution(long double a, long double b, long double x);

Gamma probability distribution function complemented.
long double gamma_distribution_c(long double a,long double b,long double x);

Incomplete gamma function.
double gamma_incomplete (double a, double x);

Incomplete gamma function complemented.
long double gamma_incomplete_c(long double a,long double x);

Inverse of incomplete gamma integral.
long double gamma_incomplete_inv (long double a,long double y0);

Inverse of complemented incomplete gamma integral.
long double gamma_incomplete_cinv (long double a,long double y0);

Normal distribution function.
long double normal_distribution (long double a);

Inverse of normal distribution function.
long double normal_distribution_inv (long double a);

Poisson distribution.
long double poisson_distribution (unsigned int k, long double m);

Complemented Poisson distribution.
long double poisson_distribution_c(unsigned int k,long double m);

Inverse Poisson distribution.
long double poisson_distribution_inv(unsigned int k,long double y);

Student's t
long double students_t (int df,long  double t);
Inverse of Student's t.
long double students_t_inv (int df,long double p);

Kolmogorov statistic.
long double kolmogorov ( long double );

Kolmogorov statistic inverse.
long double kolmogorov_inv (long double p);

Exact Smirnov statistic
long double smirnov(int n,long double e);

Inverse Smirnov
long double smirnov_inv(int n,long double);


abs

Function:arithmetic_meanl arithmetic_mean arithmetic_meanf

Synopsis
#include <stats.h>
long double arithmetic_meanl(long double *pData,int nbOfElements);
double arithmetic_mean(double *pData,int nbOfElements);
float arithmetic_meanf(float *pData,int nbOfElements);

Description

The arithmetic mean of a set of n values xi is

Returns

The arithmetic mean value.


abs

Function: beta

Synopsis
#include <stats.h>
float betaf(float x,float y);
double beta(double x,double y);
long double betal(long
    double x,long double y);
#include <qfloat.h>
qfloat betaq(qfloat &,qfloat &);

Description

Returns

The evaluated integral.

Notes:

The implementation of this function is derived from the one in the Cephes mathematical library.


abs

Function: beta_incomplete beta_incomplete_inv

Synopsis
#include <stats.h>
long double beta_incomplete(long double a,long double b,long double x);
long double beta_incomplete_inv(long double a,long double b,long double y);

Description

The beta_incomplete function returns the incomplete beta integral of the arguments, evaluated from zero to x.
The function is defined as:

In this implementation a and b must be positive values. Moreover, it holds that

0 <= x <= 1

Given y, the inverse function beta_incomplete_inv finds x such that
beta_incomplete_inv ( a, b, x ) = y .
Performs interval halving or Newton iterations to find the root of beta_incomplete_inv (a,b,x) - y = 0.

Returns

The evaluated integral.

Notes:

The implementation of this function is derived from the one in the Cephes mathematical library.


abs

Function: beta_distribution

Synopsis
#include <stats.h>
long double beta_distribution( long double a, long double b, long double x);

Description

The area from zero to x under the beta density is the integral:

Returns

The evaluated integral.

Notes:

The implementation of this function is derived from the one in the Cephes mathematical library.


abs

Function: binomial binomial_c binomial_inv

Synopsis
#include <stats.h>
long double binomial(int
    k,int n,long double p);
long double binomial_c(int k,int n,long double y);
long double binomial_inv(int k,int n,long double y);

Description

The binomial function returns the sum of the terms 0 through k of the Binomial probability density:

If p < 0 or p > 1 errno will be set to ERANGE.

If k < 0 or n <= k errno will be set to ERANGE

The complementary binomial function binomial_c returns the sum of the terms k+1 through n of the Binomial probability density

The terms are not summed directly; instead the incomplete beta integral is employed, according to the formula

y = binomial_c( k, n, p ) = beta_incomplete( k+1, n-k, p ).

The arguments must be positive, with p ranging from 0 to 1. If this is not the case errno will be set to ERANGE and zero is returned.

The inverse binomial distribution function binomial_inv finds the event probability p such that the sum of the terms 0 through k of the Binomial probability density is equal to the given cumulative probability y. This is accomplished using the inverse beta integral function and the relation

1 - p = beta_incomplete_inv( n-k, k+1, y ).

The arguments of the inverse binomial distribution must be in the ranges:

0 <= y <= 1
k >= 0
n > k

If this is not the case, errno will be set to ERANGE and zero is returned.

Returns

The evaluated integral.

Notes:

The implementation of this function is derived from the one in the Cephes mathematical library.


abs

Function: binomial_neg_distribution binomial_neg_distribution_c binomial_neg_distribution_inv

Synopsis
#include <stats.h>
long double binomial_neg_distribution(int k,int n,long double p);
long double binomial_neg_distribution_c(int k,int n,long double p);

Description

The binomial_neg_distribution binomial_neg_distribution returns the sum of the terms 0 through k of the negative binomial distribution:

In a sequence of Bernoulli trials, this is the probability that k or fewer failures precede the nth success.

The terms are not computed individually; instead the incomplete beta integral is employed, according to the formula:

y = binomial_neg_distribution( k, n, p ) = beta_incomplete( n, k+1, p )

The arguments must be positive, with p ranging from 0 to 1.

The complemented binomial negative distribution binomial_neg_distribution_c returns the sum of the terms k+1 to infinity of the negative binomial distribution:

The terms are not computed individually; instead the incomplete beta integral is employed, according to the formula:

y = binomial_neg_distribution_c(k,n,p) = beta_incomplete(K=1,n,1-p);

The functional inverse negative binomial distribution binomial_neg_distribution_inv finds the argument p such that binomial_neg_distribution(k,n,p) is equal to y.

Returns

The evaluated integrals.

Notes:

The implementation of this function is derived from the one in the Cephes mathematical library.


abs

Function:central_momentl central_moment central_momentf

Synopsis
#include <stats.h>
long double central_momentl(long double *pData,int nbOfElements,long double K);
double central_moment(double *pData,int nbOfElements,double K);
float central_momentf(float *pData,int nbOfElements,float K);

Description

The kth central_moment of a set of values xi

Returns

The central_moment value.


abs

Function: chi_square

Synopsis
#include <stats.h>
long double
    chi_sqr_distribution(long double df,long double x);
long double chi_sqr_distribution_c(long double df, long double x);
long double chi_sqr_distribution_cinv(long double df,long double x);

Description

The chi_sqr_distribution function returns the area under the left hand tail (from 0 to x) of the Chi squared probability density function with df degrees of freedom.

where x is the Chi-square variable.

The incomplete gamma integral is used with

    y = chi_sqr_distribution(v,x) = igam(v/2.0,x/2.0);

The arguments must be both positive.

The complemented Chi-square distribution chi_sqr_distribution_c returns the area under the right hand tail (from x to infinity) of the Chi squared probability density function with df degrees of freedom.

where x is the Chi-square variable.

The complemented incomplete gamma integral is used according to the formula:

y = chi_sqr_distribution_c(v,x) = igamc(v/2.0,x/2.0);

The arguments must be both positive.

The inverse of complemented Chi-square distribution function chi_sqr_distribution_cinv finds the Chi-square argument x such that the integral from x to infinity of the Chi-squared density is equal to the given cumulative probability y.

This is done using the relation:

x/2 = igami(df/2,y);

Returns

The evaluated integrals.

Notes:

The implementation of this function is derived from the one in the Cephes mathematical library.


pow

Function: digamma

Synopsis
#include <stats.h>
long double digamma(long double x);

Description

The digamma function returns the logarithmic derivative of the gamma function.

For integer x, the value is -EUL + Sum(k=1,n-1)1/k

This is used for 0 <= x <= 10. If x is negative, it is transformed to a positive argument using the reflection formula:

psi(1-x) = psi(x) + PI*cot(PI*x)

Returns

The digamma function

Notes:

The implementation of this function is based on the CEPHES mathematical library.


abs

Function: fisher_distribution fisher_distribution_c fisher_distribution_inv fisher_distribution_cinv

Synopsis
#include <stats.h>
long double fisher_distribution(int
    a,int b,long double x);
long double fisher_distribution_c(int a,int b, long double x);
long double fisher_distribution_inv(long double df,long double x);
long double fisher_distribution_cinv(int a,int b,long double y);

Description

The fisher distribution function fisher_distribution returns the area from zero to x under the Fisher F density function (also known as Snedcor's density or the variance ratio density). This is the density of

where u and u2 are random variables having Chi square distributions with df1 and df2 degrees of freedom, respectively.

The left tail area from 0 to x under the F density is:

fisher_distribution(df1,df2,F) = Iw(df1/2,df2/2)

where

The incomplete beta integral is used according to the formula

P(x) = beta_incomplete(df1/2.0,df2/2.0,df1*x/(df2+df1*x))

The arguments a and b should be greater than one and x is non-negative. If any of the argument is not in range the errno variable is set to ERANGE and zero is returned.

The complemented fisher distribution fisher_distribution_c returns the right tail area from x to infinity under the F density function (also known as Snedecor's density or the variance ratio density).

The incomplete beta integral is used, according to the formula:

P(x) = beta_incomplete(df2/2,df1/2,df2/(df2+df1*x))

fisher_distribution_c(d1,d2,F) = Iv(d1/2,d2/2)

where

v = d2 / (d2 +d1*F)

The integer arguments of fisher_distribution_c should be greater than zero, and the double argument x should be >= zero. If any of the arguments is not in range errno is set to ERANGE and zero is returned.

The inverse fisher distribution function fisher_distribution_inv finds the F density argument x such that the integral from zero to x (left tail)of the F density is equal to the given probability p.

This is accomplished using the inverse beta integral function and the relations

z = beta_incomplete_inv(df1/2,df2/2,p)

x = df2 * z/(df1*(1-z))

Probability p must be > zero and p <=unity. If any of the arguments is not in range, errno is set to ERANGE and zero is returned.

The complemented inverse fisher distribution function fisher_distribution_cinv finds the F density argument x such that the integral from x to infinity (right tail) of the F density is equal to the given probability p.

This is accomplished using the inverse beta integral function and the relations:

z = beta_incomplete_inv(df2/2,df1/2,p)

x = df2(1-z)/ (df1*z)

Error handling

if ( (ia < 1) || (ib < 1) || (y <= 0.0L) || (y > 1.0L) ) the variable errno will be set to ERANGE and zero will be returned.

Returns

The evaluated integrals.

Notes:

The implementation of this functions is derived from the Cephes mathematical library.


abs

Function: gamma_incomplete gamma_incomplete_cinv

Synopsis
#include <stats.h>
long double gamma_incomplete(long double a,long double x);
long double gamma_incomplete_c(long double a,long double x);
long double gamma_incomplete_cinv(long double a,long double y0);

Description

The incomplete gamma integral gamma_incomplete is defined by the following relations:

where F1 is the confluent hypergeometric function. Both arguments a and x must be positive. The integral is evaluated by either a power series or continued fraction expansion, depending on the relative values of a and x.

The complemented incomplete gamma integral gamma_incomplete_c is defined by:

gamma_incomplete_c(a,x) = 1 - gamma_incomplete(a,x)

The inverse of the complemented gamma integral gamma_incomplete_cinv given a probability p finds x such that

gamma_incomplete_c(a,x) = p

This can be done starting with the approximate value 3, then

x = a*t

where t = 1 - d - normal_distribution_inv(p) * sqrt(d)

d = 1/(9*a)

Returns

The evaluated integrals.

Notes:

The implementation of this function is derived from the one in the Cephes mathematical library.


abs

Function:geometric_meanl geometric_mean geometric_meanf

Synopsis
#include <stats.h>
long double geometric_meanl(long double *pData,int nbOfElements);
double geometric_mean(double *pData,int nbOfElements);
float geometric_meanf(float *pData,int nbOfElements);

Description

The geometric mean of a set of n values xi is

Returns

The geometric mean value.

See also:

HarmonicMean ArithmeticMean GeometricMean


abs

Function:harmonic_meanl harmonic_mean harmonic_meanf

Synopsis
#include <stats.h>
long double harmonic_meanl(long double *pData,int nbOfElements);
double harmonic_mean(double *pData,int nbOfElements);
float harmonic_meanf(float *pData,int nbOfElements);

Description

The harmonic mean of a set of n values xi is

Returns

The harmonic mean value.


pow

Function: kolmogorov kolmogorov_inv

Synopsis
#include <stats.h>
long double kolmogorov(long double x);
long double kolmogorov_inv(long double p);

Description

The kolmogorov function returns Kolmogorov's limiting distribution of a two sided test or probability that sqrt(n)*max_deviation > y

The inverse kolmogorov_inv function returns y such that kolmogorov(y)=p.

Returns

The kolmogorov distribution or the inverse

Notes:

The implementation of this function is based on the CEPHES mathematical library.


abs

Function:kurtosisl kurtosis kurtosisf

Synopsis
#include <stats.h>
long double kurtosisl(long double *pData,int nbOfElements);
double kurtosis(double *pData,int nbOfElements);
float kurtosisf(float *pData,int nbOfElements);

Description

Kurtosis is a measure of how sharply peaked the distribution is. It is defined as the fourth central moment of the distribution divided by the square of the maximum likelihood estimate of the variance.

Returns

The kurtosis value.


abs

Function:medianl median medianf

Synopsis
#include <stats.h>
long double medianl(long double *pData,int nbOfElements);
long double binomial_neg_distribution_c(int k,int n,long double p);

Description

The median or central value of a distribution is the value for which half the elements are smaller and half are greater. For a distribution with an even number of elements, the median is defined as the arithmetic mean of the two elements in the middle of the sorted distribution.

If nbOfElements is smaller than 1 the result is zero and errno is set to ERANGE.

If there is not enough memory for the allocation of the intermediate data vector the result is zero and errno is set to ENOMEM.

Returns

The median value.


abs

Function: normal_distribution normal_distribution_inv

Synopsis
#include <stats.h>
long double normal_distribution(long double a);
long double normal_distribution_inv(long double a);

Description

The normal distribution function normal_distribution Returns the area under the Gaussian probability density function from minus infinity to x.

The inverse of the the normal distribution function normal_distribution_inv returns the argument x for which the area under the Gaussian probability density function integrated from -infinity to x is equal to y.

For small arguments 0 < y < exp(-2), the program computes
z = sqrt( -2.0 * log(y) );

then the approximation is

x = z - log(z)/z - (1/z) P(1/z) / Q(1/z).

There are two rational functions P/Q, one for 0 < y < exp(-32) and the other for y up to exp(-2). For larger arguments, w = y - 0.5, and x/sqrt(2pi) = w + w**3 R(w**2)/S(w**2)).

Returns

The evaluated integrals.

Notes:

The implementation of this function is derived from the one in the Cephes mathematical library.


abs

Function:percentilel percentile percentilef

Synopsis
#include <stats.h>
long double percentilel(long double *pData,int nbOfElements,long double K);
double percentile(double *pData,int nbOfElements,double K);
float percentilef(float *pData,int nbOfElements,float K);

Description

The kth percentile is the value such that 100k% of the data are less than or equal to that value. If the result of multiplying the size of the dataTable by k is an integer, that item is returned. Otherwise, the mean of the two adjacent items is returned. Note that percentile (0.5) is the median function.

Returns

The percentile value.


abs

Function: poisson_distribution poisson_distribution_c poisson_distribution_inv

Synopsis
#include <stats.h>
long double poisson_distribution(int
    k,long double m);
long double poisson_distribution_c(int k,long double m)
long double poisson_distribution_inv(int k,long double m);

Description

The poisson distribution function poisson_distribution returns the sum of the first k terms (area under the left tail) of the poisson distribution

The terms are not summed directly; instead the incomplete gamma integral is employed according to the relation:

poisson_distribution(k,m) = gamma_incomplete_c(k+1,m)

The arguments must be both positive.

The complemented poisson distribution function poisson_distribution_c returns the sum of the terms k+1 to infinity (area under the right tail) of the poisson distribution:

The terms are not summed directly, instead the incomplete gamma integral is employed according to the relation:

y = poisson_distribution_c(k,m) = gamma_incomplete(k+1,m)

The arguments k and m must be both positive.

The inverse Poisson distribution function poisson_distribution_inv finds the Poisson variable x such that the integral from 0 to x of the Poisson density is equal to the given probability y.

This can be found using the inverse gamma integral function and the relation:

m - gamma_inverse(k+1,y)

Returns

The evaluated integrals.

Notes:

The implementation of this function is derived from the one in the Cephes mathematical library.


abs

Function:rmsl rms rmsf

Synopsis
#include <stats.h>
long double rmsl(long double *pData,int nbOfElements);
double rms(double *pData,int nbOfElements);
float rmsf(float *pData,int nbOfElements);

Description

The root mean square of a set of n values xi is

Returns

The root mean square value.


abs

Function:skewnessl skewness skewnessf

Synopsis
#include <stats.h>
long double skewnessl(long double *pData,int nbOfElements);
double skewness(double *pData,int nbOfElements);
float skewnessf(float *pData,int nbOfElements);

Description

The skewness of a distribution is a measure of its asymmetry with respect to the mean. It is defined as the third central moment of the distribution divided by the cube of the maximum likelihood estimate of the standard deviation.

Returns

The skewness value.


pow

Function: smirnov smirnov_inv

Synopsis
#include <stats.h>
long double smirnov(int n,long double e);
long double smirnov_inv(int n,long double e);

Description

The smirnov function returns the exact Smirnov statistic for a one-sided test equal to the probability that the maximum difference between a theoretical distribution and an empirical one based on n samples is greater than e.

The inverse function smirnov_inv returns e such that smirnov(n,e)=y.

Returns

The smirnov statistic or the inverse

Notes:

The implementation of this function is based on the CEPHES mathematical library.


abs

Function:standard_deviationl standard_deviation standard_deviationf

Synopsis
#include <stats.h>
long double standard_deviationl(long double *pData,int nbOfElements);
double standard_deviation(double *pData,int nbOfElements);
float standard_deviationf(float *pData,int nbOfElements);

Description

The standard deviation is the square root of the variance.

Returns

The standard deviation value.


abs

Function:standard_deviation_mlel standard_deviation_mle standard_deviation_mlef

Synopsis
#include <stats.h>
long double standard_deviation_mlel(long double *pData,int nbOfElements);
double standard_deviation_mle(double *pData,int nbOfElements);
float standard_deviation_mlef(float *pData,int nbOfElements);

Description

The standard deviation is the square root of the variance_mle (Maximum Likehood Estimate).

Returns

The standard deviation MLE value.


pow

Function: student_t student_t_inv

Synopsis
#include <stats.h>
#include <qfloat.h>
long double students_t(int df,long double x);
qfloat students_tq(int df,qfloat x);
long double students_t_inv(int df,long double p);
qfloat students_t_invq(int df,qfloat p);

Description

The Student's distribution function student_t computes the integral from minus infinity to t of the Student t distribution with integer k > 0 degrees of freedom:

Relation to incomplete beta integral:

1 - students_t(k,t) = 0.5 *beta_incomplete( k/2, 1/2, z )
where
 z = k/(k + t**2).

For t < -1.6, this is the method of computation. For higher t, a direct method is derived from integration by parts. Since the function is symmetric about t=0, the area under the right tail of the density is found by calling the function with -t instead of t.

The inverse of Student's t distribution students_t_inv finds the argument t such that students_t(k,t) is equal to p.

Returns

The student distribution

Credits:

The implementation of this function is based on the CEPHES mathematical library.


The Mersenne Twister

Mersenne Twister(MT) is a pseudorandom number generating algorithm developped by Makoto Matsumoto and Takuji Nishimura (alphabetical order) in 1996/1997. An improvement on initialization was given on 2002 Jan.
MT has the following merits:

  • It is designed with consideration on the flaws of various existing generators.
  • Far longer period and far higher order of equidistribution than any other implemented generators. (It is proved that the period is 2^19937-1, and 623-dimensional equidistribution property is assured.)
  • Fast generation.
  • Efficient use of the memory. (The implemented C-code mt19937.c consumes only 624 words of working area.)

The theoretical background can be reviewed here

The lcc-win32 implementation provides the following APIs:

#include <random.h>

Initialization
void mt_init_genrand(unsigned long s);
void mt_init_by_array(unsigned long init_key[], int key_length);

int 32 bit random
unsigned long genrand_int32(void);

int 31 bit random
long genrand_int31(void);

Generates a random number on [0,1]-real-interval
double genrand_real1(void);

Generates a random number on [0,1)-real-interval
double genrand_real2(void);

Generates a random number on (0,1)-real-interval
double genrand_real3(void);

Generates a random number on [0,1) with 53-bit resolution
double genrand_res53(void);


abs

Function:variancel variance variancef

Synopsis
#include <stats.h>
long double variancel(long double *pData,int nbOfElements);
double variance(double *pData,int nbOfElements);
float variancef(float *pData,int nbOfElements);

Description

The variance is the sum of the differences between each sample squared from the mean squared divided by the number of elements.

Sum(x2 - mean2)/n

Returns

The variance value.


abs

Function:variance_mlel variance_mle variance_mlef

Synopsis
#include <stats.h>
long double variance_mlel(long double *pData,int nbOfElements);
double variance_mle(double *pData,int nbOfElements);
float variance_mlef(float *pData,int nbOfElements);

Description

The variance_mle (Maximul Likehood Estimate) is

v_mle = (variance * (nbOfElements - 1))/nbOfElements

Returns

The variance_mle value.


chdir

Function: crc32

Synopsis
#include <netutils.h>
unsigned int crc32(unsigned char *buffer,unsigned int buffer_size,unsigned int initial_crc);
Link with netutils.lib

Description

The crc32 function calculates the CRC (Cyclic Redundancy Check) of the buffer given by its first argument, using the indicated length and initial CRC.

Returns

The updated CRC. Use an initial value of zero to start the process.

Notes:

This function is adapted from the code edited by Tim Lee and published as part of the TLTools subroutine library
at www.tltools.org.

For good explanation of CRC theory see ftp.adelaide.edu.au/pub/rocksoft/crc_v3.txt by Ross N.Williams.

See also "C Programmer's Guide to Serial Communications" | by Joe Campbell for a good explanation of CRC math and
example polynomial math algorithms.

Portability

Windows

Example:

#include <stdio.h>
#include <netutils.h>
/* This program will print the CRC of a given file */
int main(int argc,char *argv[])
{
    if (argc < 2) {
        printf("Usage: crc <file name>\n");
        return 1;
    }
    FILE *f = fopen(argv[1],"rb");
    if (f == NULL) {
        fprintf(stderr,"Impossible to open '%s'\n",argv[1]);
        return 1;
    }
    char buffer[4096];
    int CRC = 0;

    int bytes_read = fread(buffer,1,sizeof(buffer),f);
    while (bytes_read != 0) {
        CRC = crc32(buffer,bytes_read,CRC);
        bytes_read = fread(buffer,1,sizeof(buffer),f);
    }
    fclose(f);
    printf("CRC of '%s': %#x\n",argv[1],CRC);
    return 0;
}


_findfirst

Function: GetFtpUrl

Synopsis
#include <netutils.h>
int GetFtpUrl( char *host,char *remotepath,char *localfilename);
Link with netutils.lib

Library: netutils.lib

Description

This function will retrieve from the indicated host and remote path a file that will be stored in the local machine with the name indicated by localfilename.

Return

The result is zero if the file could be retrieved, or an error code (returned by GetLastError()) otherwise.

Example:

int main(void)
{
    GetFtpUrl("ftp.cs.virginia.edu","/pub/lcc-win32/lccwin32.exe","lccwin32.exe");
}

This will retrieve lcc from the virginia site.


_findfirst

Function: GetHttpURL

Synopsis
#include <netutils.h>
int GetHttpURL( char *URL,char *localfilename);
Link with netutils.lib

Description

This function will retrieve from the indicated URL a file that will be stored in the local machine with the name indicated by localfilename.

Return

The result is zero if the file could be retrieved, or an error code (returned by GetLastError()) otherwise.


_findfirst

Function: ping

Synopsis
#include <ping.h>
int ping(PingInterface *p);

Library:

netutils.lib

Description

This function sends an ICMP echo request to the indicated host. It returns the number of packets the foreign host has echoed. The input passes through the PingInterface structure. This structure is as follows:

typedef struct __Ping {
char *HostName;      // IN: Host name/Ip address of destination. Required
int TotalPackets;
// OPTIONAL: Number of packets to send before exiting.
Default is 5
int DataSize;
// OPTIONAL: Data size in the sent packets. Default is 32
int SleepTime;
// OPTIONAL: Time (in ms) to wait after each packet.           Default is 1000 ms.
int MaxTimeouts;
// OPTIONAL: Maximum number of timeouts allowed.           Default is 5.
int (*Callback)(struct __Ping *); // OPTIONAL: Callback function
int ttl;
// OPTIONAL: Time to live. Default 128
int verbose;
// Optional: Whether to print messages to stdout or not.
int TotalReceived;   // OUT: Total packets received
int TotalSent;
// OUT: Total packets sent
int MaxTime;
// OUT: Maximum time (ms)
int MinTime;
// OUT: Minimum time (ms)
int TotalTime;
// OUT: Total time used
int Timeouts;
// OUT: Number of timeouts
int Errorcode;
// WSAGetLastError() report when an error occurs, or
// a negative number, specific to the ping function.
int ShortPackets;
// OUT: Packets that weren't sent completely due to errors
char ip[MAXIPNAME];  // OUT: IP of destination (Can be the same as
HostName)
//--------------- Per packet specific data-------------
int Bytes;
// OUT: Bytes received
int Seq;
// OUT: Sequence number
int Time;
// OUT: Time for this packet
} PingInterface;

The only required field is the HostName field. A minimal program that uses this function is:

#include <ping.h>
#include <stdio.h>
int main(int argc,char *argv[])
{
    PingInterface p;
    memset(&p,0,sizeof(p));
    p.HostName = argv[1]);
    if (ping(&p)) {
        printf(“Host %s is up\n”,argv[1]);
    }
    else
        printf(“Host %s is down\n”,argv[1]);
}

This program will print if a host is up nor not. If the host is down, it will take 5 seconds to return.

The Callback function will be called at each packet and at each timeout event. An example of this function is the following:

#include <ping.h>
int PrintReport(PingInterface *Data)
{
    if (Data->Errorcode == WSAETIMEDOUT) {
        printf("Timed out\n");
        return 1;
    }
    printf("%d bytes from %s:",Data->Bytes, Data->ip);
    printf(" icmp_seq = %d. ",Data->Seq);
    printf(" time: %d ms ",Data->Time);
    printf("\n");
    return 1;
}

The Data->Errorcode field can be used to differentiate between a cal to the callback because a packet arrived or because a timeout event occurred.

Besides the errors returned by WSAGetLastError() following errors are returned:

#define PINGERROR_BADADDR -1
#define PINGERROR_SETSOCKOPT -2
#define PINGERROR_NONETWORK -3
#define PINGERROR_NOSOCKET -4
#define PINGERROR_INTERNAL -5

Returns

The return value is negative if there is an error, zero if there is no error but the host could not be reached, and greater than zero if the pinged host answered.


_findfirst

Function:ClientConnect

Synopsis
#include <netutils.h>
int ClientConnect(Session *session);

Library:

netutils.lib

Description

This function will connect a client to the host and port indicated in the corresponding fields of the Session structure.

Return

The result is zero if the connection succeeded, an error code otherwise

Example:

#include <netutils.h>
#include <stdio.h>
int main(int argc,char *argv[])
{
    Session session;
    char buf[8192];

    memset(&session,0,sizeof(session));
    session.port = 25876;
    session.Host = "127.0.0.1";
    if (Connect(&session))
        return 0;
    printf("Connected...\n");
    memset(buf,0,sizeof(buf));
    if (Receive(&session,sizeof(buf)-1,buf))
        return 0;
    printf("received request\n");
    printf("data is: %s\n",buf);
    Send(&session,5,"data");
}


_findfirst

Function:CloseSession

Synopsis
#include <netutils.h>
void CloseSession(Session *session);

Library:

netutils.lib

Description

Closes the socket of the session, and cleans up.


_findfirst

Function: Receive

Synopsis
#include <netutils.h>
int Receive(Session *session,int bytesToReceive, char *data);

Library:

netutils.lib

Description

This function will receive the specified number of bytes through the network. The session structure passed as argument should have been obtained by a successful ConnectClient or ConnectServer call. The number of bytes received can be retrieved in the BytesReceived field of the session structure.

Return

The result is zero if all bytes were received, an error code otherwise. The actual number of bytes received can be retrieved from the field BytesReceived of the session structure.

Example:

#include <netutils.h>
#include <stdio.h>
int main(int argc,char *argv[])
{
    Session session;
    char buf[8192];

    memset(&session,0,sizeof(session));
    session.port = 25876;
    session.Host = "127.0.0.1";
    if (ClientConnect(&session))
        return 0;
    printf("Connected...\n");
    memset(buf,0,sizeof(buf));
    if (Receive(&session,sizeof(buf)-1,buf))
        return 0;
    printf("received request\n");
    printf("data is: %s\n",buf);
    Send(&session,5,"data");
    CloseSession(&session);
}


_findfirst

Function:Send

Synopsis
#include <netutils.h>
int Send(Session *session,int bytesToSend, char *data);

Description

This function will send the specified number of bytes through the network. The session structure passed as argument should have been obtained by a successful ConnectClient or ConnectServer call. The number of bytes sent can be retrieved in the BytesSent field of the session structure.

Return

The result is zero if all bytes were sent, an error code otherwise. The actual number of bytes sent can be retrieved from the field BytesSent of the session structure.

Example:

#include <netutils.h>
#include <stdio.h>
int main(int argc,char *argv[])
{
    Session session;
    char buf[8192];

    memset(&session,0,sizeof(session));
    session.port = 25876;
    session.Host = "127.0.0.1";
    if (ClientConnect(&session))
        return 0;
    printf("Connected...\n");
    memset(buf,0,sizeof(buf));
    if (Receive(&session,sizeof(buf)-1,buf))
        return 0;
    printf("received request\n");
    printf("data is: %s\n",buf);
    Send(&session,5,"data");
    CloseSession(&session);
}


_findfirst

Function:ServerConnect

Synopsis
#include <netutils.h>
int ServerConnect(Session *session);

Description

This function will connect a server to the host and port indicated in the corresponding fields of the Session structure.

Return

The result is zero if the connection succeeded, an error code otherwise

Example:

#include <netutils.h>
#include <stdio.h>
int main(int argc,char *argv[])
{
    Session session;
    char buf[8192];

    memset(&session,0,sizeof(session));
    session.port = 25876;
    session.Host = "127.0.0.1";
    if (ServerConnect(&session))
        return 0;
    printf("Connected...\n");
    memset(buf,0,sizeof(buf));
    if (Receive(&session,sizeof(buf)-1,buf))
        return 0;
    printf("received request\n");
    printf("data is: %s\n",buf);
    Send(&session,5,"data");
}


Time Date Funcs

LCC-Win32 Time/Date Functions

_ftime | clock | gmtime | strftime
_strdate | ctime | localtime | time
asctime | difftime | mktime | struct_tm
time64 | difftime64 | mktime64 | gmtime64
ctime64 |  |  |


_ftime

Function: _ftime

Synopsis
#include <sys\timeb.h>
void _ftime(struct _timeb *timeptr);

Description

The _ftime function fills the structure timeb pointed by its argument with information about the current time.

This structure has the following relevant fields:

dstflag    Nonzero if daylight savings time is currently in effect
         for the local time zone.

millitm    Fraction of a second in milliseconds.

time       Time in seconds since midnight (00:00:00), January 1,
         1970, coordinated universal time (UTC).

timezone   Difference in minutes, moving westward, between
           UTC and local time.

Returns

This function returns no value


_strdate

Function: _strdate

Synopsis
#include <time.h>
char *_strdate(char *datestr);

Description

The _strdate function copies a date to the buffer pointed to by datestr, formatted mm/dd/yy, where mm is two digits representing the month, dd is two digits representing the day, and yy is the last two digits of the year. For example, the string 12/05/99 represents December 5, 1999. The buffer must be at least 9 bytes long.

Example
#include <time.h>
#include <stdio.h>
int main(void)
{
    char buf[25];
    printf("The date is %s\n",strdate(buf));
}

The date is 12/28/98

Remarks:
The locale settings aren't used by this function.

Lcc-win32 defines both strdate AND _strdate.


asctime

Function: asctime _wasctime

Synopsis
#include <time.h>
char *asctime(const struct tm *timeptr);
#include <wchar.h>
char *_wasctime(const struct tm *timeptr);

Description

The asctime function converts the broken-down time in the structure pointed to by timeptr into a string in the form

Sun Sep 16 01:03:52 19730

using the equivalent of the following algorithm.
char *asctime(const struct tm *timeptr)
{
    static const char wday_name[7][3] = {
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

    static const char mon_name[12][3] = {
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

    static char result[26];

    sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d",
        wday_name[timeptr->tm_wday],
        mon_name[timeptr->tm_mon],
        timeptr->tm_mday, timeptr->tm_hour,
        timeptr->tm_min, timeptr->tm_sec,
        1900 + timeptr->tm_year);
    return result;
}

Returns

The asctime function returns a pointer to the string.

See also: struct_tm

Example
#include <stdio.h>
#include <time.h>
int main(void)
{
    struct tm *newtime;
    time_t ltime;
    /* Get the time in seconds */
    time (&ltime);
    /* convert it to the structure tm */
    newtime = localtime(&ltime);
    /* print the local time as a string */
    printf("The current time and dat are %s", asctime(newtime));
}

The current time and date are Mon Dec 28 12:33:50 1998


clock

Function: clock

Synopsis
#include <time.h>
clock_t clock(void);

Description

The clock function determines the processor time used.

Returns

The clock function returns the implementations best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation.

To determine the time in seconds, the value returned by the clock function should be divided by the value of the macro CLOCKS_PER_SEC. This is defined as 1000 in lcc-win32.

If the processor time used is not available or its value cannot be represented, the function returns the value (clock_t)-1.

Example
#include <time.h>
#include <stdio.h>
#include <windows.h> // For the Sleep function
int main(void)
{
    double timedif;
    double time1 = (double)clock();
    time1 = time1/(double)CLOCKS_PER_SEC;
    Sleep(1500);
    timedif = (((double)clock()) / (double)CLOCKS_PER_SEC) - time1;
    printf("The elapsed time is %f seconds",timedif);
}
D:>clock
The elapsed time is 1.502000 seconds


ctime

Function: ctime _wctime

Synopsis
#include <time.h>
char *ctime(const time_t *timer);
#include <wchar.h>
char *_wctime(const time_t *timer);

Description

The ctime function converts the calendar time pointed to by timer to local time in the form of a string. It is equivalent to

asctime(localtime(timer))

Returns

The ctime function returns the pointer returned by the asctime function with that broken-down time as argument.

Example
#include <time.h>
#include <stdio.h>
int main(void)
{
    time_t ltime;
    time(&ltime);
    printf("The time now is %s",ctime(&ltime));
}


ctime

Function: ctime64

Synopsis
#include <time64.h>
char *ctime64(const time64_t *timer);

Description

The ctime64 function converts the calendar time pointed to by timer to local time in the form of a string. It is equivalent to

asctime(localtime64(timer))

Returns

The ctime64 function returns the pointer returned by the asctime function with that broken-down time as argument.

Example
#include <time.h>
#include <stdio.h>
int main(void)
{
    time64_t ltime;
    time64(&ltime);
    printf("The time now is %s",ctime64(&ltime));
}


difftime

Function: difftime

Synopsis
#include <time.h>
double difftime(time_t time1, time_t time0);

Description

The difftime function computes the difference between two calendar times: time1-time0.

Returns

The difftime function returns the difference expressed in seconds as a double.

Example
#include <time.h>
#include <stdio.h>
#define RUNS 1000
#define SIZE 10000
int mark[SIZE];
int main (void)
{
    time_t start,finish;
    int i,loop,n,num;
    time(&start);
    /* This loop find the prime numbers between 2 and SIZE */
    for (loop=0; loop<RUNS;++loop) {
        for (n=0; n<SIZE;n++) {
            /* This loop marks all the composite numbers with -1 */
            for (num=0,n=2;n<SIZE;n++) {
                if (!mark[n]) {
                    for (i=2*n;i<SIZE;i+=n) {
                        mark[i] = -1;
                    }
                }
                num++;
            }
        }
    }
    time(&finish);
    printf("takes");
    printf(" an average of %f seconds to find %d primes",
    difftime(finish,start)/RUNS,num);
}
From the command line
D:>lcc difftime.c
D:>lcclnk difftime.obj
D:>difftime
Program takes an average of 0.002000 seconds to find 9998 primes
D:>lcc -O difftime.c
D:>lcclnk difftime.obj
D:>difftime
Program takes an average of 0.001000 seconds to find 9998 primes


gmtime

Function: gmtime

Synopsis
#include <time.h>
struct tm *gmtime(const time_t *timer);

Description

The gmtime function converts the calendar time pointed to by timer into a broken-down time, expressed as UTC.

Returns

The gmtime function returns a pointer to the broken-down time, or a null pointer if the specified time cannot be converted to UTC.


gmtime

Function: gmtime64

Synopsis
#include <time64.h>
struct tm *gmtime64(const time64_t *timer);

Description

The gmtime64 function converts the calendar time pointed to by timer into a broken-down time, expressed as UTC.

Returns

The gmtime64 function returns a pointer to the broken-down time, or a null pointer if the specified time cannot be converted to UTC.


localtime

Function: localtime

Synopsis
#include <time.h>
struct tm *localtime(const time_t *timer);

Description

The localtime function converts the calendar time pointed to by timer into a broken-down time, expressed as local time.

Returns

The localtime function returns a pointer to the broken-down time, or a null pointer if the specified time cannot be converted to local time.


mktime

Function: mktime

Synopsis
#include <time.h>
time_t mktime(struct tm *timeptr);

Description

The mktime function converts the broken-down time, expressed as local time, in the structure pointed to by timeptr into a calendar time value with the same encoding as that of the values returned by the time function. The original values of the tm_wday and tm_yday components of the structure are ignored, and the original values of the other components are not restricted to the ranges indicated above. On successful completion, the values of the tm_wday and tm_yday components of the structure are set appropriately, and the other components are set to represent the specified calendar time, but with their values forced to the ranges indicated above; the final value of tm_mday is not set until tm_mon and tm_year are determined.

If the call is successful, a second call to the mktime function with the resulting struct tm value shall always leave it unchanged and return the same value as the first call. Furthermore, if the normalized time is exactly representable as a time_t value, then the normalized broken-down time and the broken-down time generated by converting the result of the mktime function by a call to localtime shall be identical.

Returns

The mktime function returns the specified calendar time encoded as a value of type time_t. If the calendar time cannot be represented, the function returns the value (time_t)-1.

See also: struct_tm


mktime

Function: mktime64

Synopsis
#include <time64.h>
time64_t mktime(struct tm *timeptr);

Description

The mktime function converts the broken-down time, expressed as local time, in the structure pointed to by timeptr into a calendar time value with the same encoding as that of the values returned by the time function. The original values of the tm_wday and tm_yday components of the structure are ignored, and the original values of the other components are not restricted to the ranges indicated above. On successful completion, the values of the tm_wday and tm_yday components of the structure are set appropriately, and the other components are set to represent the specified calendar time, but with their values forced to the ranges indicated above; the final value of tm_mday is not set until tm_mon and tm_year are determined.

If the call is successful, a second call to the mktime64 function with the resulting struct tm value shall always leave it unchanged and return the same value as the first call.

Returns

The mktime64 function returns the specified calendar time encoded as a value of type time64_t. If the calendar time cannot be represented, the function returns the value (time64_t)-1.

See also: struct_tm


strftime

Function: strftime

Synopsis
#include <time.h>
size_t strftime(char * restrict s, size_t maxsize, const char * restrict format,const struct tm * restrict timeptr);

Description

The strftime function places characters into the array pointed to by s as controlled by the string pointed to by format. The format shall be a multibyte character sequence, beginning and ending in its initial shift state. The format string consists of zero or more conversion specifiers and ordinary multibyte characters. A conversion specifier consists of a % character, possibly followed by an E or O modifier character (described below), followed by a character that determines the behavior of the conversion specifier. All ordinary multibyte characters (including the terminating null character) are copied unchanged into the array. If copying takes place between objects that overlap, the behavior is undefined. No more than maxsize characters are placed into the array.

Each conversion specifier is replaced by appropriate characters as described in the following list. The appropriate characters are determined using the LC_TIME category of the current locale and by the values of zero or more members of the broken-down time structure pointed to by timeptr, as specified in brackets in the description. If any of the specified values is outside the normal range, the characters stored are unspecified.

%a | is replaced by the locales abbreviated weekday name. [tm_wday]
%A | is replaced by the locales full weekday name. [tm_wday]
%b | is replaced by the locales abbreviated month name. [tm_mon]
%B | is replaced by the locales full month name. [tm_mon]
%c | is replaced by the locales appropriate date and time representation.
%C | is replaced by the year divided by 100 and truncated to an integer, as a decimal number (0099). [tm_year]
%d | is replaced by the day of the month as a decimal number (0131). [tm_mday]
%D | is equivalent to %m/%d/%y . [tm_mon, tm_mday, tm_year]
%e | is replaced by the day of the month as a decimal number (131); a single digit is preceded by a space. [tm_mday]
%F | is equivalent to %Y%m%d (the ISO 8601 date format). [tm_year, tm_mon, tm_mday]
%g | is replaced by the last 2 digits of the week-based year (see below) as a decimal number (0099). [tm_year, tm_wday, tm_yday]
%G | is replaced by the week-based year (see below) as a decimal number (e.g., 1997). [tm_year, tm_wday, tm_yday]
%h | is equivalent to %b . [tm_mon]
%H | is replaced by the hour (24-hour clock) as a decimal number (0023). [tm_hour]
%I | is replaced by the hour (12-hour clock) as a decimal number (0112). [tm_hour]
%j | is replaced by the day of the year as a decimal number (001366). [tm_yday]
%m | is replaced by the month as a decimal number (0112). [tm_mon]
%M | is replaced by the minute as a decimal number (0059). [tm_min]
%n | is replaced by a new-line character.
%p | is replaced by the locales equivalent of the AM/PM designations associated with a 12-hour clock. [tm_hour]
%r | is replaced by the locales 12-hour clock time. [tm_hour, tm_min, tm_sec]
%R | is equivalent to %H:%M . [tm_hour, tm_min]
%S | is replaced by the second as a decimal number (0060). [tm_sec]
%t | is replaced by a horizontal-tab character.
%T | is equivalent to %H:%M:%S (the ISO 8601 time format). [tm_hour, tm_min, tm_sec]
%u | is replaced by the ISO 8601 weekday as a decimal number (17), where Monday is 1. [tm_wday]
%U | is replaced by the week number of the year (the first Sunday as the first day of week 1) as a decimal number (0053). [tm_year, tm_wday, tm_yday]
%V | is replaced by the ISO 8601 week number (see below) as a decimal number (0153). [tm_year, tm_wday, tm_yday]
%w | is replaced by the weekday as a decimal number (06), where Sunday is 0. [tm_wday]
%W | is replaced by the week number of the year (the first Monday as the first day of week 1) as a decimal number (0053). [tm_year, tm_wday, tm_yday]
%x | is replaced by the locales appropriate date representation.
%X | is replaced by the locales appropriate time representation.
%y | is replaced by the last 2 digits of the year as a decimal number (0099). [tm_year]
%Y | is replaced by the year as a decimal number (e.g., 1997). [tm_year]
%z | is replaced by the offset from UTC in the ISO 8601 format 0430 (meaning 4 hours 30 minutes behind UTC, west of Greenwich), or by no characters if no time zone is determinable. [tm_isdst]
%Z | is replaced by the locales time zone name or abbreviation, or by no characters if no time zone is determinable. [tm_isdst]
%% | is replaced by %.

Some conversion specifiers can be modified by the inclusion of the E or O modifier characters to indicate an alternative format or specification. If the alternative format or specification does not exist for the current locale, the modifier is ignored.

%Ec | is replaced by the locales alternative date and time representation.
%EC | is replaced by the name of the base year (period) in the locales alternative representation.
%Ex | is replaced by the locales alternative date representation.
%EX | is replaced by the locales alternative time representation.
%Ey | is replaced by the offset from %EC (year only) in the locales alternative representation.
%EY | is replaced by the locales full alternative year representation.
%Od | is replaced by the day of the month, using the locales alternative numeric symbols (filled as needed with leading zeros, or with leading spaces if there is no alternative symbol for zero).
%Oe | is replaced by the day of the month, using the locales alternative numeric symbols (filled as needed with leading spaces).
%OH | is replaced by the hour (24-hour clock), using the locales alternative numeric symbols.
%OI | is replaced by the hour (12-hour clock), using the locales alternative numeric symbols.
%Om | is replaced by the month, using the locales alternative numeric symbols.
%OM | is replaced by the minutes, using the locales alternative numeric symbols.
%OS | is replaced by the seconds, using the locales alternative numeric symbols.
%Ou | is replaced by the ISO 8601 weekday as a number in the locales alternative representation, where Monday is 1.
%OU | is replaced by the week number, using the locales alternative numeric symbols.
%OV | is replaced by the ISO 8601 week number, using the locales alternative numeric symbols.
%Ow | is replaced by the weekday as a number, using the locales alternative numeric symbols.
%Ou | is replaced by the week number of the year, using the locales alternative numeric symbols.
%Oy | is replaced by the last 2 digits of the year, using the locales alternative numeric symbols.

%g, %G, and %V give values according to the ISO 8601 week-based year. In this system, weeks begin on a Monday and week 1 of the year is the week that includes January 4th, which is also the week that includes the first Thursday of the year, and is also the first week that contains at least four days in the year. If the first Monday of January is the 2nd, 3rd, or 4th, the preceding days are part of the last week of the preceding year; thus, for Saturday 2nd January 1999, %G is replaced by 1998 and %V is replaced by 53.If December 29th, 30th, or 31st is a Monday, it and any following days are part of week 1 of the following year. Thus, for Tuesday 30th December 1997, %G is replaced by 1998 and %V is replaced by 1.

Not implemented in CRTDLL.DLL

If a conversion specifier is not one of the above, the behavior is undefined.

In the "C" locale, the E and O modifiers are ignored and the replacement strings for the following specifiers are:

%a | the first three characters of %A
%A | one of Sunday , Monday, ... , Saturday
%b | the first three characters of %B
%B | one of January , February, ... , December
%c | equivalent to %A %B %d %T %Y
%p | one of am or pm
%r | equivalent to %I:%M:%S %p
%x | equivalent to %A %B %d %Y
%X | equivalent to %T
%Z | implementation-defined

Returns

If the total number of resulting characters including the terminating null character is not more than maxsize, the strftime function returns the number of characters placed into the array pointed to by s not including the terminating null character. Otherwise, zero is returned and the contents of the array are indeterminate.


time

Function: time

Synopsis
#include <time.h>
time_t time(time_t *timer);

Description

The time function determines the current calendar time. The encoding of the value is unspecified.

Under the lcc-win32/windows system, The time function returns the number of seconds elapsed since midnight (00:00:00), January 1, 1970, coordinated universal time, according to the system clock. The return value is stored in the location given by timer. This parameter may be NULL, in which case the return value is not stored.

Returns

The time function returns the implementations best approximation to the current calendar time. The value (time_t)-1 is returned if the calendar time is not available. If timer is not a null pointer, the return value is also assigned to the object it points to.


System Funcs

LCC-Win32 System Functions

_getpid | atexit | getenv | raise
_rotl | beginthread | jmp_buf | setjmp
_searchenv | clearerr | localeconv | setlocale
_spawn | endthread | longjmp | signal
abort | errno | main | system
assert | exit | perror | va_list
 |  | putenv |


_getpid

Function: _getpid

Synopsis
#include <process.h>
int _getpid(void);

Description

The getpid function retrieves the current process ID.

Returns

Returns an integer with the current process ID

Portability

Windows UNIX


_searchenv

Function: _searchenv

Synopsis:

#include <stdlib.h>
void _searchenv(const char *filename, const char *varname, char *pathname);

Description

The _searchenv routine searches for the target file specified by its filename argument in the specified domain. The varname variable can be any environment or user-defined variable that specifies a list of directory paths, such as PATH, LIB, and INCLUDE. _searchenv is case sensitive, so varname should match the case of the environment variable.

The routine searches first for the file in the current working directory. If it does not find the file, it looks next through the directories specified by the environment variable. If the target file is in one of those directories, the newly created path is copied into pathname. If the filename file is not found, pathname will contain an empty string.

Returns

This function returns no value

Portability

Windows


_spawn

Function: _spawn, _wspawnl

Synopsis
#include <process.h>
int _spawnl( int mode, const char *cmdname, const char *arg0, const char *arg1, ... const char *argn, NULL );
int _wspawnl( int mode, const wchar_t *cmdname, const wchar_t *arg0,const wchar_t *arg1, ... const wchar_t *argn, NULL );

This functions do not belong to the standard ANSI C library.

Description

This functions create and execute a new process. Its parameters are:
· mode Execution mode for the process to be created. This can
be either one of the constants _P_WAIT or _P_NOWAIT,
indicating whether the process starts synchronously or
asynchronously.

· cmdname The path of the program to execute.

· arg0...argN The arguments to be passed to the program.


abort

Function: abort

Synopsis
#include <stdlib.h>
void abort(void);

Description

This function provokes an immediate exit of the running program. The open files are closed and their contents are flushed to disk.

Returns

This function never returns.


atexit

Function: atexit

Synopsis
#include <stdlib.h>
int atexit(void (*func)(void));

Description
The atexit function registers the function pointed to by func, to be called without
arguments at normal program termination.

Environmental limits

The implementation shall support the registration of at least 32 functions.

Returns

The atexit function returns zero if the registration succeeds, nonzero if it fails.

Example
#include <stdlib.h>
#include <stdio.h>
void goodbye(void)
{
    printf("Goodbye");
}
int main(void)
{
    int rc = atexit(goodbye);
    if (rc != 0) {
        printf("error setting at exit function");
    }
    exit(0);
}
When run, this program produces the following output:
Goodbye


beginthread

Function: beginthread

Synopsis

#include <process.h>
unsigned long beginthread(void(*start_address)(void *), unsigned stack_size,void *arglist);

Description

The beginthread function creates a new thread of execution that begins at the start_address parameter. This routine should have no return value. When it exists, the thread is terminated. The arglist parameter is the argument of this function. It can be NULL.

To end the thread call endthread. In any case this is not necessary if the called function just exits.

Returns

If successful, this function returns the handle of the newly created thread. If an error occurs the return value is -1, in which case errno is set to EAGAIN if there are too many threads running, or to EINVAL if the argument is invalid.

Portability

Windows


clearerr

Function: clearerr

Synopsis
#include <stdio.h>
void clearerr(FILE *stream);

Description

The clearerr function clears the end-of-file and error indicators for the stream pointed to by stream.

Returns

The clearerr function returns no value.


endthread

Function: endthread

Synopsis
#include <process.h>
void enthread(void);

Description

The endthread function terminates the currently running thread.

Returns

This function returns no value.

Portability

Windows


errno

Function: errno

Synopsis
#include <errno.h>
extern int errno;

Description

errno is set on an error in a system-level call. Because errno holds the value for the last call that set it, this value may be changed by succeeding calls. Always check errno immediately before and after a call that may set it. All errno values, defined as manifest constants in ERRNO.H, are UNIX-compatible. The values valid for 32-bit Windows applications are a subset of these UNIX values.

On an error, errno is not necessarily set to the same value as the error code returned by a system call. For I/O operations only, use _doserrno to access the operating-system error-code equivalents of errno codes. For other operations the value of _doserrno is undefined.

Each errno value is associated with an error message that can be printed using perror or stored in a string using strerror. perror and strerror use the _sys_errlist array and _sys_nerr, the number of elements in _sys_errlist, to process error information.

Name String value Numerical value

E2BIG     Argument list too long 7
EACCES    Permission denied 13
EAGAIN    No more processes or not enough memory or maximum nesting level reached 11
EBADF     Bad file number 9
ECHILD    No spawned processes 10
EDEADLOCK Resource deadlock would occur 36
EDOM      Math argument 33
EEXIST    File exists 17
EINVAL    Invalid argument 22
EMFILE    Too many open files 24
ENOENT    No such file or directory 2
ENOEXEC   Exec format error 8
ENOMEM    Not enough memory 12
ENOSPC    No space left on device 28
ERANGE    Result too large 34
EXDEV     Cross-device link 18


exit

Function: exit

Synopsis
#include <stdlib.h>
void exit(int status);

Description

The exit function causes normal program termination to occur. If more than one call to the exit function is executed by a program, the behavior is undefined.

First, all functions registered by the atexit function are called, in the reverse order of their registration.

Next, all open streams with unwritten buffered data are flushed, all open streams are closed, and all files created by the tmpfile function are removed.

Finally, control is returned to the host environment. If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. The value of the argument to exit is returned by lcc-win32's runtime to the command shell or the operating system. If the value of status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation - defined.

Returns

The exit function cannot return to its caller.


getenv

Function: getenv

Synopsis
#include <stdlib.h>
char *getenv(const char *name);

Description

The getenv function searches an environment list, provided by the host environment, for a string that matches the string pointed to by name. The set of environment names and the method for altering the environment list are implementation-defined.

The implementation shall behave as if no library function calls the getenv function.

Returns

The getenv function returns a pointer to a string associated with the matched list member. The string pointed to shall not be modified by the program, but may be overwritten by a subsequent call to the getenv function. If the specified name cannot be found, a null pointer is returned.


getenv

Function: getopt

Synopsis
#include <getopt.h>
extern char *optarg;
extern int optind;
extern int optopt;
extern int opterr;
extern int optreset;
int getopt(int argc,char **argv,const char *optstring);

Description

The getopt incrementally parses a command line argument list argv and returns the next known option character. An option character is known if it has been specified in the string of accepted option characters, optstring.

The option string optstring may contain the following elements: individual characters, characters followed by a colon, and characters followed by two colons.
A character followed by a single colon indicates that an argument is to follow the option on the command line. Two colons indicates that the argument is optional.

For example, an option string "x" recognizes an option x, and an option string "x:" recognizes an option and argument x arg.

It does not matter to getopt if a following argument has a leading white space. Under windows, the character '/' can be used instead of '-' to signal an argument. This limits some arguments that can be passed through getopt. The argument "/" will be understood as '-', and processed accordingly. Similarly, an argument "/arg" will be equivalent to "-arg".

On return from getopt , optarg points to an option argument, if it is anticipated, and the variable
optind contains the index to the next argv argument for a subsequent call to getopt .

The variables opterr and optind are both initialized to 1. The optind variable may be set to another value before a set of calls to getopt in order to skip over more or less argv entries.

In order to use getopt to evaluate multiple sets of arguments, or to evaluate a single set of
arguments multiple times, the variable optreset must be set to 1 before the second and each additional set of calls to getopt , and the variable optind must be reinitialized.

The getopt function returns -1 when the argument list is exhausted. The interpretation of options in the argument list may be cancelled by the option -- (double dash) which causes getopt to signal the end of argument processing and return -1.

If the getopt function encounters a character not found in the string optstring or detects a missing option argument it writes an error message to stderr and returns ? . Setting opterr to zero will disable these error messages. If optstring has a leading : then a missing option argument causes a : to be returned in addition to suppressing any error messages.

Returns

The getopt function returns the next known option character in optstring .
If getopt encounters a character not found in optstring or if it detects a missing option argument,
it returns ? (question mark). If optstring has a leading : then a missing option argument causes
: to be returned instead of ? .
In either case, the variable optopt is set to the character that caused the error.
The getopt function returns -1 when the argument list is exhausted.

Example

extern char *optarg;
extern int optind;
int bflag, ch, fd;

bflag = 0;
while ((ch = getopt(argc, argv, "bf:")) != -1) {
switch (ch) {
case 'b':
bflag = 1;
break;
case 'f':
if ((infile = fopen(optarg, "rb"))
== NULL) {
(void)fprintf(stderr,
"myname: %s: %s\en", optarg, strerror(errno));
exit(1);
}
break;
case '?':
default:
usage();
}
}
argc -= optind;
argv += optind;

Copyright

This version of getopt is an adaptation for lcc of BSD's getopt.

/* $OpenBSD: getopt_long.c,v 1.14.2.1 2004/02/13 07:14:52 brad Exp $ */
/* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $ */

/*
* Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Sponsored in part by the Defense Advanced Research Projects
* Agency (DARPA) and Air Force Research Laboratory, Air Force
* Materiel Command, USAF, under agreement number F39502-99-1-0512.
* Copyright (c) 2000 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Dieter Baron and Thomas Klausner.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/


jmp_buf

Function: jmp_buf

Synopsis
#include <setjmp.h>
typedef long jmp_buf[18];

Description

This buffer stores the environment for use in setjmp/longjmp macros.


localeconv

Function: localeconv

Synopsis
#include <locale.h>
struct lconv *localeconv(void);

Description

The localeconv function sets the components of an object with type struct lconv with values appropriate for the formatting of numeric quantities (monetary and otherwise) according to the rules of the current locale.

The members of the structure with type char * are pointers to strings, any of which (except decimal_point) can point to "", to indicate that the value is not available in the current locale or is of zero length. Apart from grouping and mon_grouping, the strings shall start and end in the initial shift state. The members with type char are nonnegative numbers, any of which can be CHAR_MAX to indicate that the value is not available in the current locale. The members include the following:

· char *decimal_point The decimal-point character used to format nonmonetary quantities.

· char *thousands_sep The character used to separate groups of digits before the decimal-point character in formatted nonmonetary quantities.

· char *grouping A string whose elements indicate the size of each group of digits in formatted nonmonetary quantities.

· char *mon_decimal_point The decimal-point used to format monetary quantities.

· char *mon_thousands_sep The separator for groups of digits before the decimal-point in formatted monetary quantities.

· char *mon_grouping A string whose elements indicate the size of each group of digits in formatted monetary quantities.

· char *positive_sign The string used to indicate a nonnegative-valued formatted monetary quantity.

· char *negative_sign The string used to indicate a negative-valued formatted monetary quantity.

· char *currency_symbol The local currency symbol applicable to the current locale.

· char frac_digits The number of fractional digits (those after the decimal-point) to be displayed in a locally formatted monetary quantity.

· char p_cs_precedes Set to 1 or 0 if the currency_symbol respectively precedes or succeeds the value for a nonnegative locally formatted monetary quantity.

· char n_cs_precedes Set to 1 or 0 if the currency_symbol respectively precedes or succeeds the value for a negative locally formatted monetary quantity.

· char p_sep_by_space Set to a value indicating the separation of the currency_symbol, the sign string, and the value for a nonnegative locally formatted monetary quantity.

· char n_sep_by_space Set to a value indicating the separation of the currency_symbol, the sign string, and the value for a negative locally formatted monetary quantity.

· char p_sign_posn Set to a value indicating the positioning of the positive_sign for a nonnegative locally formatted monetary quantity.

· char n_sign_posn Set to a value indicating the positioning of the negative_sign for a negative locally formatted monetary quantity.

· char *int_curr_symbol The international currency symbol applicable to the current locale. The first three characters contain the alphabetic international currency symbol in accordance with those specified in ISO 4217:1995. The fourth character (immediately preceding the null character) is the character used to separate the international currency symbol from the monetary quantity.

· char int_frac_digits The number of fractional digits (those after the decimal-point) to be displayed in an internationally formatted monetary quantity.

· char int_p_cs_precedes Set to 1 or 0 if the int_currency_symbol respectively precedes or succeeds the value for a nonnegative internationally formatted monetary quantity.

· char int_n_cs_precedes Set to 1 or 0 if the int_currency_symbol respectively precedes or succeeds the value for a negative internationally formatted monetary quantity.

· char int_p_sep_by_space Set to a value indicating the separation of the int_currency_symbol, the sign string, and the value for a nonnegative internationally formatted monetary quantity.

· char int_n_sep_by_space Set to a value indicating the separation of the int_currency_symbol, the sign string, and the value for a negative internationally formatted monetary quantity.

· char int_p_sign_posn Set to a value indicating the positioning of the positive_sign for a nonnegative internationally formatted monetary quantity.

· char int_n_sign_posn Set to a value indicating the positioning of the negative_sign for a negative internationally formatted monetary quantity.

The elements of grouping and mon_grouping are interpreted according to the following:

CHAR_MAX No further grouping is to be performed.

0 The previous element is to be repeatedly used for the remainder of the digits.

other The integer value is the number of digits that compose the current group.

The next element is examined to determine the size of the next group of digits before the current group.

The values of p_sep_by_space, n_sep_by_space, int_p_sep_by_space, and int_n_sep_by_space are interpreted according to the following:

0 No space separates the currency symbol and value.

1 A space separates the currency symbol and value.

2 A space separates the currency symbol and the sign string, if adjacent.

The values of p_sign_posn, n_sign_posn, int_p_sign_posn, and int_n_sign_posn are interpreted according to the following:

0 Parentheses surround the quantity and currency symbol.

1 The sign string precedes the quantity and currency symbol.

2 The sign string succeeds the quantity and currency symbol.

3 The sign string immediately precedes the currency symbol.

4 The sign string immediately succeeds the currency symbol.

7 The implementation shall behave as if no library function calls the localeconv function.

Returns

The localeconv function returns a pointer to the filled-in object. The structure pointed to by the return value shall not be modified by the program, but may be overwritten by a subsequent call to the localeconv function. In addition, calls to the setlocale function with categories LC_ALL, LC_MONETARY, or LC_NUMERIC may overwrite the contents of the structure.


longjmp

Function: longjmp

Synopsis
#include <setjmp.h>
void longjmp(jmp_buf env, int val);

Description

The longjmp function restores the environment saved by the most recent invocation of the setjmp macro in the same invocation of the program with the corresponding jmp_buf argument. If there has been no such invocation, or if the function containing the invocation of the setjmp macro has terminated execution in the interim, or if the invocation of the setjmp macro was within the scope of an identifier with variably modified type and execution has left that scope in the interim, the behavior is undefined.

All accessible objects have values as of the time longjmp was called, except that the values of objects of automatic storage duration that are local to the function containing the invocation of the corresponding setjmp macro that do not have volatile-qualified type and have been changed between the setjmp invocation and longjmp call are indeterminate.

Returns

After longjmp is completed, program execution continues as if the corresponding invocation of the setjmp macro had just returned the value specified by val. The longjmp function cannot cause the setjmp macro to return the value 0; if val is 0,the setjmp macro returns the value 1.


main

Function: main

Synopsis

int main(int argc, char *argv[]);

or

int main(void);

Description

The main function is the entry point of the program. It can be found with two prototypes: either without any arguments, or with two arguments.

The implementation declares no prototype for this function. It is defined with a return type of int and with no parameters:

int main(void) { /* ... */ }

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

int main(int argc, char *argv[]) { /* ... */ }

or equivalent.

If they are declared, the parameters to the main function obeys the following constraints:

· The value of argc is nonnegative.

· argv[argc] is null.

· If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive contain pointers to strings, which are given values by the Win32 environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the win32 environment.

· If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name. If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc-1] represent the program parameters.

· The parameters argc and argv and the strings pointed to by the argv array, are modifiable by the program, and retain their last-stored values between program startup and program termination.


perror

Function: perror

Synopsis
#include <stdio.h>
void perror(const char *s);

Description

The perror function maps the error number in the integer expression errno to an error message. It writes a sequence of characters to the standard error stream thus: first (if s is not a null pointer and the character pointed to by s is not the null character), the string pointed to by s followed by a colon (:) and a space; then an appropriate error message string followed by a new-line character. The contents of the error message strings are the same as those returned by the strerror function with argument errno.

Returns

The perror function returns no value.


putenv

Function: putenv

Synopsis
#include <stdlib.h>
int putenv(const char *envstring);

Description

The putenv function adds new environment variables or modifies the value of existing ones. The envstring argument must be a pointer to a string of the form varname=string, where varname is the name of the environment variable to be added or modified and string is the variables value. If varname is already part of the environment, its value is replaced by string; otherwise, the new varname variable and its string value are added to the environment. You can remove a variable from the environment by specifying an empty string - in other words, by specifying only varname=.

Returns

The putenv function returns 0 if successfull, -1 otherwise


raise

Function: raise

Synopsis
#include <signal.h>
int raise(int sig);

Description

If a signal handler is called, the raise function shall not return until after the signal handler does.

See signal

Returns

The raise function returns zero if successful, nonzero if unsuccessful.


setjmp

Function: setjmp

Synopsis
#include <setjmp.h>
int setjmp(jmp_buf env);

Description

The setjmp macro saves its calling environment in its jmp_buf argument for later use by the longjmp function.

Returns

If the return is from a direct invocation, the setjmp macro returns the value zero. If the return is from a call to the longjmp function, the setjmp macro returns a nonzero value.

Environmental limits

An invocation of the setjmp macro shall appear in a program only in one of the following contexts:

· the entire controlling expression of a selection or iteration statement

· one operand of a relational or equality operator with the other operand an integer constant expression, with the resulting expression being the entire controlling expression of a selection or iteration statement

· the operand of a unary ! operator with the resulting expression being the entire controlling expression of a selection or iteration statement; or

· the entire expression of an expression statement (possibly cast to void).

· If the invocation appears in any other context, the behavior is undefined.


setlocale

Function: setlocale

Synopsis
#include <locale.h>
char *setlocale(int category, const char *locale);

Description

The setlocale function selects the appropriate portion of the programs locale as specified by the category and locale arguments. The setlocale function may be used to change or query the programs entire current locale or portions thereof. The value LC_ALL for category names the programs entire locale; the other values for category name only a portion of the programs locale. LC_COLLATE affects the behavior of the strcoll and strxfrm functions. LC_CTYPE affects the behavior of the character handling functions 174) and the multibyte and wide-character functions. LC_MONETARY affects the monetary formatting information returned by the localeconv function. LC_NUMERIC affects the decimal-point character for the formatted input/output functions and the string conversion functions, as well as the nonmonetary formatting information returned by the localeconv function. LC_TIME affects the behavior of the strftime and strfxtime functions.

A value of "C" for locale specifies the minimal environment for C translation; a value of "" for locale specifies the locale-specific native environment. Other implementation-defined strings may be passed as the second argument to setlocale.

At program startup, the equivalent of

setlocale(LC_ALL, "C");

is executed.

The implementation shall behave as if no library function calls the setlocale function.

Returns

If a pointer to a string is given for locale and the selection can be honored, the setlocale function returns a pointer to the string associated with the specified category for the new locale. If the selection cannot be honored, the setlocale function returns a null pointer and the programs locale is not changed.

Remarks for the lcc-win32/windows run time library implementation

"Locale" refers to the locality (country and language) for which you can customize certain aspects of your program. Some locale-dependent categories include the formatting of dates and the display format for monetary values.

The category argument specifies the parts of a programs locale information that are affected. The macros used for category and the parts of the program they affect are as follows:

LC_ALL All categories, as listed below

LC_COLLATE The strcoll, _stricoll, wcscoll, _wcsicoll, and strxfrm functions

LC_CTYPE The character-handling functions (except isdigit, isxdigit, mbstowcs, and mbtowc, which are unaffected)

LC_MONETARY Monetary-formatting information returned by the localeconv function

LC_NUMERIC Decimal-point character for the formatted output routines (such as printf), for the data-conversion routines, and for the nonmonetary-formatting information eturned by localeconv

LC_TIME The strftime and wcsftime functions

The locale argument is a pointer to a string that specifies the name of the locale. If locale points to an empty string, the locale is the implementation-defined native environment. A value of "C" specifies the minimal ANSI conforming environment for C translation. The "C" locale assumes that all char data types are 1 byte and that their value is always less than 256.

The locale argument takes the following form:

locale :: "lang[_country[.code_page]]"
    | ".code_page"
    | ""
    | NULL

The set of available languages, countries, and code pages includes all those supported by the Win32 NLS API.

If locale is a null pointer, setlocale queries, rather than sets, the international environment, and returns a pointer to the string associated with the specified category. The programs current locale setting is not changed. For example,

setlocale( LC_ALL, NULL );

returns the string associated with category.

The following examples pertain to the LC_ALL category. Either of the strings ".OCP" and ".ACP" can be used in place of a code page number to specify use of the system default OEM code page and system-default ANSI code page, respectively.

setlocale( LC_ALL, "" );

Sets the locale to the default, which is the system-default ANSI code page obtained from the operating system.

setlocale( LC_ALL, ".OCP" );

Explicitly sets the locale to the current OEM code page obtained from the operating system.

setlocale( LC_ALL, ".ACP" );

Sets the locale to the ANSI code page obtained from the operating system.

setlocale( LC_ALL, "[lang_ctry]" );

Sets the locale to the language and country indicated, using the default code page obtained from the host operating system.

setlocale( LC_ALL, "[lang_ctry.cp]" );

Sets the locale to the language, country, and code page indicated in the [lang_ctry.cp] string. You can use various combinations of language, country, and code page. For example:

setlocale( LC_ALL, "French_Canada.1252" );

// Set code page to French Canada ANSI default

setlocale( LC_ALL, "French_Canada.ACP" );

// Set code page to French Canada OEM default

setlocale( LC_ALL, "French_Canada.OCP" );

setlocale( LC_ALL, "[lang]" );

Sets the locale to the country indicated, using the default country for the language specified, and the system-default ANSI code page for that country as obtained from the host operating system. For example, the following two calls to setlocale are functionally equivalent:

setlocale( LC_ALL, "English" );

setlocale( LC_ALL, "English_United States.1252" );

setlocale( LC_ALL, "[.code_page]" ); Sets the code page to the value indicated, using the default country and language (as defined by the host operating system) for the specified code page.

The category must be either LC_ALL or LC_CTYPE to effect a change of code page. For example, if the default country and language of the host operating system are "United States" and "English," the following two calls to setlocale are functionally equivalent:

setlocale( LC_ALL, ".1252" );

setlocale( LC_ALL, "English_United States.1252");


signal

Function: signal

Synopsis
#include <signal.h>
void (*signal(int sig, void (*func)(int)))(int);

Description

The signal function chooses one of three ways in which receipt of the signal number sig is to be subsequently handled. If the value of func is SIG_DFL, default handling for that signal will occur. If the value of func is SIG_IGN, the signal will be ignored. Otherwise, func shall point to a function to be called when that signal occurs. An invocation of such a function because of a signal, or (recursively) of any further functions called by that invocation (other than functions in the standard library), is called a signal handler.

When a signal occurs and func points to a function, it is implementation-defined whether the equivalent of signal (sig, SIG_DFL); is executed or the implementation prevents some implementation-defined set of signals (at least including sig) from occurring until the current signal handling has completed; in the case of SIGILL, the implementation may alternatively define that no action is taken. Then the equivalent of (*func)(sig); is executed. If and when the function returns, if the value of sig is SIGFPE, SIGILL, SIGSEGV, or any other implementation-defined value corresponding to a computational exception, the behavior is undefined; otherwise the program will resume execution at the point it was interrupted.

If the signal occurs as the result of calling the abort or raise function, the signal handler shall not call the raise function.

If the signal occurs other than as the result of calling the abort or raise function, the behavior is undefined if the signal handler refers to any object with static storage duration other than by assigning a value to an object declared as volatile sig_atomic_t, or the signal handler calls any function in the standard library other than the abort function or the signal function with the first argument equal to the signal number corresponding to the signal that caused the invocation of the handler. Furthermore, if such a call to the signal function results in a SIG_ERR return, the value of errno is indeterminate.

At program startup, the equivalent of

signal(sig, SIG_IGN);

may be executed for some signals selected in an implementation-defined manner; the equivalent of signal (sig, SIG_DFL); is executed for all other signals defined by the implementation.

The implementation shall behave as if no library function calls the signal function.

Returns

If the request can be honored, the signal function returns the value of func for the most recent successful call to signal for the specified signal sig. Otherwise, a value of SIG_ERR is returned and a positive value is stored in errno.

Remarks concerning the implementation within the lcc-win32/windows system.

The implementation of signal() is made extraordinarily difficult because the lack of documentation about the behaviour of the CRTDLL.DLL run-time library. For the time being, lcc-win32 implements only the catching of SIGSEGV and SIGFPE. The implementation of other signals will be done shortly.


system

Function: system

Synopsis
#include <stdlib.h>
int system(const char *string);

Description

If string is a null pointer, the system function determines whether the host environment has a command processor. If string is not a null pointer, the system function passes the string pointed to by string to that command processor to be executed in a manner which the implementation shall document; this might then cause the program calling system to behave in a non-conforming manner or to terminate.

Returns

If the argument is a null pointer, the system function returns nonzero only if a command processor is available. If the argument is not a null pointer, and the system function does return, it returns an implementation-defined value.

Under lcc-win32/windows, the command processor, cmd.exe under windows NT or command.com under windows 95 will be called.


Structured exception handling

The general form of this facility is the following:

    __try {

            // guarded code that can generate exceptions

    }

    __except(filter integer expression) {

        // Code to handle exceptions in the try block

    }

The integer expression within parentheses (the filter expression) should yield the value EXCEPTION_EXECUTE_HANDLER (value 1), or EXCEPTION_CONTINUE_SEARCH (value 0), or EXCEPTION_CONTINUE_EXECUTION (value -1).

Within the __try block you can use the __leave keyword to exit prematurely the guarded code.

Within the __except block of code you can use the __retry construct meaning that you want to restart execution at the beginning of the current exception, in this case at the beginning of the try construct.

Related functions

To raise an exception you use the RaiseException function.

To get the exception integer code you use the GetExceptionCode.

To get information about the exception you get, use the GetExceptionInformation function.


system

Function: _System

Synopsis
#include <stdlib.h>
int _System(const char *cmd, int nCmdShow);

Description

This function spawns a new process synchronously, i.e. it will wait until the called process finishes. The program can be a console application or a windows application. The "nCmdShow" parameter is an integer that should be one of the following values:

Name and value | Meaning
SW_HIDE 0 | The process is started hidden.
SW_NORMAL 1 | The process is started visible, The process can hide itself during its execution of course.
SW_MAXIMIZE 3 | The process is started maximized if it is a windows program
SW_MINIMIZE 6 | The process is started minimized if it is a windows program

Returns

Returns the returned value of the spawned process


va_list

Function: va_list

The header <stdarg.h> declares a type and defines four macros, for advancing through a list of arguments whose number and types are not known to the called function when it is translated.

A function may be called with a variable number of arguments of varying types. Its parameter list contains one or more parameters. The rightmost parameter plays a special role in the access mechanism, and will be designated parmN in this description.

The type declared is

va_list

which is an object type suitable for holding information needed by the macros va_start, va_arg, va_end, and va_copy. If access to the varying arguments is desired, the called function shall declare an object (referred to as ap in this subclause) having type va_list. The object ap may be passed as an argument to another function; if that function invokes the va_arg macro with parameter ap, the value of ap in the calling function is indeterminate and shall be passed to the va_end macro prior to any further reference to ap.

Example
#include <stdio.h>
#include <stdarg.h>
int average( int first, ... );
int main( void )
{
    /* Call with 3 integers (zero is used as terminator). */
    printf( "Average is: %d", average( 2, 5, 9, 0 ) );
    /* Call with 5 integers. */
    printf( "Average is: %d", average( 5, 8, 2, 19, 88 , 0 ) );
    /* Call with just zero terminator. */
    printf( "Average is: %d", average( 0 ) );
}
/* Returns the average of a variable list of integers. */
int average( int first, ... )
{
    int count = 0, sum = 0, i = first;
    va_list marker;
    va_start( marker, first ); /* Initialize variable arguments. */
    while( i != 0 )
    {
        sum += i;
        count++;
        i = va_arg( marker, int);
    }
    va_end( marker ); /* Reset variable arguments. */
    return( sum ? (sum / count) : 0 );
}


Console Funcs

LCC-Win32 Console Functions

The console suite of functions are based on an old Turbo-C CONIO.H library for adapted for LCC-Win32 and created by Daniel Guerrero Miralles.

_setcursortype

gettextinfo

movetext

textmode

clreol

gotoxy

normvideo

wherex_wherey

clrscr

highvideo

textbackground

delline

lowvideo

textcolor


_setcursortype

Function: _setcursortype

Synopsis
#include <tcconio.h>
void _setcursortype(int cur_t);

link with tcconio.lib

Description

Changes the text cursor shape. Valid values for the cur_t parameter are:

- _NOCURSOR: makes the cursor invisible.

- _SOLIDCURSOR: makes the cursor look like an full block.

- _NORMALCURSOR: makes the cursor look like an underscore.

This is the default shape for the cursor.


clreol

Function: clreol

Synopsis
#include <conio.h>
void clreol(void);

link with tcconio.lib

Description

Clears the text from the current text cursor position, to the end of the line.


clrscr

Function: clrscr

Synopsis
#include <tcconio.h>
void clrscr(void);

link with tcconio.lib

Description

Clears the text (console window) screen.


delline

Function: delline

Synopsis
#include <tcconio.h>
void delline(void);

link with tcconio.lib

Description

Removes the current text line, scrolling up all the lines below.


gettextinfo

Function: gettextinfo

Synopsis
#include <tcconio.h>
void gettextinfo(struct text_info *s);

Description

Retrieves information about the status of the console. Certain fields are useless because their values are fixed, for example the output window origin. The text_info struct is defined as follows:

struct text_info
{
    unsigned char winleft;
    unsigned char wintop;
    unsigned char winright;
    unsigned char winbottom;
    unsigned char attribute;
    unsigned char normattr;
    unsigned char currmode;
    unsigned char screenheight;
    unsigned char screenwidth;
    unsigned char curx;
    unsigned char cury;
};

the fields values mean:

- winleft, winright, wintop, winbottom: coordinates of the output window. Since they cannot be changed, their value is meaningless.

- attribute: current attribute (foreground and background colors) used for text output.

- normattr: default text attribute (set when normvideo() is called).

- currmode: current video mode. This value is fixed to C80 (80 columns color display).

- screenheight, screenwidth: width and height of the screen, in characters. This values ARE meaningful, because the console size can be changed by the user.

- curx, cury: current cursor possition.


gotoxy

Function: gotoxy

Synopsis
#include <tcconio.h>
void gotoxy(int x,int y);

Description

Changes the current text cursor position. Valid values ranges are (1..sceenwidth, 1 .. screenheight),

The point (1,1) represents the coordinates of the upper left corner of the text display.


highvideo

Function: highvideo

Synopsis
#include <tcconio.h>
void highvideo(void);

link with tcconio.lib

Description

Makes subsequent output text to appear brighter. If the text is already in high video, the function does nothing.


lowvideo

Function: lowvideo

Synopsis
#include <tcconio.h>
void lowvideo(void);

Description

Makes subsequent output text to appear darker. If the text is already in low video (the default), the function does nothing.


movetext

Function: movetext

Synopsis
#include <tcconio.h>
int movetext(int left, int top, int right, int bottom, int destleft, int destright);

link with tcconio.lib

Description

Copies (despite of its name) a rectangular section of the screen to another place. Parameters are:

- left, right, top, bottom: coordinates that describe the source rectangle. The upper left corner of the screen is (1,1).

- destleft, desttop: coordinates of the uppper left corner of the destination rectangle. The destination rectangle has the same size of the source one.

Returns

The return value is 1 if the text could be copied or 0 if it was not, for example because the coordinates were invalid.


normvideo

Function: normvideo

Synopsis
#include <tcconio.h>
void normvideo(void);

link with tcconio.lib

Description

Sets the default colors for the text console (gray characters over a black background).


textbackground

Function: textbackground

Synopsis
#include <tcconio.h>
void textbackground(int color);

link with tcconio.lib

Description

Sets a new background color for the text mode console. The colors are:

BLACK, BLUE, GREEN, CYAN, RED, MAGENTA, BROWN, LIGHTGRAY,

DARKGRAY, LIGHTBLUE, LIGHTGREEN, LIGHTCYAN, LIGHTRED, LIGHTMAGENTA, YELLOW, WHITE.

The first 8 colors are in low video, while the last 8 are in high video. This means that if you have set the text color to BLUE and call highvideo(), subsequent text will be displayed in LIGHTBLUE.


textcolor

Function: textcolor

Synopsis
#include <tcconio.h>
void textcolor(int color);

link with tcconio.lib

Description

Sets a new color for text. Color can be any of the following:

BLACK, BLUE, GREEN, CYAN, RED, MAGENTA, BROWN, LIGHTGRAY,

DARKGRAY, LIGHTBLUE, LIGHTGREEN, LIGHTCYAN, LIGHTRED, LIGHTMAGENTA, YELLOW, WHITE.

The first 8 colors are in low video, while the last 8 are in high video. This means that if you have set the text color to BLUE and call highvideo(), subsequent text will be displayed in LIGHTBLUE.


textmode

Function: textmode

Synopsis
#include <tcconio.h>
void textmode(int newmode);

Description

This function resets the text mode screen to its normal mode: clears the screen, sets the default colors and shows the normal cursor shape.

The newmode argument is not used, and is there for compatibility reasons with the old Turbo C conio functions.


wherex wherey

Function: wherex wherey

Synopsis
#include <tcconio.h>
int wherex(void);
int wherey(void);

Description

This functions return the current position of the text cursor, in characters.


Bignum Funcs

LCC-Win32 Bignum Library Functions

atoquad | operator == | quadacos | quadln
BignumPrecision | operator > | quadacosh | quadpgcd
double2quad | operator >= | quadasin | quadpow
doubleToquad | operator < | quadasinh | quadrand
fact | operator <= | quadatan | quadratio
logb2 | operator - | quadatanh | quadround
long2quad | operator -= | quadcmp | quadsin
longlongToquad | operator * | quadcos | quadsinh
longToquad | operator *= | quadcosh | quadsqrt
newBignum | operator + | quadexp | quadtan
operator = | operator += | quadexpformat | quadtanh
operator / | quad2a | quadfloor | quadtrunc
operator /= | quad2double | quadintegerp |
operator != | quad2ll | quadisqrt |


atoquad

Function: atoquad

Synopsis
#include <bignums.h>
pBignum atoquad(char * str);

Description
Converts the given string to a newly allocated big number.

Returns

atoquad returns a pointer to the newly created bignum object.

Example

pBig a = atoquad("568877666599988777755443334");


BignumPrecision

Function: BignumPrecision

Synopsis
#include <bignums.h>
int BignumPrecision(int);

Description

Sets the precision to a given value. Each big number is represented as a vector of integers. For each integer, the precision increases of 30 bits. The argument is the number of integers to reserve for each big number. For instance, if you request a precision of 30, 30 integers of 30 bits precision will be used, i.e. 900 bits per big number.

Returns

Returns the absolute value


double2quad

Function: double 2quad

Synopsis
#include <bignums.h>
void double2quad(double x, pBignum y);

Description
Converts the given double to a bignum and stores the result in the given bignum y that must have been previously allocated.

Returns

double2quad does not return a value.


doubleToquad

unction: double Toquad

Synopsis
#include <bignums.h>
pBignum doubleToquad(double x);

Description
Converts the given double to a newly allocated big number.

Returns

doubleToquad returns a pointer to the newly created bignum object.


fact

Function: fact

Synopsis
#include <bignums.h>
pBignum fact(int n);

Description

Returns n!


logb2

Function: logb2

Synopsis
#include <bignums.h>
pBignum logb2(pBignum a);

Description

Returns a newly allocated big number with the log base 2 of its argument.


long2quad

Function: long 2quad

Synopsis
#include <bignums.h>
void long2quad(long x, pBignum y);

Description
Converts the given long to a bignum and stores the result in the given bignum y that must have been previously allocated.

Returns

long2quad does not return a value.


longlongToquad

Function: longlong Toquad

Synopsis
#include <bignums.h>
pBignum longlongToquad(long long x);

Description
Converts the given 64 bit integer to a newly allocated big number.

Returns

longlongToquad returns a pointer to the newly created bignum object.


longToquad

Function: longToquad

Synopsis
#include <bignums.h>
pBignum longToquad(long x);

Description
Converts the given long integer to a newly allocated big number.

Returns

longToquad returns a pointer to the newly created bignum object.


newBignum

Function: newBignum

Synopsis
#include <bignums.h>
pBignum
    newBignum(void)
pBignum newBignum(int x);
pBignum newBignum(double x);
pBignum newBignum(long long x);
pBignum newBignum(char * str);

Description

Creates a new bignum and returns a pointer to the bignum object. The following list shows the different ways of initializing the bignum object.

newBignum(void)
Returns a new big number initialized to zero
newBignum(int x)
Returns a new bignum initialized to the given integer.
newBignum(double x)
Returns a new big number initialized to the given double precision number.
newBignum(long long x)
Returns a new big number initialized to the given long long integer.
newBignum(char * str)
Returns a new big number initialized to the converted value of the given string.


operator assignment

Function: operator =

Synopsis

#include <bignums.h>
pBignum operator=(pBignum
    &a, int b);
pBignum operator=(double &a, pBignum b);
pBignum operator=(pBignum &a, double b);

Description

Assignments from int, from double or to double.


operator division

Function: operator /

Synopsis
#include <bignums.h>
operator/(pBignum a, pBignum b);

Description

Returns newly allocated big number with the result of the division.


operator division equal

Function: operator /=

Synopsis
#include <bignums.h>
operator/=(pBignum a, pBignum b);

Description

Stores the division result in its first argument. Returns first argument..


operator does not equal

Function: operator !=

Synopsis
#include <bignums.h>
int operator!=(pBignum a, pBignum b);
int operator!=(pBignum a, long b);
int operator!=(pBignum a, double b);
int operator!=(long a, pBignum b);
int operator!=(double a, pBignum b);

Description

If a does not equal b, returns 1, else returns 0. (a!=b)?1:0


operator equals

Function: operator ==
Synopsis
#include <bignums.h>
int operator==(pBignum a, pBignum b);
int operator==(pBignum a, long b);
int operator==(pBignum a, double b);
int operator==(long a, pBignum b);
int operator==(double a, pBignum b);

Description
If a equals b, returns 1, else returns 0. (a==b)?1:0


operator greater than

Function: operator >

Synopsis
#include <bignums.h>
int operator>(pBignum a, pBignum b);
int operator>(pBignum a, long b);
int operator>(pBignum a, double b);
int operator>(long a, pBignum b);
int operator>(double a, pBignum b);

Description

If a is greater than b, returns 1, else returns 0. (a>b)?1:0


operator greater than or equal

Function: operator >=
Synopsis
#include <bignums.h>
int operator>=(pBignum a, pBignum b);
int operator>=(pBignum a, long b);
int operator>=(pBignum a, double b);
int operator>=(long a, pBignum b);
int operator>=(double a, pBignum b);

Description
If a is greater than or equal to b, returns 1, else returns 0. (a>=b)?1:0


operator less than

Function: operator <
Synopsis
#include <bignums.h>
int operator<(pBignum a, pBignum b);
int operator<(pBignum a, long b);
int operator<(pBignum a, double b);
int operator<(long a, pBignum b);
int operator<(double a, pBignum b);

Description
If a is less than b, returns 1, else returns 0. (a<b)?1:0


operator less than or equal

Function: operator <=
Synopsis
#include <bignums.h>
int operator<=(pBignum a, pBignum b);
int operator<=(pBignum a, long b);
int operator<=(pBignum a, double b);
int operator<=(long a, pBignum b);
int operator<=(double a, pBignum b);

Description
If a is less than or equal to b, returns 1, else returns 0. (a<=b)?1:0


operator minus

Function: operator -

Synopsis
#include <bignums.h>
operator-(pBignum a, pBignum b);

Description

Returns newly allocated big number with the result of the subtraction.


operator minus equal

Function: operator -=

Synopsis
#include <bignums.h>
operator-=(pBignum a, pBignum b);

Description

Returns a pointer to the first argument. The subtraction is stored in the first argument, no new storage is used.


operator multiply

Function: operator *

Synopsis
#include <bignums.h>
operator*(pBignum a, pBignum b);

Description

Returns newly allocated big number with the result of the multiplication.


operator multiply equal

Function: operator *=

Synopsis
#include <bignums.h>
operator*=(pBignum a, pBignum b);

Description

Stores the multiplication result in its first argument. Returns first argument.


operator plus

Function: operator +

Synopsis
#include <bignums.h>
operator+(pBignum a, pBignum b);
pBignum operator+(pBignum a, long b);
... other conversions

Description

Returns newly allocated big number with the result of the addition.


operator plus equal

Function: operator +=

Synopsis
#include <bignums.h>
operator+=(pBignum a, pBignum b);

Description

Returns the addition of the first operand and the second. No new storage, the result is stored in the first operator.


quad2a

Function: quad toa

Synopsis
#include <bignums.h>
void quadtoa(pBignum x, unsigned char *outbuf);

Description
Formats a given big number as text in the given output buffer.

Returns

quad2a does not return a value.


quad2double

Function: quad2double

Synopsis
#include <bignums.h>
double quad2double(pBignum x);

Description
Converts the given bignum to a double.

Returns

quad2double returns the floating point double representation of the bignum.


quad2ll

Function: quad2ll

Synopsis
#include <bignums.h>
long long quad2ll(pBignum x);

Description
Converts the given bignum to a long long.

Returns

quad2double returns the long long representation of the bignum.


quadacos

Function: quadacos

Synopsis
#include <bignums.h>
pBignum quadacos(pBignum x);

Description

Returns the arc cosine of x.


quadacosh

Function: quadacosh

Synopsis
#include <bignums.h>
pBignum quadacosh(pBignum x);

Description

Returns the Hyperbolic arc cos of x.


quadasin

Function: quadasin

Synopsis
#include <bignums.h>
pBignum quadasin(pBignum x);

Description

Returns the arc sine of x.


quadasinh

Function: quadasinh

Synopsis
#include <bignums.h>
pBignum quadsinh(pBignum x);

Description

Returns the Hyperbolic arc sine of x.


quadatan

Function: quadatan

Synopsis
#include <bignums.h>
pBignum quadatan(pBignum x);

Description

Returns the arc Tangent of x.


quadatanh

Function: quadatanh

Synopsis
#include <bignums.h>
pBignum quadatanh(pBignum x);

Description

Returns the arc Hyperbolic tangent of x.


quadcmp

Function: quadcmp

Synopsis
#include <bignums.h>
int quadcmp(pBignum a, pBignum b);

Description

Returns –1 if a < b, 0 if a == b, and 1 if a > b


quadcos

Function: quadcos

Synopsis
#include <bignums.h>
pBignum quadcos(pBignum x);

Description

Returns the cosine of x.


quadcosh

Function: quadcosh

Synopsis
#include <bignums.h>
pBignum quadsinh(pBignum x);

Description

Returns the Hyperbolic cos of x.


quadexp

Function: quadexp

Synopsis
#include <bignums.h>
pBignum quadexp(pBignum a);

Description

Returns newly allocated big number containing e raised to the first argument.


quadexpformat

Function: quadexpformat

Synopsis
#include <bignums.h>
void quadexpformat(pBignum x, unsigned char *outbuf, int width, int decimals);

Description
Formats a given big number “x” as text in the buffer pointed to by “outbuf”, with the given width and decimals.

Returns

quadexpformatl does not return a value.


quadfloor

Function: quadfloor

Synopsis
#include <bignums.h>
pBignum quadfloor(pBignum x);

Description

Returns the largest integer less than x.


quadintegerp

Function: quadintegerp

Synopsis
#include <bignums.h>
pBignum quadintegerp(pBignum x);

Description

Returns 1 if the given big number is represented as an exact integer, or 0 if it is represented as a ratio.


quadisqrt

Function: quadisqrt

Synopsis
#include <bignums.h>
pBignum quadisqrt(pBignum a);

Description

Returns a newly allocated big number with the integer square root of its argument.


quadln

Function: quadln

Synopsis
#include <bignums.h>
pBignum quadln(pBignum a);

Description

Returns the natural logarithm of its argument in a newly allocated big number.


quadpgcd

Function: quadpgcd

Synopsis
#include <bignums.h>
pBignum quadpgcd(pBignum x, pBignum y);

Description

Returns the gcd of the two big numbers.


quadpow

Function: quadpow

Synopsis
#include <bignums.h>
pBignum quadpow(pBignum a, pBignum b);
pBignum quadpow(pBignum a, int b);

Description

Returns a newly allocated big number with the result of elevating the first argument to the second argument power.

Returns

result = first ^ second


quadrand

Function: quadrand

Synopsis
#include <bignums.h>
pBignum quadrand(pBignum a);

Description

Returns a random number between 0 and the given big number.


quadratio

Function: quadratio

Synopsis
#include <bignums.h>
pBignum quadratio(int numerator, int denominator);

Description

Returns a new big number built as a ratio from the given integers.


quadround

Function: quadround

Synopsis
#include <bignums.h>
pBignum round(pBignum x, int n);

Description

Rounds the given number to n places. Returns a new number, the input is not modified.


quadsin

Function: quadsin

Synopsis
#include <bignums.h>
pBignum quadsin(pBignum x);

Description

Returns the sine of x.


quadsinh

Function: quadsinh

Synopsis
#include <bignums.h>
pBignum quadsinh(pBignum x);

Description

Returns the Hyperbolic sine of x.


quadsqrt

Function: quadsqrt

Synopsis
#include <bignums.h>
pBignum quadsqrt(pBignum a);

Description

Returns a newly allocated big number with the square root of its argument.


quadtan

Function: quadtan

Synopsis
#include <bignums.h>
pBignum quadtan(pBignum x);

Description

Returns the Tangent of x.


quadtanh

Function: quadtanh

Synopsis
#include <bignums.h>
pBignum quadtanh(pBignum x);

Description

Returns the Hyperbolic tangent of x.


quadtrunc

Function: quadtrunc

Synopsis
#include <bignums.h>
pBignum quadtrunc(pBignum x);

Description

Return the nearest integer to x but not larger.


sqrt

Function: FileEncrypt

Synopsis
#include <netutils.h>
int FileEncrypt(char *inputfile,char *password,char *outputfile,int direction);
Link with netutils.lib

Description

This function will encrypt or decrypt the given file using the given password, that should be at least 8 characters long. The "direction" argument is one for encryption, zero for decryption.

If the "outputfile" argument is NULL, the input file will be overwritten with the result.

Returns

Returns zero for success, or:

  • -2 for password too short
  • -3 for lack of memory
  • -4 for input file not found
  • -5 for output file creation failure
  • -6 for wrong decoding password
  • -7 for bad authentication

Credits

This file encryption utility has been adapted for lcc-win32 from the original of Mr Brian Gladman.

---------------------------------------------------------------------------
Copyright (c) 2002, Dr Brian Gladman < >, Worcester, UK.
All rights reserved.

LICENSE TERMS

The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:

1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;

2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;

3. the copyright holder's name is not used to endorse products
built using this software without specific written permission.

ALTERNATIVELY, provided that this notice is retained in full, this product
may be distributed under the terms of the GNU General Public License (GPL),
in which case the provisions of the GPL apply INSTEAD OF those given above.

DISCLAIMER

This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
-------------------------------------------------------------------------

Example

#include <netutils.h>
#include <stdio.h>
int main(int argc,char *argv[])
{
    char *outfile,*infile,*passwd;
    int flag,r;
    if (argc < 4) {
usage:
        printf("Usage: fcrypt <-d or -e> <password> <input file> [output file]\n");
        printf("-d means decrypt, -e means encrypt. ");
        printf("Password should be at least 8 characters long\n");
        printf("If output name is absent, input file is replaced by ");
        printf("the encrypted version\n");
        return 1;
    }
    if (argv[1][0] == '-') {
        if (argv[1][1] == 'd')
            flag = 0;
        else if (argv[1][1] == 'e')
            flag = 1;
        else goto usage;
    }
    else goto usage;
    passwd = argv[2];
    infile = argv[3];
    if (argc == 4) {
        outfile = NULL;
    }
    else
        outfile = argv[4];
    r = FileEncrypt(infile,passwd,outfile,flag);
    switch(r) {
        case -2:
            printf("Password should be at least 8 characters\n");
            break;
        case -3:
            printf("Out of memory");
            break;
        case -4:
            printf("file '%s' does not exist\n",infile);
            break;
        case -5:
            printf("Can't create output file\n");
            break;
        case -6:
            printf("Bad password\n");
            break;
        case -7:
            printf("Bad authentication. File corrupt?\n");
            break;
    }
    return r;
}


sqrt

Function: Sha1FromFile

Synopsis
#include <netutils.h>
int Sha1FromFile(char *filename , char *digest);
int Sha1FromBuffer(char *buffer,int len,char *digest)

Description

This function returns a unique 160 bits value from the data in the given file or in the given buffer, written into the variable "digest", that must be at least 160 bits (20 bytes) long.

The hash is used as a unique value of fixed size representing a large amount of data. Hashes of two sets of data should match if the corresponding data also matches. Small changes to the data result in large, unpredictable changes in the hash. Note that the resulting digest will NOT be zero terminated.

Returns

Returns zero if everything worked, or a negative number if an error occurred: the file could not be opened, the digest pointer was NULL, the given length was less or equal to zero.

Example
#include <math.h>
#include <stdio.h>
int main(int argc,char *argv[])
{
    unsigned char digest[20];
    int i,j;
    if (argc < 2) {
    puts("Usage: sha1 <file name>\n");
    return(0);
    }
    if (Sha1FromFile(argv[1],digest)) {
        fprintf(stderr,"File '%s' not found\n",argv[1]);
        return 1;
    }

    for (i = 0; i < 5; i++) {
        for (j = 0; j < 4; j++) {
            printf("%02X", digest[i*4+j]);
        }
        putchar(' ');
    }
    putchar('\n');
}

Credits

The implementation of this function is based on the software published by Steve Reid <steve@edmweb.com>.


GC Funcs

LCC-Win32 GC Library Functions

GC_exclude_static_roots | GC_malloc_atomic
GC_expand_hp | GC_malloc_ignore_off_page
GC_free | GC_realloc
GC_get_heap_size | GC_set_max_heap_size
GC_malloc | GC_size
 | GC_set_warn_proc


Preparing your programs for use with the memory manager.

Using the memory manager (gc) is very simple but there are some rules you should be aware of.

1. Never store pointers to objects allocated with the collector in inaccessible places. For instance:

1.1. Do not store pointers in the window extra bytes, without keeping a pointer somewhere in memory, to indicate to the collector that that object is being used. The memory manager has no access to those pointers, inside the systems data structures. It will therefore assume that memory can be reclaimed, with bad consequences for your program.

1.2. Do not store pointers at odd addresses, or at addresses not multiple of four. The compiler and the linker take care of aligning memory such that this always is the case for all your data when the program starts. After that, it is up to you to follow this rule.

2. Do not store pointers in arrays declared as integer, or in DWORDs. The compiler generates type information and makes special calls to the memory manager, when the object allocated contains no pointers. Basically, it tells the collector to ignore those memory locations, since they do not contain pointers. If you circumvent this with casts, the collector will not know that the data is being used and will reclaim it.

3. It is better, though not required, to set all pointers that are no longer needed to NULL, to avoid retaining too much data unnecessarily. If you do not do this, the data will be retained until the scope of the pointer finishes. Pointers stored in global variables have indefinite scope in time, so the data they point to will never be reclaimed and the program will leak. A similar situation holds for pointers stored as local variables in the main() function.


GC_exclude_static_roots

Function: GC_exclude_static_roots

Synopsis
#include <gc.h>
void GC_exclude_static_roots(GC_PTR start, GC_PTR_finish);

Description
Inform the collector that a certain section of statically allocated memory contains no pointers to garbage collected memory. Thus it need not be scanned. This is sometimes important if the application maps large read/write files into the address space, which could be mistaken for dynamic library data segments on some systems.

Returns

No return value


GC_expand_hp

Function: GC_expand_hp

Synopsis
#include <gc.h>
void GC_expand_hp(size_t number_of_bytes);

Description
Explicitly increase the heap size. This is normally done automatically if a garbage collection failed to GC_reclaim enough memory. Explicit calls to GC_expand_hp may prevent unnecessarily frequent collections at program startup.

Returns

No return value


GC_free

Function: GC_free

Synopsis
#include <gc.h>
void GC_free(GC_PTR object_addr);

Description

Explicitly deallocate an object returned by GC_malloc or GC_malloc_atomic. Not necessary, but can be used to minimize collections if performance is critical. Probably a performance loss for very small objects (<= 8 bytes).

Returns

No return value


GC_get_heap_size

Function: GC_get_heap_size

Synopsis
#include <gc.h>
size_t GC_get_heap_size(void);

Description

Excludes collector private data structures. Includes empty blocks and fragmentation loss. Includes some pages that were allocated but never written.

Returns

Return the number of bytes in the heap.


GC_malloc

Function: GC_malloc

Synopsis
#include <gc.h>
GC_PTR GC_malloc(size_t nbytes);

Description

Allocate an object of size nbytes. Unlike malloc, the object is cleared before being returned to the user. GC_malloc will invoke the garbage collector when it determines this to be appropriate.

GC_malloc may return 0 if it is unable to acquire sufficient space from the operating system. This is the most probable consequence of running out of space. Other possible consequences are that a function call will fail due to lack of stack space, or that the collector will fail in other ways because it cannot maintain its internal data structures, or that a crucial system process will fail and take down the machine. Most of these possibilities are independent of the malloc implementation.

Returns

Return the pointer to the newly allocated block of memory.


GC_malloc_atomic

Function: GC_malloc_atomic

Synopsis
#include <gc.h>
GC_PTR GC_malloc_atomic(size_t nbytes);

Description
Allocate an object of size nbytes that is guaranteed not to contain any pointers. The returned object is not guaranteed to be cleared. Can always be replaced by GC_malloc, but results in faster collection times. The collector will probably run faster if large character arrays, etc. are allocated with GC_malloc_atomic than if they are statically allocated.

Returns

Returns the pointer to the newly allocated block of memory.


GC_malloc_ignore_off_page

Function: GC_malloc_ignore_off_page

Synopsis
#include <gc.h>
GC_PTR GC_malloc_ignore_off_page(size_t number_of_bytes);

Description

Identical to GC_malloc, but the client promises to keep a pointer to be somewhere within the first 256 bytes of the object while it is live. This pointer should normally be declared volatile to prevent interference from compiler optimizations. This is the recommended way to allocate anything that is likely to be larger than 100Kbytes or so. (GC_malloc may result in failure to reclaim such objects.)

Returns

Return the pointer to the newly allocated block of memory.


GC_realloc

Function: GC_realloc

Synopsis
#include <gc.h>
GC_PTR GC_realloc(GC_PTR old_obejct, size_t new_size);

Description

Change the size of object to be new_size. Returns a pointer to the new object, which may, or may not, be the same as the pointer to the old object. The new object is taken to be atomic if the old one was. If the new object is composite and larger than the original object, then the newly added bytes are cleared (we hope). This is very likely to allocate a new object, unless MERGE_SIZES is defined in gc_priv.h. Even then, it is likely to recycle the old object only if the object is grown in small additive increments (which, we claim, is generally bad coding practice.)

Returns

Return the pointer to the newly re-allocated block of memory.


GC_set_max_heap_size

Function: GC_set_max_heap_size

Synopsis
#include <gc.h>
void GC_set_max_heap_size(GC_word n);

Description

Limit the heap size to n bytes. Useful when you're debugging, especially on systems that don't handle running out of memory well. If n is zero, the heap size is unbounded. This is the default.

Returns

No return value.


GC_size

Function: GC_size

Synopsis
#include <gc.h>
size_t GC_size(GC_ptr pointer_to_object);

Description

Note that the size can be greater than the size you requested since GC_malloc can round up the request.

Returns

Returns the size in bytes of the object pointed to by its argument.


GC_set_warn_proc

Function: GC_set_warn_proc

Synopsis
#include <gc.h>
typedef void (*GC_warn_proc) (char *msg, GC_word arg);
GC_API GC_warn_proc GC_set_warn_proc(GC_warn_proc p);

Description

Can be used to redirect warnings from the collector. Such warnings should be rare, and should not be ignored during code development.


Intrinsic Funcs

LCC-Win32 Intrinsic Functions

_bsf | _fcos | _fsin
_bsr | _fistp | _fsincos
_bswap | _fldl2e | _overflow
_carry | _fldlg2 | _rdtsc
_cpuid | _fldln2 | _rint
_cpuidPresent | _fldpi |


_bsf

Function: _bsf

Synopsis
#include <intrinsics.h>
int _bsf(long arg);

Description

Returns an integer with the index of the first non-zero bit in the given integer starting with the least significant bit.


_bsr

Function: _bsr

Synopsis
#include <intrinsics.h>
int _bsr(long arg);

Description

Returns an integer with the index of the first non-zero bit in the given integer, starting with the most significant bit.


_bswap

Function: _bswap

Synopsis
#include <intrinsics.h>
int _bswap(long);

Description

_bswap swaps the order of the four bytes of a 32-bit register: bits 0-7 exchange places with bits 24-31, and bits 8-15 swap with bits 16-23.

Returns

The _bswap function returns the byte swapped long integer


_carry

Function: _carry

Synopsis
#include <intrinsics.h>
int _carry(void);

Description

The value returned from _carry is VERY volatile since most calculations set/unset it. You should not assume that the value returned is the value of the last C instruction performed, since the lcc’s optimizer could re-arrange the instructions. The best way to do this is to write only one operation, immediately followed by an assignment expression. For example you should write:

a = b+c;

instead of

a = b+foo(5)+78;

If you test the carry/overflow flag at the end of a complicated expression, you cannot know the exact operation that produced the error. Besides, since many operations change this flag, an actual overflow could be hidden by the operations that follow it.

Returns

Returns the carry flag as an integer.


_cpuid

Function: _cpuid

Synopsis
#include <intrinsics.h>
long long _cpuid(_CPUID *);

Description

This function fills the fields of the given _CPUID structure. This structure receives information about the CPU as given by the CPUID machine instruction.

Since this intrinsic will provoke an illegal instruction if used in a machine that doesn't support the CPUID instruction, you should verify this before with the _cpuidPresent() function.

Portability

This intrinsic function is specific to the lcc-win32 system. See intrinsics.h for a description of the various fields of this struct.

typedef struct _cpuIdentification {
    char Vendor[16];
    unsigned Stepping:4;
    unsigned Model:4;
    unsigned Family:4;
    unsigned Type:2;
    unsigned Reserved1:18;
    unsigned FpuPresent:1;
    unsigned VME:1;
    unsigned DebuggingExtensions:1;
    unsigned PageSizeExtensions:1;
    unsigned TimeStampCounter:1;
    unsigned MSR:1;
    unsigned PhysicalAddressExtensions:1;
    unsigned MachineCheckException:1;
    unsigned CMPXCHG8B:1;
    unsigned APICOnChip:1;
    unsigned reserved2:1;
    unsigned SEP:1;
    unsigned MTRR:1;
    unsigned PGE:1;
    unsigned MCA:1;
    unsigned CMOV:1;
    unsigned FGPAT:1;
    unsigned PSE36:1;
    unsigned PN:1;
    unsigned reserved3:4;
    unsigned MMX:1;
    unsigned FXSR:1;
    unsigned XMM:1;
    unsigned SSE2:1;
    unsigned SelfSnoop:1;
    unsigned reserved4:1;
    unsigned reserved5:2;
}_CPUID;


_cpuidPresent

Function: _cpuidPresent

Synopsis
#include <intrinsics.h>
int _cpuidPresent(void);

Description

This function will return 1 if the CPUID instruction is supported by the machine, zero otherwise.

Portability

This intrinsic function is specific to the lcc-win32 system.


_fcos

Function: _fcos

Synopsis
#include <intrinsics.h>
double _fcos(arg);

Description

_fcos calculates the cosine of arg (in radians).

Returns

Returns cos(arg).


_fistp

Function: _fistp

Synopsis
#include <intrinsics.h>
int _fistp(double arg);

Description

Returns a long integer from the given double using the rounding mode that is in effect at the time of the call. Normally this should be rounding to nearest number, since lcc-win32 never changes this setting. This allows for very fast rounding. Remember that to satisfy the rules of ANSI C, lcc-win32 is forced to set the rounding to truncation, round the figure, and then restore the original mode. This can be avoided by using this intrinsic function to round floating point data.

Returns

Returns the integer of the rounded double.


_fldl2e

Function: _fldl2e

Synopsis
#include <intrinsics.h>
double _fldl2e(void);

Description

_fldl2e returns the logarithm base 2 of e.


_fldlg2

Function: _fldlg2

Synopsis
#include <intrinsics.h>
double _fldlg2(void);

Description

_fldlg2 returns the logarithm base 10 of e.


_fldln2

Function: _fldln2

Synopsis
#include <intrinsics.h>
double _fldln2(void);

Description

_fldln2 returns the natural logarithm (base e) of 2.


_fldpi

Function: _fldpi

Synopsis
#include <intrinsics.h>
double _fldpi(void);

Description

_fldpi returns the constant PI in floating point format.

Returns

PI


_fsin

Function: _fsin

Synopsis
#include <intrinsics.h>
double _fsin(arg);

Description

_fsin calculates the sin of arg (in radians).

Returns

Returns sin(arg).


_fsincos

Function: _fsincos

Synopsis
#include <intrinsics.h>
double _fsincos(arg, cos *x);

Description

_fsincos calculates the sin of arg (in radians) and also calculates the cos of arg.

Returns

Returns sin(arg), and stores the cosine in the address pointed by cos *x.


_rdtsc

Function: _GetStackPointer

Synopsis
#include <intrinsics.h>
void * _stdcall _GetStackPointer(void);

Description

The _GetStackPointer function returns the current machine stack.

Returns

The current stack, (ESP).


_overflow

Function: _overflow

Synopsis
#include <intrinsics.h>
int _overflow(void);

Description

Returns the value of the overflow flag. The same considerations apply as to the _carry() function above.


_rdtsc

Function: _rdtsc

Synopsis
#include <intrinsics.h>
long long _stdcall _rdtsc(void);

Description

The _rdtsc function reads the time stamp counter register in the Pentium CPU.

Returns

The _rdtsc function returns a 64 bit unsigned integer that has the number of cycles the CPU has executed since the machine was last reset. This counter will updated each clock cycle, and represent a very high accuracy counter.

Note that in a multitasking operating system, the process that is executing can be pre-empted by the OS, and then control passed to another process. During this time, the counter continues to tick. Therefore, this is a counter that is useful for elapsed CPU time, but not for measuring the process time.


_rint

Function: _rint

Synopsis
#include <intrinsics.h>
int _rint(double arg);

Description

Rounds the given floating point number to an integer using the current rounding mode. By default, the rounding mode is round to nearest number. To use this, you should include <math.h>.


Lists are containers that support the storage and retrieval of data that is not contiguous in memory

Perl compatible regular expressions

The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax and semantics as Perl, with just a few differences. The current implementation of PCRE (release 4.x) corresponds approximately with Perl 5.8, including support for UTF-8 encoded strings. However, this support has to be explicitly enabled; it is not the default.

The library was written by Philip Hazel <ph10@cam.ac.uk>

University of Cambridge Computing Service,
Cambridge, England. Phone: +44 1223 334714.

Copyright (c) 1997-2003 University of Cambridge

PCRE API and PCRE details

PCRE has its own native API, which is described in this document. For details about Perl regular expressions, see here.

The native API function prototypes are defined in the header file pcre.h The header file defines the macros PCRE_MAJOR and PCRE_MINOR to contain the major and minor release numbers for the library. Applications can use these to include support for different releases.

The functions pcre_compile(), pcre_study(), and pcre_exec() are used for compiling and matching regular expressions. A sample program that demonstrates the simplest way of using them is given in the file pcredemo.c. The pcresample documentation describes how to run it.

There are convenience functions for extracting captured substrings from a matched subject string. They are:

pcre_copy_substring() pcre_copy_named_substring()
pcre_get_substring() pcre_get_named_substring()
pcre_get_substring_list()

pcre_free_substring() and pcre_free_substring_list() are also provided, to free the memory used for extracted strings.

The function pcre_maketables() is used (optionally) to build a set of character tables in the current locale for passing to pcre_compile().

The function pcre_fullinfo() is used to find out information about a compiled pattern; pcre_info() is an obsolete version which returns only some of the available information, but is retained for backwards compatibility. The function pcre_version() returns a pointer to a string containing the version of PCRE and its date of release.

The global variables pcre_malloc and pcre_free initially contain the entry points of the standard malloc() and free() functions respectively. PCRE calls the memory management functions via these variables, so a calling program can replace them if it wishes to intercept the calls. This should be done before calling any PCRE functions.

The global variable pcre_callout initially contains NULL. It can be set by the caller to a "callout" function, which PCRE will then call at specified points during a matching operation. Details are given in the pcrecallout documentation.


Perl compatible regular expressions tutorial

What is a regular expression?

An expression can be an elementary unit (or atom) or the joining of several elementary units.

An elementary unit is either a single character or a metacharacter.

A metacharacter is a character that has a special meaning other than itself. For instance, the letter 'b' is an atom and a character. The character '^' stands for example for the beginning of a line. We have then an expression line

^b

meaning "the character b at the beginning of a line"

You can group atoms using parentheses, like this

(^b)


Qualifiers

Qualifiers specify how many times the preceeding expression may appear in a match. The qualifiers characters are ?, + and *.

? This character means that the preceeding expression can appear either zero or one time.

+ This character means that the preceeding expression must appear at least once, making it a required item.

* This character means that the preceeding expression may appear zero or more times. Use it with care since it matches zero occurences unexpected results may occur.


Ranges

Like qualifiers, ranges specify how many times the preceeding expression may appear. They have the following syntax:

{ m }

or

{m,n}

The first means that the preceeding expression must appear exactly <m> times, for instance:

{12}

The preceeding expression must appear 12 times.

The second means that the expression must at least appear m times and at most n times. For instance:

{3,6}

means that the expression must appear at least 3 times and at most 6 times.

It is possible to leave the second number unspecified using:

{3,}

This means that the expression must appear at least 3 times, but it has no upper bound in the number of times it can appear.


Ranges

Matching line ends

The characters ^ and $ match the beginning and the end of a line respectively. Note that they do not consume any characters in the match, they just indicate a position within a text line, so it is not necessary to put them in an eventual replacement expression.

Escapes

What happens if you want to search for a character that is assigned to a meta-character? For instance, reading the above paragraph implies that you can't search for the $ character because it would be interpreted as a line end.

The solution is to escape the metacharacters to give them their plain meaning again. This is done with the backslash \ character this way:

$ means end of line

\$ means the dollar character

Using the logical OR operator

If you want to build an expression where either one OR the other expression should be accepted in a match you use the vertical bar character:

expr1 | expr2

This operator is better understood as the alternate operator. You want a match if one OR the other expression matches.

This operator has the lowest precedence of all regex operators.

Note carefully that it tells the regex engine to match either everything to the left of the vertical bar, or everything to the right of the vertical bar. This may not be (and usually it is not) what you want.

If you want to limit the reach of the or operator, you should use the parentheses for grouping.

For instance:

\b(cat|dog)\b

This tells the regex engine to

\b find a word boundary, then

(cat|dog) either "cat" or "dog", and then

\b another word boundary.

If we had omitted the parentheses, the regex engine would have searched for "a word boundary followed by cat", or, "dog followed by a word boundary and we would have spurious matches like

catalogue

underdog


Ranges

Character classes

Character classes are just sets of characters that will match always only one character in the text. They are enclosed in square brackets like this:

[xyz]

This means that at this position a match will be found if the current examined character is either x,y, or z.

Character classes can be abbreviated with the - character. For instance the expression

[b-i]

means the set of all characters from 'b' to 'i' inclusive. This is handy for representing lower case characters for instance: [a-z] or upper case characters:[A-Z] or just digits: [0-9].

The PCRE package accepts some character classes using the escape character:

\s

represents white space and it is equivalent to putting a space and a tabulation character within square brackets. Note that PCRE accepts \t for tab and \n for new line too.

Matching any arbitrary character.

The metacharacter for matching anything is the point: . This will match any character at the current position.


Ranges

Matching the surrounding text

Using PCRE it is possible to ensure that the text following the current position is either found or not found. There are two types of macthes that do not consume any characters like the ^ or $ metacharacters: they can refer either to the text after the current position (look aheads) or behind the current position (look-behinds).

The characters

(?= indicate the start of a positive (must match) look-ahead

(?! indicate the start of a negative (must not match) look-ahead

) Closes either.

The characters

(?<= indicate the start of a positive (must match) look-behind

(?<! indicate the start of a negative (must not match) look-behind

) Close either.


Matching Floating Point Numbers with a Regular Expression

This example is taken from

http://www.regular-expressions.info/floatingpoint.html.

In this example, I will show you how you can avoid a common mistake often made by people inexperienced with regular expressions. As an example, we will try to build a regular expression that can match any floating point number. Our regex should also match integers, and floating point numbers where the integer part is not given (i.e. zero). We will not try to match numbers with an exponent, such as 1.5e8 (150 million in scientific notation).

At first thought, the following regex seems to do the trick:

[-+]?[0-9]*\.?[0-9]*

This defines a floating point number as an optional sign, followed by an optional series of digits (integer part), followed by an optional dot, followed by another optional series of digits (fraction part).

Spelling out the regex in words makes it obvious: everything in this regular expression is optional. This regular expression will consider a sign by itself or a dot by itself as a valid floating point number. In fact, it will even consider an empty string as a valid floating point number. This regular expression can cause serious trouble if it is used in a scripting language like Perl or PHP to verify user input.

Not escaping the dot is also a common mistake. A dot that is not escaped will match any character, including a dot. If we had not escaped the dot, 4.4 would be considered a floating point number, and 4X4 too.

When creating a regular expression, it is more important to consider what it should not match, than what it should. The above regex will indeed match a proper floating point number, because the regex engine is greedy. But it will also match many things we do not want, which we have to exclude.

Here is a better attempt:

[-+]?([0-9]*\.[0-9]+|[0-9]+)

This regular expression will match an optional sign, that is either followed by zero or more digits followed by a dot and one or more digits (a floating point number with optional integer part), or followed by one or more digits (an integer).

This is a far better definition. Any match will include at least one digit, because there is no way around the [0-9]+ part. We have successfully excluded the matches we do not want: those without digits.

We can optimize this regular expression as:

[-+]?([0-9]*\.)?[0-9]+

If you also want to match numbers with exponents, you can use:

[-+]?([0-9]*\.)?[0-9]+([eE][-+]?[0-9]+)?

Notice how I made the entire exponent part optional by grouping it together, rather than making each element in the exponent optional.


Ranges

Finding repeated words in a line

grep -n "\b(\w+)\s\1\b" pcre.c

4589: UTF8 mode. Leave the test in in all cases; in the special case we have
5041: /* If req_char is set, we know that that character must appear in the subject

\b word boundary
(w+) a group built from word characters ( \w ) one or more times ( + )
\s white space separating the words
\1 The same contents that in the preceeding group
\b Finished by a word boundary


Ranges

Trimming whitespace

You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for

^[ \t]+

and replace with nothing to delete leading whitespace (spaces and tabs).

Search for

[ \t]+$

to trim trailing whitespace. Do both by combining the regular expressions into

^[ \t]+|[ \t]+$

Instead of
[ \t]
which matches a space or a tab, you can expand the character class into
[ \t\r\n]
if you also want to strip line breaks. Or you can use the shorthand \s instead


PCRE REGULAR EXPRESSION DETAILS

The syntax and semantics of the regular expressions supported by PCRE are described below. Regular expressions are also described in the Perl documentation and in a number of other books, some of which have copious examples. Jeffrey Friedl's "Mastering Regular Expressions", published by O'Reilly, covers them in great detail. The description here is intended as reference documentation.

The basic operation of PCRE is on strings of bytes. However, there is also support for UTF-8 character strings. To use this support you must build PCRE to include UTF-8 support, and then call pcre_compile() with the PCRE_UTF8 option. How this affects the pattern matching is mentioned in several places below. There is also a summary of UTF-8 features in the section on UTF-8 support in the main pcre page.

A regular expression is a pattern that is matched against a subject string from left to right. Most characters stand for themselves in a pattern, and match the corresponding characters in the subject. As a trivial example, the pattern

The quick brown fox

matches a portion of a subject string that is identical to itself. The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are encoded in the pattern by the use of metacharacters, which do not stand for themselves but instead are interpreted in some special way.

There are two different sets of meta-characters: those that are recognized anywhere in the pattern except within square brackets, and those that are recognized in square brackets. Outside square brackets, the meta-characters are as follows:

\ general escape character with several uses ^ assert start of string (or line, in multiline mode) $ assert end of string (or line, in multiline mode) . match any character except newline (by default) [ start character class definition | start of alternative branch ( start subpattern ) end subpattern ? extends the meaning of ( also 0 or 1 quantifier also quantifier minimizer * 0 or more quantifier + 1 or more quantifier also "possessive quantifier" { start min/max quantifier

Part of a pattern that is in square brackets is called a "character class". In a character class the only metacharacters are:

\ general escape character ^ negate the class, but only if the first character indicates character range [ POSIX character class (only if followed by POSIX syntax) ] terminates the character class

The following sections describe the use of each of the meta-characters.

BACKSLASH

The backslash character has several uses. Firstly, if it is followed by a non-alphameric character, it takes away any special meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes.

For example, if you want to match a * character, you write \* in the pattern. This escaping action applies whether or not the following character would otherwise be interpreted as a meta-character, so it is always safe to precede a nonalphameric with backslash to specify that it stands for itself. In particular, if you want to match a backslash, you write \\.

If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the pattern (other than in a character class) and characters between a # outside a character class and the next newline character are ignored. An escaping backslash can be used to include a whitespace or # character as part of the pattern.

If you want to remove the special meaning from a sequence of characters, you can do so by putting them between \Q and \E. This is different from Perl in that $ and @ are handled as literals in \Q...\E sequences in PCRE, whereas in Perl, $ and @ cause variable interpolation. Note the following examples:

Pattern PCRE matches Perl matches

\Qabc$xyz\E abc$xyz abc followed by the

contents of $xyz \Qabc\$xyz\E abc\$xyz abc\$xyz \Qabc\E\$\Qxyz\E abc$xyz abc$xyz

The \Q...\E sequence is recognized both inside and outside character classes.

A second use of backslash provides a way of encoding nonprinting characters in patterns in a visible manner. There is no restriction on the appearance of non-printing characters, apart from the binary zero that terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to use one of the following escape sequences than the binary character it represents:

\a alarm, that is, the BEL character (hex 07) \cx "control-x", where x is any character \e escape (hex 1B) \f formfeed (hex 0C) \n newline (hex 0A) \r carriage return (hex 0D) \t tab (hex 09) \ddd character with octal code ddd, or backreference \xhh character with hex code hh \x{hhh..} character with hex code hhh... (UTF-8 mode only)

The precise effect of \cx is as follows: if x is a lower case letter, it is converted to upper case. Then bit 6 of the character (hex 40) is inverted. Thus \cz becomes hex 1A, but \c{ becomes hex 3B, while \c; becomes hex 7B.

After \x, from zero to two hexadecimal digits are read (letters can be in upper or lower case). In UTF-8 mode, any number of hexadecimal digits may appear between \x{ and }, but the value of the character code must be less than 2**31 (that is, the maximum hexadecimal value is 7FFFFFFF). If characters other than hexadecimal digits appear between \x{ and }, or if there is no terminating }, this form of escape is not recognized. Instead, the initial \x will be interpreted as a basic hexadecimal escape, with no following digits, giving a byte whose value is zero.

Characters whose value is less than 256 can be defined by either of the two syntaxes for \x when PCRE is in UTF-8 mode. There is no difference in the way they are handled. For example, \xdc is exactly the same as \x{dc}.

After \0 up to two further octal digits are read. In both cases, if there are fewer than two digits, just those that are present are used. Thus the sequence \0\x\07 specifies two binary zeros followed by a BEL character (code value 7). Make sure you supply two digits after the initial zero if the character that follows is itself an octal digit.

The handling of a backslash followed by a digit other than 0 is complicated. Outside a character class, PCRE reads it and any following digits as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the expression, the entire sequence is taken as a back reference. A description of how this works is given later, following the discussion of parenthesized subpatterns.

Inside a character class, or if the decimal number is greater than 9 and there have not been that many capturing subpatterns, PCRE re-reads up to three octal digits following the backslash, and generates a single byte from the least significant 8 bits of the value. Any subsequent digits stand for themselves. For example:

\040 is another way of writing a space \40 is the same, provided there are fewer than 40 previous capturing subpatterns \7 is always a back reference \11 might be a back reference, or another way of writing a tab \011 is always a tab \0113 is a tab followed by the character "3" \113 might be a back reference, otherwise the character with octal code 113 \377 might be a back reference, otherwise the byte consisting entirely of 1 bits \81 is either a back reference, or a binary zero followed by the two characters "8" and "1"

Note that octal values of 100 or greater must not be introduced by a leading zero, because no more than three octal digits are ever read.

All the sequences that define a single byte value or a single UTF-8 character (in UTF-8 mode) can be used both inside and outside character classes. In addition, inside a character class, the sequence \b is interpreted as the backspace character (hex 08). Outside a character class it has a different meaning (see below).

The third use of backslash is for specifying generic character types:

\d any decimal digit \D any character that is not a decimal digit \s any whitespace character \S any character that is not a whitespace character \w any "word" character W any "non-word" character

Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any given character matches one, and only one, of each pair.

In UTF-8 mode, characters with values greater than 255 never match \d, \s, or \w, and always match \D, \S, and \W.

For compatibility with Perl, \s does not match the VT character (code 11). This makes it different from the the POSIX "space" class. The \s characters are HT (9), LF (10), FF (12), CR (13), and space (32).

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if localespecific matching is taking place (see "Locale support" in the pcreapi page). For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.

These character type sequences can appear both inside and outside character classes. They each match one character of the appropriate type. If the current matching point is at the end of the subject string, all of them fail, since there is no character to match.

The fourth use of backslash is for certain simple assertions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below. The backslashed assertions are

\b matches at a word boundary \B matches when not at a word boundary \A matches at start of subject \Z matches at end of subject or before newline at end \z matches at end of subject \G matches at first matching position in subject

These assertions may not appear in character classes (but note that \b has a different meaning, namely the backspace character, inside a character class).

A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively. The \A, \Z, and \z assertions differ from the traditional circumflex and dollar (described below) in that they only ever match at the very start and end of the subject string, whatever options are set. Thus, they are independent of multiline mode.

They are not affected by the PCRE_NOTBOL or PCRE_NOTEOL options. If the startoffset argument of pcre_exec() is nonzero, indicating that matching is to start at a point other than the beginning of the subject, \A can never match. The difference between \Z and \z is that \Z matches before a newline that is the last character of the string as well as at the end of the string, whereas \z matches only at the end.

The \G assertion is true only when the current matching position is at the start point of the match, as specified by the startoffset argument of pcre_exec(). It differs from \A when the value of startoffset is non-zero. By calling pcre_exec() multiple times with appropriate arguments, you can mimic Perl's /g option, and it is in this kind of implementation where \G can be useful.

Note, however, that PCRE's interpretation of \G, as the start of the current match, is subtly different from Perl's, which defines it as the end of the previous match. In Perl, these can be different when the previously matched string was empty. Because PCRE does just one match at a time, it cannot reproduce this behaviour.

If all the alternatives of a pattern begin with \G, the expression is anchored to the starting match position, and the "anchored" flag is set in the compiled regular expression.

CIRCUMFLEX AND DOLLAR

Outside a character class, in the default matching mode, the circumflex character is an assertion which is true only if the current matching point is at the start of the subject string. If the startoffset argument of pcre_exec() is nonzero, circumflex can never match if the PCRE_MULTILINE option is unset. Inside a character class, circumflex has an entirely different meaning (see below).

Circumflex need not be the first character of the pattern if a number of alternatives are involved, but it should be the first thing in each alternative in which it appears if the pattern is ever to match that branch. If all possible alternatives start with a circumflex, that is, if the pattern is constrained to match only at the start of the subject, it is said to be an "anchored" pattern. (There are also other constructs that can cause a pattern to be anchored.)

A dollar character is an assertion which is true only if the current matching point is at the end of the subject string, or immediately before a newline character that is the last character in the string (by default). Dollar need not be the last character of the pattern if a number of alternatives are involved, but it should be the last item in any branch in which it appears. Dollar has no special meaning in a character class.

The meaning of dollar can be changed so that it matches only at the very end of the string, by setting the PCRE_DOLLAR_ENDONLY option at compile time. This does not affect the \Z assertion.

The meanings of the circumflex and dollar characters are changed if the PCRE_MULTILINE option is set. When this is the case, they match immediately after and immediately before an internal newline character, respectively, in addition to matching at the start and end of the subject string. For example, the pattern /^abc$/ matches the subject string "def\nabc" in multiline mode, but not otherwise. Consequently, patterns that are anchored in single line mode because all branches start with ^ are not anchored in multiline mode, and a match for circumflex is possible when the startoffset argument of pcre_exec() is non-zero. The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set.

Note that the sequences \A, \Z, and \z can be used to match the start and end of the subject in both modes, and if all branches of a pattern start with \A it is always anchored, whether PCRE_MULTILINE is set or not.

FULL STOP (PERIOD, DOT)

Outside a character class, a dot in the pattern matches any one character in the subject, including a non-printing character, but not (by default) newline. In UTF-8 mode, a dot matches any UTF-8 character, which might be more than one byte long, except (by default) for newline. If the PCRE_DOTALL option is set, dots match newlines as well. The handling of dot is entirely independent of the handling of circumflex and dollar, the only relationship being that they both involve newline characters. Dot has no special meaning in a character class.

MATCHING A SINGLE BYTE

Outside a character class, the escape sequence \C matches any one byte, both in and out of UTF-8 mode. Unlike a dot, it always matches a newline. The feature is provided in Perl in order to match individual bytes in UTF-8 mode. Because it breaks up UTF-8 characters into individual bytes, what remains in the string may be a malformed UTF-8 string. For this reason it is best avoided.

PCRE does not allow \C to appear in lookbehind assertions (see below), because in UTF-8 mode it makes it impossible to calculate the length of the lookbehind.

SQUARE BRACKETS

An opening square bracket introduces a character class, terminated by a closing square bracket. A closing square bracket on its own is not special. If a closing square bracket is required as a member of the class, it should be the first data character in the class (after an initial circumflex, if present) or escaped with a backslash.

A character class matches a single character in the subject. In UTF-8 mode, the character may occupy more than one byte. A matched character must be in the set of characters defined by the class, unless the first character in the class definition is a circumflex, in which case the subject character must not be in the set defined by the class. If a circumflex is actually required as a member of the class, ensure it is not the first character, or escape it with a backslash.

For example, the character class [aeiou] matches any lower case vowel, while [^aeiou] matches any character that is not a lower case vowel. Note that a circumflex is just a convenient notation for specifying the characters which are in the class by enumerating those that are not. It is not an assertion: it still consumes a character from the subject string, and fails if the current pointer is at the end of the string.

In UTF-8 mode, characters with values greater than 255 can be included in a class as a literal string of bytes, or by using the \x{ escaping mechanism.

When caseless matching is set, any letters in a class represent both their upper case and lower case versions, so for example, a caseless [aeiou] matches "A" as well as "a", and a caseless [^aeiou] does not match "A", whereas a caseful version would. PCRE does not support the concept of case for characters with values greater than 255. The newline character is never treated in any special way in character classes, whatever the setting of the PCRE_DOTALL or PCRE_MULTILINE options is. A class such as [^a] will always match a newline.

The minus (hyphen) character can be used to specify a range of characters in a character class. For example, [d-m] matches any letter between d and m, inclusive. If a minus character is required in a class, it must be escaped with a backslash or appear in a position where it cannot be interpreted as indicating a range, typically as the first or last character in the class.

It is not possible to have the literal character "]" as the end character of a range. A pattern such as [W-]46] is interpreted as a class of two characters ("W" and "-") followed by a literal string "46]", so it would match "W46]" or "-46]". However, if the "]" is escaped with a backslash it is interpreted as the end of range, so [W-\]46] is interpreted as a single class containing a range followed by two separate characters. The octal or hexadecimal representation of "]" can also be used to end a range.

Ranges operate in the collating sequence of character values. They can also be used for characters specified numerically, for example [\000-\037]. In UTF-8 mode, ranges can include characters whose values are greater than 255, for example [\x{100}-\x{2ff}].

If a range that includes letters is used when caseless matching is set, it matches the letters in either case. For example, [W-c] is equivalent to [][\^_`wxyzabc], matched caselessly, and if character tables for the "fr" locale are in use, [\xc8-\xcb] matches accented E characters in both cases.

The character types \d, \D, \s, \S, \w, and \W may also appear in a character class, and add the characters that they match to the class. For example, [\dABCDEF] matches any hexadecimal digit. A circumflex can conveniently be used with the upper case character types to specify a more restricted set of characters than the matching lower case type. For example, the class [^\W_] matches any letter or digit, but not underscore.

All non-alphameric characters other than \, -, ^ (at the start) and the terminating ] are non-special in character classes, but it does no harm if they are escaped.

POSIX CHARACTER CLASSES

Perl supports the POSIX notation for character classes, which uses names enclosed by [: and :] within the enclosing square brackets. PCRE also supports this notation. For example,

[01[:alpha:]%]

matches "0", "1", any alphabetic character, or "%". The supported class names are

alnum letters and digits alpha letters ascii character codes 0 127 blank space or tab only cntrl control characters digit decimal digits (same as \d) graph printing characters, excluding space lower lower case letters print printing characters, including space punct printing characters, excluding letters and digits space white space (not quite the same as \s) upper upper case letters word "word" characters (same as \w) xdigit hexadecimal digits

The "space" characters are HT (9), LF (10), VT (11), FF (12), CR (13), and space (32). Notice that this list includes the VT character (code 11). This makes "space" different to \s, which does not include VT (for Perl compatibility).

The name "word" is a Perl extension, and "blank" is a GNU extension from Perl 5.8. Another Perl extension is negation, which is indicated by a ^ character after the colon. For example,

[12[:^digit:]]

matches "1", "2", or any non-digit. PCRE (and Perl) also recognize the POSIX syntax [.ch.] and [=ch=] where "ch" is a "collating element", but these are not supported, and an error is given if they are encountered.

In UTF-8 mode, characters with values greater than 255 do not match any of the POSIX character classes.

VERTICAL BAR

Vertical bar characters are used to separate alternative patterns. For example, the pattern

gilbert|sullivan

matches either "gilbert" or "sullivan". Any number of alternatives may appear, and an empty alternative is permitted (matching the empty string). The matching process tries each alternative in turn, from left to right, and the first one that succeeds is used. If the alternatives are within a subpattern (defined below), "succeeds" means matching the rest of the main pattern as well as the alternative in the subpattern.

INTERNAL OPTION SETTING

The settings of the PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, and PCRE_EXTENDED options can be changed from within the pattern by a sequence of Perl option letters enclosed between "(?" and ")". The option letters are

i for PCRE_CASELESS m for PCRE_MULTILINE s for PCRE_DOTALL x for PCRE_EXTENDED

For example, (?im) sets caseless, multiline matching. It is also possible to unset these options by preceding the letter with a hyphen, and a combined setting and unsetting such as (?im-sx), which sets PCRE_CASELESS and PCRE_MULTILINE while unsetting PCRE_DOTALL and PCRE_EXTENDED, is also permitted. If a letter appears both before and after the hyphen, the option is unset.

When an option change occurs at top level (that is, not inside subpattern parentheses), the change applies to the remainder of the pattern that follows. If the change is placed right at the start of a pattern, PCRE extracts it into the global options (and it will therefore show up in data extracted by the pcre_fullinfo() function).

An option change within a subpattern affects only that part of the current pattern that follows it, so

(a(?i)b)c

matches abc and aBc and no other strings (assuming PCRE_CASELESS is not used). By this means, options can be made to have different settings in different parts of the pattern. Any changes made in one alternative do carry on into subsequent branches within the same subpattern. For example,

(a(?i)b|c)

matches "ab", "aB", "c", and "C", even though when matching "C" the first branch is abandoned before the option setting. This is because the effects of option settings happen at compile time. There would be some very weird behaviour otherwise.

The PCRE-specific options PCRE_UNGREEDY and PCRE_EXTRA can be changed in the same way as the Perl-compatible options by using the characters U and X respectively. The (?X) flag setting is special in that it must always occur earlier in the pattern than any of the additional features it turns on, even when it is at top level. It is best put at the start.

SUBPATTERNS

Subpatterns are delimited by parentheses (round brackets), which can be nested. Marking part of a pattern as a subpattern does two things:

1. It localizes a set of alternatives. For example, the pattern

cat(aract|erpillar|)

matches one of the words "cat", "cataract", or "caterpillar". Without the parentheses, it would match "cataract", "erpillar" or the empty string.

2. It sets up the subpattern as a capturing subpattern (as defined above). When the whole pattern matches, that portion of the subject string that matched the subpattern is passed back to the caller via the ovector argument of pcre_exec(). Opening parentheses are counted from left to right (starting from 1) to obtain the numbers of the capturing subpatterns.

For example, if the string "the red king" is matched against the pattern

the ((red|white) (king|queen))

the captured substrings are "red king", "red", and "king", and are numbered 1, 2, and 3, respectively.

The fact that plain parentheses fulfil two functions is not always helpful. There are often times when a grouping subpattern is required without a capturing requirement. If an opening parenthesis is followed by a question mark and a colon, the subpattern does not do any capturing, and is not counted when computing the number of any subsequent capturing subpatterns. For example, if the string "the white queen" is matched against the pattern

the ((?:red|white) (king|queen))

the captured substrings are "white queen" and "queen", and are numbered 1 and 2. The maximum number of capturing subpatterns is 65535, and the maximum depth of nesting of all subpatterns, both capturing and non-capturing, is 200.

As a convenient shorthand, if any option settings are required at the start of a non-capturing subpattern, the option letters may appear between the "?" and the ":". Thus the two patterns

(?i:saturday|sunday) (?:(?i)saturday|sunday)

match exactly the same set of strings. Because alternative branches are tried from left to right, and options are not reset until the end of the subpattern is reached, an option setting in one branch does affect subsequent branches, so the above patterns match "SUNDAY" as well as "Saturday".

NAMED SUBPATTERNS

Identifying capturing parentheses by number is simple, but it can be very hard to keep track of the numbers in complicated regular expressions. Furthermore, if an expression is modified, the numbers may change. To help with the difficulty, PCRE supports the naming of subpatterns, something that Perl does not provide. The Python syntax (?P<name>...) is used. Names consist of alphanumeric characters and underscores, and must be unique within a pattern.

Named capturing parentheses are still allocated numbers as well as names. The PCRE API provides function calls for extracting the name-to-number translation table from a compiled pattern. For further details see the pcreapi documentation.

REPETITION

Repetition is specified by quantifiers, which can follow any of the following items:

a literal data character the . metacharacter the \C escape sequence escapes such as \d that match single characters a character class a back reference (see next section) a parenthesized subpattern (unless it is an assertion)

The general repetition quantifier specifies a minimum and maximum number of permitted matches, by giving the two numbers in curly brackets (braces), separated by a comma. The numbers must be less than 65536, and the first must be less than or equal to the second. For example:

z{2,4}

matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special character. If the second number is omitted, but the comma is present, there is no upper limit; if the second number and the comma are both omitted, the quantifier specifies an exact number of required matches. Thus

[aeiou]{3,}

matches at least 3 successive vowels, but may match many more, while

\d{8}

matches exactly 8 digits. An opening curly bracket that appears in a position where a quantifier is not allowed, or one that does not match the syntax of a quantifier, is taken as a literal character. For example, {,6} is not a quantifier, but a literal string of four characters.

In UTF-8 mode, quantifiers apply to UTF-8 characters rather than to individual bytes. Thus, for example, \x{100}{2} matches two UTF-8 characters, each of which is represented by a two-byte sequence.

The quantifier {0} is permitted, causing the expression to behave as if the previous item and the quantifier were not present.

For convenience (and historical compatibility) the three most common quantifiers have single-character abbreviations:

* is equivalent to {0,} + is equivalent to {1,} ? is equivalent to {0,1}

It is possible to construct infinite loops by following a subpattern that can match no characters with a quantifier that has no upper limit, for example:

(a?)*

Earlier versions of Perl and PCRE used to give an error at compile time for such patterns. However, because there are cases where this can be useful, such patterns are now accepted, but if any repetition of the subpattern does in fact match no characters, the loop is forcibly broken.

By default, the quantifiers are "greedy", that is, they match as much as possible (up to the maximum number of permitted times), without causing the rest of the pattern to fail. The classic example of where this gives problems is in trying to match comments in C programs. These appear between the sequences /* and */ and within the sequence, individual * and / characters may appear. An attempt to match C comments by applying the pattern

/\*.*\*/

to the string

/* first command */ not comment /* second comment */

fails, because it matches the entire string owing to the greediness of the .* item.

However, if a quantifier is followed by a question mark, it ceases to be greedy, and instead matches the minimum number of times possible, so the pattern

/\*.*?\*/

does the right thing with the C comments. The meaning of the various quantifiers is not otherwise changed, just the preferred number of matches. Do not confuse this use of question mark with its use as a quantifier in its own right. Because it has two uses, it can sometimes appear doubled, as in

\d??\d

which matches one digit by preference, but can match two if that is the only way the rest of the pattern matches.

If the PCRE_UNGREEDY option is set (an option which is not available in Perl), the quantifiers are not greedy by default, but individual ones can be made greedy by following them with a question mark. In other words, it inverts the default behaviour.

When a parenthesized subpattern is quantified with a minimum repeat count that is greater than 1 or with a limited maximum, more store is required for the compiled pattern, in proportion to the size of the minimum or maximum. If a pattern starts with .* or .{0,} and the PCRE_DOTALL option (equivalent to Perl's /s) is set, thus allowing the . to match newlines, the pattern is implicitly anchored, because whatever follows will be tried against every character position in the subject string, so there is no point in retrying the overall match at any position after the first. PCRE normally treats such a pattern as though it were preceded by \A.

In cases where it is known that the subject string contains no newlines, it is worth setting PCRE_DOTALL in order to obtain this optimization, or alternatively using ^ to indicate anchoring explicitly.

However, there is one situation where the optimization cannot be used. When .* is inside capturing parentheses that are the subject of a backreference elsewhere in the pattern, a match at the start may fail, and a later one succeed. Consider, for example:

(.*)abc\1

If the subject is "xyz123abc123" the match point is the fourth character. For this reason, such a pattern is not implicitly anchored.

When a capturing subpattern is repeated, the value captured is the substring that matched the final iteration. For example, after

(tweedle[dume]{3}\s*)+

has matched "tweedledum tweedledee" the value of the captured substring is "tweedledee". However, if there are nested capturing subpatterns, the corresponding captured values may have been set in previous iterations. For example, after

/(a|(b))+/

matches "aba" the value of the second captured substring is "b".

ATOMIC GROUPING AND POSSESSIVE QUANTIFIERS

With both maximizing and minimizing repetition, failure of what follows normally causes the repeated item to be reevaluated to see if a different number of repeats allows the rest of the pattern to match. Sometimes it is useful to prevent this, either to change the nature of the match, or to cause it fail earlier than it otherwise might, when the author of the pattern knows there is no point in carrying on.

Consider, for example, the pattern \d+foo when applied to the subject line

123456bar

After matching all 6 digits and then failing to match "foo", the normal action of the matcher is to try again with only 5 digits matching the \d+ item, and then with 4, and so on, before ultimately failing. "Atomic grouping" (a term taken from Jeffrey Friedl's book) provides the means for specifying that once a subpattern has matched, it is not to be reevaluated in this way.

If we use atomic grouping for the previous example, the matcher would give up immediately on failing to match "foo" the first time. The notation is a kind of special parenthesis, starting with (?> as in this example:

(?>\d+)bar

This kind of parenthesis "locks up" the part of the pattern it contains once it has matched, and a failure further into the pattern is prevented from backtracking into it. Backtracking past it to previous items, however, works as normal.

An alternative description is that a subpattern of this type matches the string of characters that an identical standalone pattern would match, if anchored at the current point in the subject string.

Atomic grouping subpatterns are not capturing subpatterns. Simple cases such as the above example can be thought of as a maximizing repeat that must swallow everything it can. So, while both \d+ and \d+? are prepared to adjust the number of digits they match in order to make the rest of the pattern match, (?>\d+) can only match an entire sequence of digits.

Atomic groups in general can of course contain arbitrarily complicated subpatterns, and can be nested. However, when the subpattern for an atomic group is just a single repeated item, as in the example above, a simpler notation, called a "possessive quantifier" can be used. This consists of an additional + character following a quantifier. Using this notation, the previous example can be rewritten as

\d++bar

Possessive quantifiers are always greedy; the setting of the PCRE_UNGREEDY option is ignored. They are a convenient notation for the simpler forms of atomic group. However, there is no difference in the meaning or processing of a possessive quantifier and the equivalent atomic group.

The possessive quantifier syntax is an extension to the Perl syntax. It originates in Sun's Java package.

When a pattern contains an unlimited repeat inside a subpattern that can itself be repeated an unlimited number of times, the use of an atomic group is the only way to avoid some failing matches taking a very long time indeed. The pattern

(\D+|<\d+>)*[!?]

matches an unlimited number of substrings that either consist of non-digits, or digits enclosed in <>, followed by either ! or ?. When it matches, it runs quickly. However, if it is applied to

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

it takes a long time before reporting failure. This is because the string can be divided between the two repeats in a large number of ways, and all have to be tried. (The example used [!?] rather than a single character at the end, because both PCRE and Perl have an optimization that allows for fast failure when a single character is used. They remember the last single character that is required for a match, and fail early if it is not present in the string.) If the pattern is changed to

((?>\D+)|<\d+>)*[!?]

sequences of non-digits cannot be broken, and failure happens quickly.

BACK REFERENCES

Outside a character class, a backslash followed by a digit greater than 0 (and possibly further digits) is a back reference to a capturing subpattern earlier (that is, to its left) in the pattern, provided there have been that many previous capturing left parentheses.

However, if the decimal number following the backslash is less than 10, it is always taken as a back reference, and causes an error only if there are not that many capturing left parentheses in the entire pattern. In other words, the parentheses that are referenced need not be to the left of the reference for numbers less than 10. See the section entitled "Backslash" above for further details of the handling of digits following a backslash.

A back reference matches whatever actually matched the capturing subpattern in the current subject string, rather than anything matching the subpattern itself (see "Subpatterns as subroutines" below for a way of doing that). So the pattern

(sens|respons)e and \1ibility

matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility". If caseful matching is in force at the time of the back reference, the case of letters is relevant. For example,

((?i)rah)\s+\1

matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original capturing subpattern is matched caselessly.

Back references to named subpatterns use the Python syntax (?P=name). We could rewrite the above example as follows:

(?<p1>(?i)rah)\s+(?P=p1)

There may be more than one back reference to the same subpattern. If a subpattern has not actually been used in a particular match, any back references to it always fail. For example, the pattern

(a|(bc))\2

always fails if it starts to match "a" rather than "bc". Because there may be many capturing parentheses in a pattern, all digits following the backslash are taken as part of a potential back reference number. If the pattern continues with a digit character, some delimiter must be used to terminate the back reference. If the PCRE_EXTENDED option is set, this can be whitespace. Otherwise an empty comment can be used.

A back reference that occurs inside the parentheses to which it refers fails when the subpattern is first used, so, for example, (a\1) never matches. However, such references can be useful inside repeated subpatterns. For example, the pattern

(a|b\1)+

matches any number of "a"s and also "aba", "ababbaa" etc. At each iteration of the subpattern, the back reference matches the character string corresponding to the previous iteration. In order for this to work, the pattern must be such that the first iteration does not need to match the back reference. This can be done using alternation, as in the example above, or by a quantifier with a minimum of zero.

ASSERTIONS

An assertion is a test on the characters following or preceding the current matching point that does not actually consume any characters. The simple assertions coded as \b, \B, \A, \G, \Z, \z, ^ and $ are described above. More complicated assertions are coded as subpatterns. There are two kinds: those that look ahead of the current position in the subject string, and those that look behind it.

An assertion subpattern is matched in the normal way, except that it does not cause the current matching position to be changed. Lookahead assertions start with (?= for positive assertions and (?! for negative assertions. For example,

\w+(?=;)

matches a word followed by a semicolon, but does not include the semicolon in the match, and

foo(?!bar)

matches any occurrence of "foo" that is not followed by "bar". Note that the apparently similar pattern

(?!foo)bar

does not find an occurrence of "bar" that is preceded by something other than "foo"; it finds any occurrence of "bar" whatsoever, because the assertion (?!foo) is always true when the next three characters are "bar". A lookbehind assertion is needed to achieve this effect.

If you want to force a matching failure at some point in a pattern, the most convenient way to do it is with (?!) because an empty string always matches, so an assertion that requires there not to be an empty string must always fail.

Lookbehind assertions start with (?<= for positive assertions and (?<! for negative assertions. For example,

(?<!foo)bar

does find an occurrence of "bar" that is not preceded by "foo". The contents of a lookbehind assertion are restricted such that all the strings it matches must have a fixed length. However, if there are several alternatives, they do not all have to have the same fixed length. Thus

(?<=bullock|donkey)

is permitted, but

(?<!dogs?|cats?)

causes an error at compile time. Branches that match different length strings are permitted only at the top level of a lookbehind assertion. This is an extension compared with Perl (at least for 5.8), which requires all branches to match the same length of string. An assertion such as

(?<=ab(c|de))

is not permitted, because its single top-level branch can match two different lengths, but it is acceptable if rewritten to use two top-level branches:

(?<=abc|abde)

The implementation of lookbehind assertions is, for each alternative, to temporarily move the current position back by the fixed width and then try to match. If there are insufficient characters before the current position, the match is deemed to fail.

PCRE does not allow the \C escape (which matches a single byte in UTF-8 mode) to appear in lookbehind assertions, because it makes it impossible to calculate the length of the lookbehind.

Atomic groups can be used in conjunction with lookbehind assertions to specify efficient matching at the end of the subject string. Consider a simple pattern such as

abcd$

when applied to a long string that does not match. Because matching proceeds from left to right, PCRE will look for each "a" in the subject and then see if what follows matches the rest of the pattern. If the pattern is specified as

^.*abcd$

the initial .* matches the entire string at first, but when this fails (because there is no following "a"), it backtracks to match all but the last character, then all but the last two characters, and so on. Once again the search for "a" covers the entire string, from right to left, so we are no better off. However, if the pattern is written as

^(?>.*)(?<=abcd)

or, equivalently,

^.*+(?<=abcd)

there can be no backtracking for the .* item; it can match only the entire string. The subsequent lookbehind assertion does a single test on the last four characters. If it fails, the match fails immediately. For long strings, this approach makes a significant difference to the processing time.

Several assertions (of any sort) may occur in succession. For example,

(?<=\d{3})(?<!999)foo

matches "foo" preceded by three digits that are not "999". Notice that each of the assertions is applied independently at the same point in the subject string. First there is a check that the previous three characters are all digits, and then there is a check that the same three characters are not "999". This pattern does not match "foo" preceded by six characters, the first of which are digits and the last three of which are not "999". For example, it doesn't match "123abcfoo". A pattern to do that is

(?<=\d{3}...)(?<!999)foo

This time the first assertion looks at the preceding six characters, checking that the first three are digits, and then the second assertion checks that the preceding three characters are not "999".

Assertions can be nested in any combination. For example,

(?<=(?<!foo)bar)baz

matches an occurrence of "baz" that is preceded by "bar" which in turn is not preceded by "foo", while

(?<=\d{3}(?!999)...)foo

is another pattern which matches "foo" preceded by three digits and any three characters that are not "999".

Assertion subpatterns are not capturing subpatterns, and may not be repeated, because it makes no sense to assert the same thing several times. If any kind of assertion contains capturing subpatterns within it, these are counted for the purposes of numbering the capturing subpatterns in the whole pattern. However, substring capturing is carried out only for positive assertions, because it does not make sense for negative assertions.

CONDITIONAL SUBPATTERNS

It is possible to cause the matching process to obey a subpattern conditionally or to choose between two alternative subpatterns, depending on the result of an assertion, or whether a previous capturing subpattern matched or not. The two possible forms of conditional subpattern are

(?(condition)yes-pattern) (?(condition)yes-pattern|no-pattern)

If the condition is satisfied, the yes-pattern is used; otherwise the no-pattern (if present) is used. If there are more than two alternatives in the subpattern, a compile-time error occurs.

There are three kinds of condition. If the text between the parentheses consists of a sequence of digits, the condition is satisfied if the capturing subpattern of that number has previously matched. The number must be greater than zero. Consider the following pattern, which contains nonsignificant white space to make it more readable (assume the PCRE_EXTENDED option) and to divide it into three parts for ease of discussion:

( \( )? [^()]+ (?(1) \) )

The first part matches an optional opening parenthesis, and if that character is present, sets it as the first captured substring. The second part matches one or more characters that are not parentheses. The third part is a conditional subpattern that tests whether the first set of parentheses matched or not. If they did, that is, if subject started with an opening parenthesis, the condition is true, and so the yes-pattern is executed and a closing parenthesis is required. Otherwise, since no-pattern is not present, the subpattern matches nothing. In other words, this pattern matches a sequence of non-parentheses, optionally enclosed in parentheses.

If the condition is the string (R), it is satisfied if a recursive call to the pattern or subpattern has been made. At "top level", the condition is false. This is a PCRE extension. Recursive patterns are described in the next section.

If the condition is not a sequence of digits or (R), it must be an assertion. This may be a positive or negative lookahead or lookbehind assertion. Consider this pattern, again containing non-significant white space, and with the two alternatives on the second line:

(?(?=[^a-z]*[a-z]) \d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )

The condition is a positive lookahead assertion that matches an optional sequence of non-letters followed by a letter. In other words, it tests for the presence of at least one letter in the subject. If a letter is found, the subject is matched against the first alternative; otherwise it is matched against the second. This pattern matches strings in one of the two forms dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits.

COMMENTS

The sequence (?# marks the start of a comment which continues up to the next closing parenthesis. Nested parentheses are not permitted. The characters that make up a comment play no part in the pattern matching at all.

If the PCRE_EXTENDED option is set, an unescaped # character outside a character class introduces a comment that continues up to the next newline character in the pattern.

RECURSIVE PATTERNS

Consider the problem of matching a string in parentheses, allowing for unlimited nested parentheses. Without the use of recursion, the best that can be done is to use a pattern that matches up to some fixed depth of nesting. It is not possible to handle an arbitrary nesting depth. Perl has provided an experimental facility that allows regular expressions to recurse (amongst other things). It does this by interpolating Perl code in the expression at run time, and the code can refer to the expression itself. A Perl pattern to solve the parentheses problem can be created like this:

$re = qr{\( (?: (?>[^()]+) | (?p{$re}) )* \)}x;

The (?p{...}) item interpolates Perl code at run time, and in this case refers recursively to the pattern in which it appears. Obviously, PCRE cannot support the interpolation of Perl code. Instead, it supports some special syntax for recursion of the entire pattern, and also for individual subpattern recursion.

The special item that consists of (? followed by a number greater than zero and a closing parenthesis is a recursive call of the subpattern of the given number, provided that it occurs inside that subpattern. (If not, it is a "subroutine" call, which is described in the next section.) The special item (?R) is a recursive call of the entire regular expression.

For example, this PCRE pattern solves the nested parentheses problem (assume the PCRE_EXTENDED option is set so that white space is ignored):

\( ( (?>[^()]+) | (?R) )* \)

First it matches an opening parenthesis. Then it matches any number of substrings which can either be a sequence of nonparentheses, or a recursive match of the pattern itself (that is a correctly parenthesized substring). Finally there is a closing parenthesis.

If this were part of a larger pattern, you would not want to recurse the entire pattern, so instead you could use this:

( \( ( (?>[^()]+) | (?1) )* \) )

We have put the pattern into parentheses, and caused the recursion to refer to them instead of the whole pattern. In a larger pattern, keeping track of parenthesis numbers can be tricky. It may be more convenient to use named parentheses instead. For this, PCRE uses (?P>name), which is an extension to the Python syntax that PCRE uses for named parentheses (Perl does not provide named parentheses). We could rewrite the above example as follows:

(?<pn> \( ( (?>[^()]+) | (?P>pn) )* \) )

This particular example pattern contains nested unlimited repeats, and so the use of atomic grouping for matching strings of non-parentheses is important when applying the pattern to strings that do not match. For example, when this pattern is applied to

(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()

it yields "no match" quickly. However, if atomic grouping is not used, the match runs for a very long time indeed because there are so many different ways the + and * repeats can carve up the subject, and all have to be tested before failure can be reported. At the end of a match, the values set for any capturing subpatterns are those from the outermost level of the recursion at which the subpattern value is set. If you want to obtain intermediate values, a callout function can be used (see below and the pcrecallout documentation). If the pattern above is matched against

(ab(cd)ef)

the value for the capturing parentheses is "ef", which is the last value taken on at the top level. If additional parentheses are added, giving

\( ( ( (?>[^()]+) | (?R) )* ) \) ^ ^ ^ ^

the string they capture is "ab(cd)ef", the contents of the top level parentheses. If there are more than 15 capturing parentheses in a pattern, PCRE has to obtain extra memory to store data during a recursion, which it does by using pcre_malloc, freeing it via pcre_free afterwards. If no memory can be obtained, the match fails with the PCRE_ERROR_NOMEMORY error.

Do not confuse the (?R) item with the condition (R), which tests for recursion. Consider this pattern, which matches text in angle brackets, allowing for arbitrary nesting. Only digits are allowed in nested brackets (that is, when recursing), whereas any characters are permitted at the outer level.

< (?: (?(R) \d++ | [^<>]*+) | (?R)) * >

In this pattern, (?(R) is the start of a conditional subpattern, with two different alternatives for the recursive and non-recursive cases. The (?R) item is the actual recursive call.

SUBPATTERNS AS SUBROUTINES

If the syntax for a recursive subpattern reference (either by number or by name) is used outside the parentheses to which it refers, it operates like a subroutine in a programming language. An earlier example pointed out that the pattern

(sens|respons)e and \1ibility

matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility". If instead the pattern

(sens|respons)e and (?1)ibility

is used, it does match "sense and responsibility" as well as the other two strings. Such references must, however, follow the subpattern to which they refer.

CALLOUTS

Perl has a feature whereby using the sequence (?{...}) causes arbitrary Perl code to be obeyed in the middle of matching a regular expression. This makes it possible, amongst other things, to extract different substrings that match the same pair of parentheses when there is a repetition.

PCRE provides a similar feature, but of course it cannot obey arbitrary Perl code. The feature is called "callout". The caller of PCRE provides an external function by putting its entry point in the global variable pcre_callout. By default, this variable contains NULL, which disables all calling out.

Within a regular expression, (?C) indicates the points at which the external function is to be called. If you want to identify different callout points, you can put a number less than 256 after the letter C. The default value is zero. For example, this pattern has two callout points:

(?C1)9abc(?C2)def

During matching, when PCRE reaches a callout point (and pcre_callout is set), the external function is called. It is provided with the number of the callout, and, optionally, one item of data originally supplied by the caller of pcre_exec(). The callout function may cause matching to backtrack, or to fail altogether. A complete description of the interface to the callout function is given in the pcrecallout documentation.


strncat

Function: pcre_compile

Synopsis
#include <pcre.h>
pcre *pcre_compile(const char *pattern, int options, const char **errptr, int *erroffset, const unsigned char *tableptr);

Description

The function pcre_compile() is called to compile a pattern into an internal form. The pattern is a C string terminated by a binary zero, and is passed in the argument pattern. A pointer to a single block of memory that is obtained via pcre_malloc is returned. This contains the compiled code and related data. The pcre type is defined for the returned block; this is a typedef for a structure whose contents are not externally defined. It is up to the caller to free the memory when it is no longer required.

Although the compiled code of a PCRE regex is relocatable, that is, it does not depend on memory location, the complete pcre data block is not fully relocatable, because it con- tains a copy of the tableptr argument, which is an address (see below). The options argument contains independent bits that affect the compilation. It should be zero if no options are required. Some of the options, in particular, those that are compatible with Perl, can also be set and unset from within the pattern (see the detailed description of regular expres- sions in the pcrepattern documentation). For these options, the contents of the options argument specifies their initial settings at the start of compilation and execution. The PCRE_ANCHORED option can be set at the time of matching as well as at compile time.

If errptr is NULL, pcre_compile() returns NULL immediately. Otherwise, if compilation of a pattern fails, pcre_compile() returns NULL, and sets the variable pointed to by errptr to point to a textual error message. The offset from the start of the pattern to the character where the error was discovered is placed in the variable pointed to by erroffset, which must not be NULL. If it is, an immediate error is given.

If the final argument, tableptr, is NULL, PCRE uses a default set of character tables which are built when it is compiled, using the default C locale. Otherwise, tableptr must be the result of a call to pcre_maketables(). See the section on locale support below.

This code fragment shows a typical straightforward call to pcre_compile():

pcre *re;
const char *error;
int erroffset;
re = pcre_compile( "^A.*Z", /* the pattern */
 0, /* default options */
&error, /* for error message */
&erroffset, /* for error offset within the source string */
NULL); /* use default character tables */

The following option bits are defined:

PCRE_ANCHORED

If this bit is set, the pattern is forced to be "anchored", that is, it is constrained to match only at the first match- ing point in the string which is being searched (the "sub- ject string"). This effect can also be achieved by appropri- ate constructs in the pattern itself, which is the only way to do it in Perl.

PCRE_CASELESS

If this bit is set, letters in the pattern match both upper and lower case letters. It is equivalent to Perl's /i option, and it can be changed within a pattern by a (?i) option setting.

PCRE_DOLLAR_ENDONLY

If this bit is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this option, a dollar also matches immediately before the final character if it is a newline (but not before any other new- lines). The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set. There is no equivalent to this option in Perl, and no way to set it within a pattern.

PCRE_DOTALL

If this bit is set, a dot metacharater in the pattern matches all characters, including newlines. Without it, new- lines are excluded. This option is equivalent to Perl's /s option, and it can be changed within a pattern by a (?s) option setting. A negative class such as [^a] always matches a newline character, independent of the setting of this option.

PCRE_EXTENDED

If this bit is set, whitespace data characters in the pat- tern are totally ignored except when escaped or inside a character class. Whitespace does not include the VT charac- ter (code 11). In addition, characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x option, and it can be changed within a pattern by a (?x) option setting.

This option makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional sub- pattern.

PCRE_EXTRA

This option was invented in order to turn on additional functionality of PCRE that is incompatible with Perl, but it is currently of very little use. When set, any backslash in a pattern that is followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. There are at present no other features controlled by this option. It can also be set by a (?X) option setting within a pattern.

PCRE_MULTILINE

By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless PCRE_DOLLAR_ENDONLY is set). This is the same as Perl.

When PCRE_MULTILINE it is set, the "start of line" and "end of line" constructs match immediately following or immedi- ately before any newline in the subject string, respec- tively, as well as at the very start and end. This is equivalent to Perl's /m option, and it can be changed within a pattern by a (?m) option setting. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting PCRE_MULTILINE has no effect.

PCRE_NO_AUTO_CAPTURE

If this option is set, it disables the use of numbered cap- turing parentheses in the pattern. Any opening parenthesis that is not followed by ? behaves as if it were followed by ?: but named parentheses can still be used for capturing (and they acquire numbers in the usual way). There is no equivalent of this option in Perl.

PCRE_UNGREEDY

This option inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by "?". It is not compatible with Perl. It can also be set by a (?U) option setting within the pattern.

PCRE_UTF8

This option causes PCRE to regard both the pattern and the subject as strings of UTF-8 characters instead of single- byte character strings. However, it is available only if PCRE has been built to include UTF-8 support. If not, the use of this option provokes an error. Details of how this option changes the behaviour of PCRE are given in the sec- tion on UTF-8 support in the main pcre page.

PCRE_NO_UTF8_CHECK

When PCRE_UTF8 is set, the validity of the pattern as a UTF-8 string is automatically checked. If an invalid UTF-8 sequence of bytes is found, pcre_compile() returns an error. If you already know that your pattern is valid, and you want to skip this check for performance reasons, you can set the PCRE_NO_UTF8_CHECK option. When it is set, the effect of passing an invalid UTF-8 string as a pattern is undefined. It may cause your program to crash. Note that there is a similar option for suppressing the checking of subject strings passed to pcre_exec().

Returns

A compiled regular expression object.


strncat

Function: pcre_copy_named_substring pcre_get_string_number pcre_get_named_substring

Synopsis
#include <pcre.h>
int pcre_copy_named_substring(const pcre *code, const char *subject, int *ovector, int stringcount, const char *stringname, char *buffer, int buffersize);
int pcre_get_stringnumber(const pcre *code, const char *name);
int pcre_get_named_substring(const pcre *code, const char *subject, int *ovector, int stringcount, const char *stringname, const char **stringptr);

Description

To extract a substring by name, you first have to find associated number. This can be done by calling pcre_get_stringnumber(). The first argument is the compiled pattern, and the second is the name. For example, for this pattern

ab(?<xxx>\d+)...

the number of the subpattern called "xxx" is 1. Given the number, you can then extract the substring directly, or use one of the functions described in the previous section. For convenience, there are also two functions that do the whole job.

Most of the arguments of pcre_copy_named_substring() and pcre_get_named_substring() are the same as those for the functions that extract by number, and so are not re- described here. There are just two differences.

First, instead of a substring number, a substring name is given. Second, there is an extra argument, given at the start, which is a pointer to the compiled pattern. This is needed in order to gain access to the name-to-number trans- lation table.

These functions call pcre_get_stringnumber(), and if it succeeds, they then call pcre_copy_substring() or pcre_get_substring(), as appropriate.

Returns

The result of the function is the length of the string, not including the terminating zero, or one of

PCRE_ERROR_NOMEMORY (-6)

The buffer was too small for pcre_copy_substring(), or the attempt to get memory failed for pcre_get_substring().

PCRE_ERROR_NOSUBSTRING (-7)

There is no substring whose number is stringnumber.

The pcre_get_substring_list() function extracts all avail- able substrings and builds a list of pointers to them. All this is done in a single block of memory which is obtained via pcre_malloc. The address of the memory block is returned via listptr, which is also the start of the list of string pointers. The end of the list is marked by a NULL pointer. The yield of the function is zero if all went well, or

PCRE_ERROR_NOMEMORY (-6)

if the attempt to get the memory block failed.

When any of these functions encounter a substring that is unset, which can happen when capturing subpattern number n+1 matches some part of the subject, but subpattern n has not been used at all, they return an empty string. This can be distinguished from a genuine zero-length substring by inspecting the appropriate offset in ovector, which is nega- tive for unset substrings.

The two convenience functions pcre_free_substring() and pcre_free_substring_list() can be used to free the memory returned by a previous call of pcre_get_substring() or pcre_get_substring_list(), respectively. They do nothing more than call the function pointed to by pcre_free, which of course could be called directly from a C program. How- ever, PCRE is used in some situations where it is linked via a special interface to another programming language which cannot use pcre_free directly; it is for these cases that the functions are provided.


strncat

Function: pcre_study

Synopsis
#include <pcre.h>
pcre_extra *pcre_study(const pcre *code, int options, const char **errptr);

Description

When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for matching. The function pcre_study() takes a pointer to a compiled pattern as its first argument. If studing the pattern produces additional information that will help speed up matching, pcre_study() returns a pointer to a pcre_extra block, in which the study_data field points to the results of the study.

The returned value from a pcre_study() can be passed directly to pcre_exec(). However, the pcre_extra block also contains other fields that can be set by the caller before the block is passed; these are described below. If studying the pattern does not produce any additional information, pcre_study() returns NULL. In that circumstance, if the cal- ling program wants to pass some of the other fields to pcre_exec(), it must set up its own pcre_extra block.

The second argument contains option bits. At present, no options are defined for pcre_study(), and this argument should always be zero.

The third argument for pcre_study() is a pointer for an error message. If studying succeeds (even if no data is returned), the variable it points to is set to NULL. Other- wise it points to a textual error message. You should there- fore test the error pointer for NULL after calling pcre_study(), to be sure that it has run successfully.

This is a typical call to pcre_study():

pcre_extra *pe;
pe = pcre_study( re, /* result of pcre_compile() */
0, /* no options exist */
&error); /* set to NULL or points to a message */

At present, studying a pattern is useful only for non- anchored patterns that do not have a single fixed starting character. A bitmap of possible starting characters is created.

Returns

A pointer to a pcre_extra block, in which the study_data field points to the results of the study.


strncat

Function: pcre_exec

Synopsis
#include <pcre.h>
int pcre_exec(const pcre *code,  // Result of a previous pcre_compile()
        const pcre_extra *extra, // Result of a previous pcre_styudy() or NULL
        const char *subject,     // The string to be searched
        int length,              // Length of the above string
        int startoffset,         // Index of the starting character
        int options,             // Options explained below
        int *ovector,            // This should hold the substring information
        int ovecsize);           // Length of the vector above.

Description

The function pcre_exec() is called to match a subject string against a pre-compiled pattern, which is passed in the code argument. If the pattern has been studied, the result of the study should be passed in the extra argument.

Here is an example of a simple call to pcre_exec():

int rc;
int ovector[30];
rc = pcre_exec( re, /* result of pcre_compile() */
    NULL, /* we didn't study the pattern */
    "some string", /* the subject string */
    11, /* the length of the subject string */
    0, /* start at offset 0 in the subject */
    0, /* default options */
    ovector, /* vector for substring information */
    30); /* number of elements in the vector */

If the extra argument is not NULL, it must point to a pcre_extra data block. The pcre_study() function returns such a block (when it doesn't return NULL), but you can also create one for yourself, and pass additional information in it. The fields in the block are as follows:

unsigned long int flags;
void *study_data;
unsigned long int match_limit;
void *callout_data;

The flags field is a bitmap that specifies which of the other fields are set. The flag bits are:

PCRE_EXTRA_STUDY_DATA PCRE_EXTRA_MATCH_LIMIT PCRE_EXTRA_CALLOUT_DATA

Other flag bits should be set to zero. The study_data field is set in the pcre_extra block that is returned by pcre_study(), together with the appropriate flag bit. You should not set this yourself, but you can add to the block by setting the other fields.

The match_limit field provides a means of preventing PCRE from using up a vast amount of resources when running patterns that are not going to match, but which have a very large number of possibilities in their search trees. The classic example is the use of nested unlimited repeats. Internally, PCRE uses a function called match() which it calls repeatedly (sometimes recursively). The limit is imposed on the number of times this function is called during a match, which has the effect of limiting the amount of recursion and backtracking that can take place. For patterns that are not anchored, the count starts from zero for each position in the subject string.

The default limit for the library can be set when PCRE is built; the default default is 10 million, which handles all but the most extreme cases. You can reduce the default by suppling pcre_exec() with a pcre_extra block in which match_limit is set to a smaller value, and PCRE_EXTRA_MATCH_LIMIT is set in the flags field. If the limit is exceeded, pcre_exec() returns PCRE_ERROR_MATCHLIMIT.

The pcre_callout field is used in conjunction with the "callout" feature, which is described in the pcrecallout documentation.

The PCRE_ANCHORED option can be passed in the options argument, whose unused bits must be zero. This limits pcre_exec() to matching at the first matching position. However, if a pattern was compiled with PCRE_ANCHORED, or turned out to be anchored by virtue of its contents, it cannot be made unachored at matching time.

When PCRE_UTF8 was set at compile time, the validity of the subject as a UTF-8 string is automatically checked. If an invalid UTF-8 sequence of bytes is found, pcre_exec() returns the error PCRE_ERROR_BADUTF8. If you already know that your subject is valid, and you want to skip this check for performance reasons, you can set the PCRE_NO_UTF8_CHECK option when calling pcre_exec(). When this option is set, the effect of passing an invalid UTF-8 string as a subject is undefined. It may cause your program to crash.

There are also three further options that can be set only at matching time:

PCRE_NOTBOL

The first character of the string is not the beginning of a line, so the circumflex metacharacter should not match before it. Setting this without PCRE_MULTILINE (at compile time) causes circumflex never to match.

PCRE_NOTEOL

The end of the string is not the end of a line, so the dollar metacharacter should not match it nor (except in multiline mode) a newline immediately before it. Setting this without PCRE_MULTILINE (at compile time) causes dollar never to match.

PCRE_NOTEMPTY

An empty string is not considered to be a valid match if this option is set. If there are alternatives in the pattern, they are tried. If all the alternatives match the empty string, the entire match fails. For example, if the pattern

a?b?

is applied to a string not beginning with "a" or "b", it matches the empty string at the start of the subject. With PCRE_NOTEMPTY set, this match is not valid, so PCRE searches further into the string for occurrences of "a" or "b".

Perl has no direct equivalent of PCRE_NOTEMPTY, but it does make a special case of a pattern match of the empty string within its split() function, and when using the /g modifier. It is possible to emulate Perl's behaviour after matching a null string by first trying the match again at the same offset with PCRE_NOTEMPTY set, and then if that fails by advancing the starting offset (see below) and trying an ordinary match again.

The subject string is passed to pcre_exec() as a pointer in subject, a length in length, and a starting offset in startoffset. Unlike the pattern string, the subject may contain binary zero bytes. When the starting offset is zero, the search for a match starts at the beginning of the subject, and this is by far the most common case.

If the pattern was compiled with the PCRE_UTF8 option, the subject must be a sequence of bytes that is a valid UTF-8 string. If an invalid UTF-8 string is passed, PCRE's behaviour is not defined.

A non-zero starting offset is useful when searching for another match in the same subject by calling pcre_exec() again after a previous success. Setting startoffset differs from just passing over a shortened string and setting PCRE_NOTBOL in the case of a pattern that begins with any kind of lookbehind. For example, consider the pattern

\Biss\B

which finds occurrences of "iss" in the middle of words. (\B matches only if the current position in the subject is not a word boundary.) When applied to the string "Mississipi" the first call to pcre_exec() finds the first occurrence. If pcre_exec() is called again with just the remainder of the subject, namely "issipi", it does not match, because \B is always false at the start of the subject, which is deemed to be a word boundary. However, if pcre_exec() is passed the entire string again, but with startoffset set to 4, it finds the second occurrence of "iss" because it is able to look behind the starting point to discover that it is preceded by a letter.

If a non-zero starting offset is passed when the pattern is anchored, one attempt to match at the given offset is tried. This can only succeed if the pattern does not require the match to be at the start of the subject.

In general, a pattern matches a certain portion of the subject, and in addition, further substrings from the subject may be picked out by parts of the pattern. Following the usage in Jeffrey Friedl's book, this is called "capturing" in what follows, and the phrase "capturing subpattern" is used for a fragment of a pattern that picks out a substring. PCRE supports several other kinds of parenthesized subpattern that do not cause substrings to be captured. Captured substrings are returned to the caller via a vector of integer offsets whose address is passed in ovector. The number of elements in the vector is passed in ovecsize. The first two-thirds of the vector is used to pass back captured substrings, each substring using a pair of integers. The remaining third of the vector is used as workspace by pcre_exec() while matching capturing subpatterns, and is not available for passing back information. The length passed in ovecsize should always be a multiple of three. If it is not, it is rounded down.

When a match has been successful, information about captured substrings is returned in pairs of integers, starting at the beginning of ovector, and continuing up to two-thirds of its length at the most. The first element of a pair is set to the offset of the first character in a substring, and the second is set to the offset of the first character after the end of a substring. The first pair, ovector[0] and ovector[1], identify the portion of the subject string matched by the entire pattern. The next pair is used for the first capturing subpattern, and so on. The value returned by pcre_exec() is the number of pairs that have been set. If there are no capturing subpatterns, the return value from a successful match is 1, indicating that just the first pair of offsets has been set.

Some convenience functions are provided for extracting the captured substrings as separate strings. These are described in the following section.

It is possible for an capturing subpattern number n+1 to match some part of the subject when subpattern n has not been used at all. For example, if the string "abc" is matched against the pattern (a|(z))(bc) subpatterns 1 and 3 are matched, but 2 is not. When this happens, both offset values corresponding to the unused subpattern are set to -1.

If a capturing subpattern is matched repeatedly, it is the last portion of the string that it matched that gets returned.

If the vector is too small to hold all the captured substrings, it is used as far as possible (up to two-thirds of its length), and the function returns a value of zero. In particular, if the substring offsets are not of interest, pcre_exec() may be called with ovector passed as NULL and ovecsize as zero. However, if the pattern contains back references and the ovector isn't big enough to remember the related substrings, PCRE has to get additional memory for use during matching. Thus it is usually advisable to supply an ovector.

Note that pcre_info() can be used to find out how many capturing subpatterns there are in a compiled pattern. The smallest size for ovector that will allow for n captured substrings, in addition to the offsets of the substring matched by the whole pattern, is (n+1)*3.

Returns

If pcre_exec() fails, it returns a negative number. The following are defined in the header file:

PCRE_ERROR_NOMATCH (-1)

The subject string did not match the pattern.

PCRE_ERROR_NULL (-2)

Either code or subject was passed as NULL, or ovector was NULL and ovecsize was not zero.

PCRE_ERROR_BADOPTION (-3)

An unrecognized bit was set in the options argument.

PCRE_ERROR_BADMAGIC (-4)

PCRE stores a 4-byte "magic number" at the start of the compiled code, to catch the case when it is passed a junk pointer. This is the error it gives when the magic number isn't present.

PCRE_ERROR_UNKNOWN_NODE (-5)

While running the pattern match, an unknown item was encountered in the compiled pattern. This error could be caused by a bug in PCRE or by overwriting of the compiled pattern.

PCRE_ERROR_NOMEMORY (-6)

If a pattern contains back references, but the ovector that is passed to pcre_exec() is not big enough to remember the referenced substrings, PCRE gets a block of memory at the start of matching to use for this purpose. If the call via pcre_malloc() fails, this error is given. The memory is freed at the end of matching.

PCRE_ERROR_NOSUBSTRING (-7)

This error is used by the pcre_copy_substring(), pcre_get_substring(), and pcre_get_substring_list() functions (see below). It is never returned by pcre_exec().

PCRE_ERROR_MATCHLIMIT (-8)

The recursion and backtracking limit, as specified by the match_limit field in a pcre_extra structure (or defaulted) was reached. See the description above.

PCRE_ERROR_CALLOUT (-9)

This error is never generated by pcre_exec() itself. It is provided for use by callout functions that want to yield a distinctive error code. See the pcrecallout documentation for details.

PCRE_ERROR_BADUTF8 (-10)

A string that contains an invalid UTF-8 byte sequence was passed as a subject.


Regular Expressions Funcs

LCC-Win32 Reg Expressions Functions

regcomp | regexec
regerror | regsub

REGEX 7

25 Oct 1995
Henry Spencer

Name
 regex POSIX 1003.2

DESCRIPTION
Regular expressions (``RE''s), as defined in POSIX 1003.2, come in two forms:

  • modern REs (roughly those of egrep 1003.2 calls these ``extended'' REs) and

  • obsolete REs (roughly those of ed 1003.2 ``basic'' REs).

Obsolete REs mostly exist for backward compatibility in some old programs; they will be discussed at the end.

1003.2 leaves some aspects of RE syntax and semantics open (¶ marks decisions on these aspects that may not be fully portable to other 1003.2 implementations).

A (modern) RE is one (¶ or more) non-empty branches,separated by `|'. It matches anything that matches one of the branches.

A branch is one (¶ or more) pieces, concatenated. It matches a match for the first, followed by a match for the second, etc.

A piece is an atom possibly followed by a single `*', `+', `?', or bound.
An atom followed by `*' matches a sequence of 0 or more matches of the atom.
An atom followed by `+' matches a sequence of 1 or more matches of the atom.
An atom followed by `?' matches a sequence of 0 or 1 matches of the atom.

A bound is `{' followed by an unsigned decimal integer, possibly followed by `,' possibly followed by another unsigned decimal integer, always followed by `}'.

The integers must lie between 0 and RE_DUP_MAX (255) inclusive, and if there are two of them, the first may not exceed the second. An atom followed by a bound containing one integer i and no comma matches
a sequence of exactly i matches of the atom.
An atom followed by a bound containing one integer i and a comma matches a sequence of i or more matches of the atom.

An atom followed by a bound containing two integers i and j matches a sequence of i through j (inclusive) matches of the atom.

An atom is

  • a regular expression enclosed in `()' (matching a match for the regular expression),
  • an empty set of `()' (matching the null string)
  • (¶ a bracket expression (see below),
  • . (matching any single character),
  • ^ (matching the null string at the beginning of a line),
  • $ (matching the null string at the end of a line),
  • a \e followed by one of the characters `^.[$()|*+?{\e' (matching that character taken as an ordinary character),
  • a \e followed by any other character (matching that character taken as an ordinary character, as if the `\e' had not been present), or
  • a single character with no other significance (matching that character).

A `{' followed by a character other than a digit is an ordinary character, not the beginning of a bound. It is illegal to end an RE with `\e'.

A bracket expression is a list of characters enclosed in `[ ]'. It normally matches any single character from the list (but see below).

  • If the list begins with `^', it matches any single character (but see below) not from the rest of the list.
  • If two characters in the list are separated by `-', this is shorthand for the full range of characters between those two (inclusive) in the collating sequence, e.g. `[0-9]' in ASCII matches any decimal digit.

It is illegal for two ranges to share an endpoint, e.g. `a-c-e'. Ranges are very collating-sequence-dependent,
and portable programs should avoid relying on them.

To include a literal `]' in the list, make it the first character (following a possible `^').
To include a literal `-', make it the first or last character,or the second endpoint of a range.
To use a literal `-' as the first endpoint of a range, enclose it in `[.' and `.]' to make it a collating element (see below).
With the exception of these and some combinations using `[' (see next paragraphs), all other special characters, including `\e', lose their special significance within a bracket expression.

Within a bracket expression, a collating element (a character, a multi-character sequence that collates as if it were a single character,or a collating-sequence name for either) enclosed in `[.' and `.]' stands for the
sequence of characters of that collating element.

The sequence is a single element of the bracket expression's list. A bracket expression containing a multi-character collating element can thus match more than one character, e.g. if the collating sequence includes a `ch' collating element, then the RE `[[.ch.]]*c' matches the first five characters of `chchcc'.

Within a bracket expression, a collating element enclosed in `[=' and `=]' is an equivalence class, standing for the sequences of characters of all collating elements equivalent to that one, including itself.
(If there are no other equivalent collating elements, the treatment is as if the enclosing delimiters were `[.' and `.]'.)
For example, if o and \o'o^' are the members of an equivalence class, then `[[=o=]]', `[[=\o'o^'=]]', and `[o\o'o^']' are all synonymous. An equivalence class may not be an endpoint of a range.

Within a bracket expression, the name of a character class enclosed in `[:' and `:]' stands for the list of all characters belonging to that class. Standard character class names are:

alnum digit punct alpha graph space blank lower upper cntrl print xdigit

These stand for the character classes defined in ctype. A locale may provide others.
A character class may not be used as an endpoint of a range.

There are two special cases of bracket expressions:

the bracket expressions `[[:<:]]' and `[[:>:]]' match the null string at the beginning and end of a word respectively.

A word is defined as a sequence of word characters which is neither preceded nor followed by word characters.
A word character is an alnum character (as defined by ctype) or an underscore.
This is an extension, compatible with but not specified by POSIX 1003.2, and should be used with
caution in software intended to be portable to other systems.

In the event that an RE could match more than one substring of a given string, the RE matches the one starting earliest in the string.

If the RE could match more than one substring starting at that point, it matches the longest.
Subexpressions also match the longest possible substrings, subject to the constraint that the whole match be as long as possible, with subexpressions starting earlier in the RE taking priority over ones starting later.
Note that higher-level subexpressions thus take priority over their lower-level component subexpressions.

Match lengths are measured in characters, not collating elements. A null string is considered longer than no match at all. For example,

`bb*' matches the three middle characters of `abbbc',

`(wee|week)(knights|nights)' matches all ten characters of `weeknights', when `(.*).*' is matched against `abc' the parenthesized subexpression matches all three characters, and when `(a*)*' is matched against `bc' both the whole RE and the parenthesized subexpression match the null string.

If case-independent matching is specified, the effect is much as if all case distinctions had vanished from the
alphabet.

When an alphabetic that exists in multiple cases appears as an ordinary character outside a bracket expression, it is effectively transformed into a bracket expression containing both cases, e.g. `x' becomes `[xX]'.

When it appears inside a bracket expression, all case counterparts of it are added to the bracket expression, so that (e.g.) `[x]' becomes `[xX]' and `[^x]' becomes `[^xX]'.

No particular limit is imposed on the length of REs (Programs intended to be portable should not employ REs longer than 256 bytes, as an implementation can refuse to accept such REs and remain POSIX-compliant.

Obsolete (``basic'') regular expressions differ in several respects. `|', `+', and `?' are ordinary characters and there is no equivalent for their functionality.

The delimiters for bounds are `\e{' and `\e}', with `{' and `}' by themselves ordinary characters.
The parentheses for nested subexpressions are `\e(' and `\e)', with `(' and `)' by themselves ordinary characters.
`^' is an ordinary character except at the beginning of the RE or\(dg the beginning of a parenthesized subexpression,
`$' is an ordinary character except at the end of the RE or the end of a parenthesized subexpression,
and `*' is an ordinary character if it appears at the beginning of the RE or the beginning of a parenthesized subexpression (after a possible leading `^').

Finally, there is one new type of atom, a back reference: `\e' followed by a non-zero decimal digit d matches the same sequence of characters matched by the dth parenthesized subexpression (numbering subexpressions by the positions of their opening parentheses, left to right), so that (e.g.) `\e([bc]\e)\e1' matches `bb' or `cc' but not `bc'.

See: POSIX 1003.2, section 2.8 (Regular Expression Notation).
HISTORY
Written by Henry Spencer, based on the 1003.2 spec.
BUGS
Having two kinds of REs is a botch.

The current 1003.2 spec says that `)' is an ordinary character in
the absence of an unmatched `('; this was an unintentional result of a wording error, and change is likely.
Avoid relying on it.

Back references are a dreadful botch, posing major problems for efficient implementations.
They are also somewhat vaguely defined (does `a\e(\e(b\e)*\e2\e)*d' match `abbbd'?).
Avoid using them.

1003.2's specification of case-independent matching is vague. The ``one case implies all cases'' definition given above is current consensus among implementors as to the right interpretation.

The syntax for word boundaries is incredibly ugly.


regcomp

Function: regcomp

Synopsis
#include <regexp.h>
regexp *regcomp(char *exp);

Description

regcomp compiles a regular expression into a structure of type regexp, and returns a pointer to it. The space has been allocated using malloc and may be released by free. Returns NULL in case of error.

typedef struct regexp {
    char *startp[NSUBEXP];
    char *endp[NSUBEXP];
    char regstart;   /* Internal use only. */
    char reganch;    /* Internal use only. */
    char *regmust;   /* Internal use only. */
    int regmlen;     /* Internal use only. */
    char program[1]; /* Unwarranted chumminess with compiler. */
} regexp;


regerror

Function: regerror

Synopsis
#include <regexp.h>
void regerror(char *s);

Description

regerror is called whenever an error is detected in regcomp, regexec,or regsub.

The default regerror does nothing. regerror can be replaced by the user if other actions are desirable.


regexec

Function: regexec

Synopsis
#include <regexp.h>
int regexec(regexp *prog, char * string);

Description

regexec matches a NULL-terminated string against the compiled regular expression in prog. It returns 1 for success and 0 for failure, and adjusts the contents ofprog's startp and endp (see below) accordingly.

The members of a regexp structure include at least the following (not necessarily in order):

char *startp[NSUBEXP];

char *endp[NSUBEXP];

where NSUBEXP is defined (as 10) in the header file.

Once a successful regexec has been done using the regexp, each startp - endp pair describes one substring within the string, with the startp pointing to the first character of the substring and the endp pointing to the first character following the substring.

The 0th substring is the substring of string that matched the whole regular expression.

The others are those substrings that matched parenthesized expressions within the regular expression, with parenthesized expressions numbered in left-to-right order of their opening parentheses.


regsub

Function: regsub

Synopsis
#include <regexp.h>
void regsub(regexp *prog,char *source,char *dest);

Description

regsub copies source to dest, making substitutions according to the most recent regexec performed using prog.

Each instance of `&' in source is replaced by the substring indicated by startp[ ] and endp[ ].

Each instance of n, where n is a digit, is replaced by the substring indicated bystartp [ ] andendp[ ] .

To get a literal `&' or \n into dest, prefix it with \; to get a literal \ preceding `&' or \n, prefix it with another \.


GNU Database Funcs

LCC-Win32 GNU Database Functions

gdbm_close gdbm_fetch

gdbm_delete

 gdbm_open


gdbm_close

Function: gdbm_close

Synopsis
#include <gdbm.h>
void gdbm_close(GDBM_FILE dbf);

Description

Closes the gdbm file and flushes all data to disk.


gdbm_delete

Function: gdbm_delete

Synopsis
#include <gdbm.h>
int gdbm_delete(GDBM_FILE dbf,datum key);

Description

Dbf is the pointer returned by gdbm_open. Key is the key data.

The return value is -1 if the item is not present or the requester is a reader. The return value is 0 if there was a successful delete.


gdbm_exists

Function: gdbm_exists

Synopsis
#include <gdbm.h>
int gdbm_exists(GDBM_FILE *dbf, datum key);

Description

If the key is found within the database, the return value will be true. If nothing appropriate is found, the return value will be false. This routine is useful for checking for the existence of a record, without performing the memory allocation done by gdbm_fetch


gdbm_fetch

Function: gdbm_fetch

Synopsis
#include <gdbm.h>
datum gdbm_fetch(GDBM_FILE dbf, datum key);

Description

Dbf is the pointer returned by gdbm_open. Key is the key data.

If the dptr element of the return value is NULL, no data was found. Otherwise the return value is a pointer to the found data. The storage space for the element is allocated using malloc. gdbm does not automatically free this data. It is the programmer's responsibility to free this storage when it is no longer needed.


gdbm_open

Function: gdbm_open

Synopsis
#include <gdbm.h>
GDBM_FILE gdbm_open __P((char *Name, int Block_size,
            int Read_write, int Mode, void (*Fatal_func)()));

Description

Name is the name of the file (the complete name, gdbm does not append any characters to this name). Block_size is the size of a single transfer from disk to memory. This parameter is ignored unless the file is a new file. The minimum size is 512. If it is less than 512, dbm will use the stat block size for the file system. Read_write can have one of the following values:

GDBM_READER

reader access

GDBM_WRITER

writer access

GDBM_WRCREAT

writer - if database does not exist create new one

GDBM_NEWDB

writer - create new database regardless if one exists

For the last three (writers of the database) the following may be added to Read_write by bitwise or:

GDBM_SYNC,

which causes all database operations to be synchronized to the disk, and

GDBM_NOLOCK,

which prevents the library from performing any locking on the database file.

Mode is the file mode (see chmod(2) and open(2)) if the file is created. (*Fatal_func) () is a function for dbm to call if it detects a fatal error. The only parameter of this function is a string. If the value of 0 is provided, gdbm will use a default function.

The return value dbf is the pointer needed by all other routines to access that gdbm file. If the return is the NULL pointer, gdbm_open was not successful. The errors can be found in gdbm_errno for gdbm errors and in errno for system errors. (For error codes, see gdbmerrno.h.)


gdbm_store

Function: gdbm_store

Synopsis
#include <gdbm.h>
int gdbm_store(GDBM_FILE dbf,datum key, datum data, int flag);

Description

Stores the given data under the given key. The dbf parameter is the return value of of a previous gdbm_open call. The key and the data arguments are structures of type datum, defined in gdbm.h.

typedef struct {
    char *dptr;
    int dsize;
} datum;

flag can have one of the following values:

GDBM_INSERT insert only, generate an error if key exists

GDBM_REPLACE replace contents if key exists.

If a reader calls gdbm_store, the return value will be -1. If called with GDBM_INSERT and key is in the database, the return value will be 1. Otherwise, the return value is 0.

NOTICE: If you store data for a key that is already in the data base, gdbm replaces the old data with the new data if called with GDBM_REPLACE. You do not get two data items for the same key and you do not get an error from gdbm_store.

NOTICE: The size in gdbm is not restricted like dbm or ndbm. Your data can be as large as you want.


Overview

The 'zlib' compression library provides in-memory compression and decompression functions, including integrity checks of the uncompressed data. This version of the library supports only one compression method (deflation) but other algorithms will be added later and will have the same stream interface.

Compression can be done in a single step if the buffers are large enough (for example if an input file is mmap'ed), or can be done by repeated calls of the compression function. In the latter case, the application must provide more input and/or consume the output (providing more output space) before each call.

The library also supports reading and writing files in gzip (.gz) format with an interface similar to that of stdio.

The library does not install any signal handler. The decoder checks the consistency of the compressed data, so the library should never crash even in case of corrupted input.

compress | compress2 | deflate | deflateInit | deflateEnd | gzclose
gzdopen | gzeof | gzerror | gzflush | gzgetc | gzgets
gzopen | gzprintf | gzputc | gzputs | gzread | gzrewind
inflate | inflateInit | inflateEnd | uncompress | gzwrite | gztell

Copyright

'zlib' general purpose compression library version 1.1.4, March 11th, 2002

Copyright (C) 1995-2002 Jean-loup Gailly and Mark Adler

This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented ; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly
jloup@gzip.org
Mark Adler
madler@alumni.caltech.edu
The data format used by the zlib library is described by RFCs (Request for Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).

This manual is converted from zlib.h by piaip

Visit http://ftp.cdrom.com/pub/infozip/zlib/ for the official zlib web page.


Network functions

This functions are described in "netutils.h" and implemented in "netutils.lib". You should include that header file and that library to use them


abs

Function: dispose_bitstring

Synopsis
#include <bitstring.h>
void dispose_bitstring(bitstring *bs);

Description

This function releases the memory used by the given bit string.

Returns

No result.


abs

Function: get_allocator_bitstring

Synopsis
#include <bitstring.h>
Malloc_Function_Type get_allocator_bitstring(bitstring *bs);

Description

This function returns the function pointer used to allocate memory stored in the given bit string.

Returns

The memory allocator function.


abs

Function: get_destructor_bitstring

Synopsis
#include <bitstring.h>
Malloc_Function_Type get_destructor_bitstring(bitstring *bs);

Description

This function returns the function pointer used to free memory stored in the given bit string.

Returns

The memory free function.


abs

Function: set_size_bitstring

Synopsis
#include <bitstring.h>
bool set_size_bitstring(bitstring *bs);

Description

This function sets the number of elements the bit-string can contain and allocates or releases memory as needed. the contents of the input bitstring are preserved.

Returns

The input bitstring or NULL, if there is a memory allocation error.


abs

Functions: sprint_bitstring fprint_bitstring

Synopsis
#include <bitstring.h>
int sprint_bitstring( bitstring *b, size_t bufsiz, char *buf);
int fprint_bitstring( bitstring *b, FILE *f);

Description

This functions print a bitstring in the specified stream. The bits are printed from the last element to the first, separated by spaces

Returns

The number of characters written.


abs

Functions: ToBitstring

Synopsis
#include <bitstring.h>
bitstring *ToBitstring(int);
bitstring *ToBitstring(long long);
bitstring *ToBitstring(double);
bitstring *ToBitstring(long double);

bitstring *ToBitstring(char *);

Description

This functions copy the bits from the given type into a newly allocated bitstring of size sizeof(type). The conversion function for char *, is different, it parses the given null terminated character string for either 1 or 0. Blanks and tab characters are ignored. Any character that is not in the set <space, tab, '1' ,'0'> will stop the conversion.

If no bits were recognized the result is NULL.

Returns

A pointer to the newly created bitstring.


abs

Function: dispose_list

Synopsis
#include <list.h>
void dispose_list(list *li);

Description

This function destroys all the list passed in argument.

Returns

No result.


abs

Function: find_list

Synopsis
#include <list.h>
void *find_list(list *l,int (*fn)(void *anElement,void *ElementToFind),void *ElementTofind);

Description

This function uses the given comparison function to search for a given element in the list. The arguments are:

  • The list to be searched
  • The comparison function that takes two arguments: the first is the element of the list to be compared and the second is the element being searched. This function should return zero when the two elements are equal, non-zero when the elements are different. If this function is NULL, the memcmp function will be used.
  • A pointer to the data that is to be searched in the list.

Returns

A pointer to the data contained in the found element, or NULL if no element was found that matched.


abs

Function: get_size_list

Synopsis
#include <list.h>
int get_size_list(list *li);

Description

This function returns the number of elements stored in the given list

Returns

The length of the list.


abs

Function: get_subrange_list

Synopsis
#include <list.h>
list *get_subrange_list(list *li, size_t start, size_t end);

Description

This function copies the elements of the list passed in argument from the element with index start till the element with index end (inclusive). Note that the contents of the list are NOT copied, just the data containers will be copied. To make a deep copy use one of the mapping functions

Returns

A pointer to a newly created list. This list shares with the original all the data.


abs

Function: iterate_list

Synopsis
#include <list.h>
void *iterate_list(list *l,int (*fn)(void *));

Description

This functions calls the given function in sequence, beginning with the first element of the list, till the last one. The function receives as its input a pointer to the content of each element. If the function returns 0, the process stops, and further calls are done. If the result of the function is different than zero, the function is called again.

Returns

A pointer to the data contained in the first element for which the function returns zero, or NULL if the list was empty or if the end of the list was reached and the function never returned zero.


Lists are containers that support the storage and retrieval of data that is not contiguous in memory.

Like the other containers, lists accept the [ ] notation.

The interface supports the following functions:

Allocating/disposing of lists

list *new_list(size_t elementSize);
void dispose_list(list *);

Copying lists

list *copy_list(list *);
list *get_subrange_list(list *l,size_t start,size_t end);

Accessing the list properties

size_t get_size_list(list *l);
list *set_size_list(list *l,size_t newsiz);

Accessing list elements

void *set_element_list(list *l,size_t position,void *pNewElement);
void *operator []=(list *l,size_t position,void *pNewElement);
void *get_element_list(list *l,size_t position);
void *operator [](list *l,size_t position);

Adding or deleting items

list *push_back_list(list *l,void *pdata);
list *push_front_list(list *l,void *pdata);
list *insert_list(list *l,size_t position,void *pElement);
list *remove_list(list *l,size_t position);
list *pop_front_list(list *l);
list *pop_back_list(list *l);

Applying a function to a whole list

void *iterate_list(list *l,int (*fn)(void *));
list *binary_map_list(list *l1,list *l2,binary_operator fn);

Utilities

list *concat_list(list *l1,list *l2);
list *nconcat_list(list *l1,list *l2);
list *reverse_list(list *l);
void *find_list(list *l,
            int (*fn)(void *anElement,void *ElementToFind),
            void *ElementTofind);
list *qsort_list(list *l,int *(compar)(const void *,const void *));


abs

Function: nconcat_list

Synopsis
#include <list.h>
list *nconcat_list(list *L1,list *L2);

Description

This function appends the second list to the first one. The first input lists is modified, i.e. the first element of L2 will be . appended to the last of L1.

Returns

A pointer to a new list structure containing the new list. If both lists are NULL, NULL is returned. If either list is empty, a pointer to the other list will be returned without modifying it in any way.


abs

Function: pop_front_list

Synopsis
#include <list.h>
list *pop_front_list(list *l);

Description

This functions removes one element at the beginning of the list. If the list is empty, nothing is done.

Returns

A pointer to the given list structure or NULL if the list was empty.


abs

Function: push_back_list

Synopsis
#include <list.h>
void *push_back_list(list *l,void *pdata);

Description

This functions adds one element containing the given data pointer at the end of the list.

Returns

A pointer to the given list structure.


abs

Function: push_front_list

Synopsis
#include <list.h>
void *push_front_list(list *l,void *pdata);

Description

This functions adds one element containing the given data pointer at the beginning of the list.

Returns

A pointer to the given list structure.


abs

Function: remove_list

Synopsis
#include <list.h>
list *remove_list(list *l, size_t position);

Description

This functions removes one element at the specified position of the list.

Returns

A pointer to the given list structure.


abs

Function: set_size_list

Synopsis
#include <list.h>
int set_size_list(list *li,size_t newsiz);

Description

This function modifies the number of elements in the given list, adding or deleting elemnt as needed so that the list length is exactly newsiz elements.

Returns

A pointer to the list, or NULL if a memory allocation error occurred.


abs

Functions: copy copy_string

Synopsis
#include <str.h>

String overloaded copy(String &s);
String copy_string(String &s);

Description

Builds a copy of the given string. The characters in the string are also copied

Returns

A copy of the given string or invalid_string if the source string is invalid.


abs

Functions: operator( )

Synopsis
#include <str.h>

String EXPORT operator()(const char* cstr);
String EXPORT operator()(const wchar_t *wstr);
char *EXPORT operator()(String &str);
wchar_t *EXPORT operator()(String &str);

Description

This functions implement casts to convert from one data type (the argument data type) and String.

String EXPORT operator()(const char* cstr);
String EXPORT operator()(const wchar_t *wstr);

This casts convert between a char * (that is assumed to be a zero terminated C string) and a String structure.

char *EXPORT operator()(String &str);
wchar_t *EXPORT operator()(String &str);

This casts convert between a String and a zero terminated C string or wchar_t string.

Returns

The transformed data type..


abs

Functions: operator ==

Synopsis
#include <str.h>
int operator == (const String& s1, const String& s2);
int operator == (const String & string1, int i);
int operator == (int i,const String & string1);

Description

This function returns 1 if s1 is equal to s2. The comparison is case sensitive. The comparisons with an integer have only the objective to make possible comparisons with functions that return an invalid string to signal failure. The only valid value for the integer is zero. This allows to write:

    if (!Strchr(S1,'A'))

Returns

A boolean value with the result of the comparison.


abs

Functions: operator > grString

Synopsis
#include <str.h>
int operator >(const String& s1, const String& s2);
int grString(const String *s1,const String *s2);

Description

This function returns 1 if s1 is greater than s2, i.e. s1 appears later in the lexicographical order. The comparison is case sensitive.

Returns

A boolean value with the result of the comparison.


abs

Functions: operator >= geqString

Synopsis
#include <str.h>
int operator >=(const String& s1, const String& s2);
int geqString(String *s1,const String *s2);

Description

This function returns 1 if s1 is greater or equal than s2, i.e. s1 appears first or is the same in the lexicographical order. The comparison is case sensitive.

Returns

A boolean value with the result of the comparison.


abs

Functions: operator <

Synopsis
#include <str.h>
int operator <(const String& s1, const String& s2);

Description

This function returns 1 if s1 is less than s2, i.e. s1 appears first in the lexicographical order. The comparison is case sensitive.

Returns

A boolean value with the result of the comparison.


abs

Functions: operator <=

Synopsis
#include <str.h>
int operator <=(const String& s1, const String& s2);

Description

This function returns 1 if s1 is less or equal than s2, i.e. s1 appears first or is the same in the lexicographical order. The comparison is case sensitive.

Returns

A boolean value with the result of the comparison.


abs

Functions: operator[ ]= set_element_string

Synopsis
#include <str.h>
int set_element_string(String &str, size_t position, int newval);
int operator[]=(String &str, size_t position,int newval);
int operator[]=(Stringp &str, size_t position,int newval);

Description

This function sets the character stored at the given position in the given string to the new value. The [ ] notation is used with String and Stringp.

Returns

The character stored at the given position.


abs

Functions: Strcontent

Synopsis
#include <str.h>
void *Strcontent(String &str);

Description

This function returns a pointer to the characters in the string. For wide string this will be a pointer to wchar_t, for multi byte strings this will be a char *.

Returns

A pointer to the contents of the string.


abs

Functions: Strcpy

Synopsis
#include <str.h>

void overloaded Strcpy (String & target, String & source);
void overloaded Strcpy (String & target, char *source);
void overloaded Strcpy (String & target, wchar_t *source);
Description

Copies the second string or char * into the first string.

Returns

No return value.


abs

Functions: Strcspn

Synopsis
#include <str.h>
size_t Strcspn(const String& s1, const String &s2);

Description

The Strcspn function computes the length of the maximum initial segment of the string s1 which consist entirely of characters not contained in the s2 string.

Returns

The length of the segment.


strncat

Function: Strfromenv

Synopsis
#include <str.h>
String overloaded Strfromenv(String &name);
String overloaded Strfromenv(char *name);

Description

The Strfromenv function returns a String with the contents of the given environment variable. If the variable isn't found, an invalid string is returned.

Returns

The value of the environment variable.


abs

Functions: clear_vector

Synopsis
#include <vector.h>
size_t clear_vector(vector *v);

Description

Sets all elements to zero and sets the size of the vector to zero.

Returns

The former size of the vector, in elements.


abs

Functions: concat_vector

Synopsis
#include <vector.h>
vector * concat_vector(vector *v1,vector *v2);

Description

Returns a new vector with the elements of v1 first, followed by the elements of v2.

Returns

A pointer to the new vector.


abs

Functions: copy_vector

Synopsis
#include <vector.h>
vector *copy_vector(vector *v);

Description

This function copies all the elements of the given vector into a newly allocated one.

Returns

A pointer to the newly created vector.


abs

Functions: get_capacity_vector

Synopsis
#include <vector.h>
size_t get_capacity_vector(vector *v);

Description

Returns the number of elements that can be stored in the given vector without provoking a resize operation.

Returns

The capacity.


abs

Functions: get_size_vector

Synopsis
#include <vector.h>
size_t get_size_vector(vector *v);

Description

Returns the number of elements in the given vector.

Returns

The number of elements.


abs

Functions: get_subrange_vector

Synopsis
#include <vector.h>
vector *get_subrange_vector(vector *v,size_t start,size_t end);

Description

This function copies all the elements in the indicated range from the given vector into a newly allocated one. The element size will be the same as the argument template.

Returns

A pointer to the newly created vector.


abs

Functions: insert_vector

Synopsis
#include <vector.h>
vector *insert_vector(vector *v,size_t position,void *element);

Description

Inserts the given element at the given position into the vector. The vector may be resized to allocate place for the new element, if the number of elements exceeds the vector's capacity.

Returns

A pointer to the given vector.


abs

Functions: iterate_vector

Synopsis
#include <vector.h>
void *iterate_vector(vector *v,int (*fn)(void *));

Description

Calls the given function for each element of the vector. The iteration stops when the called function returns zero. In this case the value returned is a pointer to the element where the function stopped. If the function never returns zero, the result value is NULL.

Returns

A pointer an element of the vector or NULL if the called function never returns zero.


abs

Functions: new_vector

Synopsis
#include <vector.h>
vector *new_vector(size_t size,size_t element_size,
                    void *contents=0,size_t capacity=0)

Description

This function allocates a new vector of "size" elements, each with "element_size" bytes.

The optional parameter "contents" allow you to initialize the new vector with an already pre-existing set of data. Each data element will be copied from the "contents" parameter.

The optional argument "capacity" is used when you want to pre-allocate sufficient space to avoid the costly resizing of a vector when elements are added to it. If the capacity parameter is smaller than the "size" parameter, the size parameter will be used.

Returns

A pointer to the newly created vector.


abs

Functions: nsort_vector

Synopsis
#include <vector.h>
vector *nsort_vector(vector *v,int (*compar)(const void *,const void *));

Description

Sorts the elements of the given vector in place.

Returns

A pointer to the given, now sorted, vector.


abs

Functions: pop_back_vector

Synopsis
#include <vector.h>
void *pop_back_vector(vector *v);

Description

Removes the last element of the vector. If the number of elements of the vector is zero, nothing is done.

Returns

A pointer to the removed item. The storage is still valid, and it will remain valid unless the vector is resized, or new elements are added.


abs

Functions: remove_vector

Synopsis
#include <vector.h>
void *remove_vector(vector *v,size_t position);

Description

Removes the given element at the given position into the vector. If the vector has no elements, nothing is done.

Returns

A pointer to the given vector.


abs

Functions: sort_vector

Synopsis
#include <vector.h>
vector *sort_vector(vector *v,int (*compar)(const void *,const void *));

Description

Returns a new vector with the elements of v sorted. The input vector is not modified.

Returns

A pointer to the new sorted vector.


Lists are containers that support the storage and retrieval of data that is not contiguous in memory

Vectors are a linear (one dimensional) sequence of data elements. Like the other containers, vectors accept the [ ] notation.

The interface supports the following functions:

Allocating

vector *new_vector(size_t size,size_t element_size,void *contents=0,size_t capacity=0)

Copying

vector *copy_vector(vector *v);
vector *get_subrange_vector(vector *v, size_t start,size_t end);

Accessing the properties

size_t get_size_vector(vector *v);
size_t get_capacity_vector(vector *v);

Accessing the elements

void *set_element_vector(vector *v,size_t position,void *data);
void *operator []=(vector *v,size_t position,void *data);
void *get_element_vector(vector *v,size_t position);
void *operator [](vector *v, size_t position);

Adding or deleting items

vector *insert_vector(vector *v,size_t position,void *pElement);
vector *remove_vector(vector *v,size_t position);

Applying a function

void *iterate_vector(bitstring *b,int (*fn)(void *data));

Utilities

vector *concat_vector(vector *v1,vector *v2);
vector *sort_vector(vector *v,int (*compar)(const void *,const void *));
vector *nsort_vector(vector *v,int (*compar)(const void *,const void *));
size_t clear_vector(vector *v);
void *pop_back_vector(vector *v);
int operator==(vector v1,vector v2);
int equal_vector(vector *v1,vector *v2);

Conversions


chmod

Function: chmod

Synopsis

#include <io.h>
int chmod(const char *path, int amode);

Description

Changes file access mode.

chmod sets the file-access permissions of the file given by path according to the mask given by amode. path points to a string.

amode can contain one or both of the symbolic constants S_IWRITE and S_IREAD (defined in sys\stat.h).

Value of amode Access permission

S_IWRITE Permission to write

S_IREAD Permission to read

S_IREAD | S_IWRITE Permission to read and write (write permission implies read permission)

Return Value

Upon successfully changing the file access mode, chmod returns 0. Otherwise, chmod returns a value of -1.

In the event of an error, the global variable errno is set to one of the following values:

EACCES Permission denied

ENOENT Path or file name not found


creat

Function: creat

Synopsis

#include <io.h>
int creat(const char *path, int amode);

Description

Creates a new file or overwrites an existing one.

Note: Remember that a backslash in a path requires '\\'.

creat creates a new file or prepares to rewrite an existing file given by path. amode applies only to newly created files.

A file created with creat is always created in the translation mode specified by the global variable _fmode (O_TEXT or O_BINARY).

If the file exists and the write attribute is set, creat truncates the file to a length of 0 bytes, leaving the file attributes unchanged. If the existing file has the read-only attribute set, the creat call fails and the file remains unchanged.

The creat call examines only the S_IWRITE bit of the access-mode word amode. If that bit is 1, the file can be written to. If the bit is 0, the file is marked as read-only. All other operating system attributes are set to 0.

amode can be one of the following (defined in sys\stat.h):

Value of amode Access permission

S_IWRITE Permission to write

S_IREAD Permission to read

S_IREAD / S_IWRITE Permission to read and write (write permission implies read permission)

Return Value

Upon successful completion, creat returns the new file handle, a nonnegative integer; otherwise, it returns -1.

In the event of error, the global variable errno is set to one of the following:

EACCES Permission denied

ENOENT Path or file name not found

EMFILE Too many open files


strncat

Function: _fcloseall

Synopsis
#include <stdio.h>
int _fcloseall(void);

Description

Closes all open streams except stdin, stdout, stderr. It also closes and deletes any temporary files created by tmpfile. All buffers associated with the streams are flushed prior to closing. System-allocated buffers are released when the stream is closed. Buffers assigned by the user with setbuf and setvbuf are not automatically released.

Returns

The total number of files closed or EOF if an error occurs.

Example:

/* This program opens files named "file1" and "file2".It  uses fclose to close "file1" and
 * _fcloseall to close all remaining files. */

#include <stdio.h>

int main( void )
{
   FILE *stream, *stream2;
   int numclosed;

   /* Open for read (will fail if file "file1" does not exist) */
   if( (stream  = fopen( "file1", "r" )) == NULL )
      printf( "The file 'file1' was not opened\n" );
   else
      printf( "The file 'file1' was opened\n" );

   /* Open for write */
   if( (stream2 = fopen( "file2", "w+" )) == NULL )
      printf( "The file 'file2' was not opened\n" );
   else
      printf( "The file 'file2' was opened\n" );

   /* Close stream */
   if( stream && fclose( stream ) )
      printf( "The file 'file1' was not closed\n" );

   /* All other files are closed: */
   numclosed = _fcloseall( );
   printf( "Number of files closed by _fcloseall: %u\n", numclosed );
  return 0;
}


strncat

Function: fdopen

Synopsis
#include <stdio.h>
int fdopen(int handle,const char *mode);

Description

Associates an I/O stream with the file identified by handle, thus allowing a file opened for low-level I/O to be buffered and formatted. _wfdopen is a wide-character version of fdopen; the mode argument to wfdopen is a wide-character string. wfdopen and fdopen behave identically otherwise.

The mode character string specifies the type of file and file access as follows:

"r" | Opens for reading. If the file does not exist or cannot be found, the fopen call fails.
"w" | Opens an empty file for writing. If the given file exists, its contents are destroyed.
"a" | Opens for writing at the end of the file (appending); creates the file first if it doesn’t exist.
"r+" | Opens for both reading and writing. (The file must exist.)
"w+" | Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed.
"a+" | Opens for reading and appending; creates the file first if it doesn’t exist.

When a file is opened with the "a" or "a+" access type, all write operations occur at the end of the file. The file pointer can be repositioned using fseek or rewind, but is always moved back to the end of the file before any write operation is carried out. Thus, existing data cannot be overwritten. When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for “update”). However, when you switch between reading and writing, there must be an intervening fflush, fsetpos, fseek, or rewind operation. The current position can be specified for the fsetpos or fseek operation, if desired.

In addition to the above values, the following characters can be included in mode to specify the translation mode for newline characters:

t | Open in text (translated) mode. In this mode, carriage return–linefeed (CR-LF) combinations are translated into single linefeeds (LF) on input, and LF characters are translated to CR-LF combinations on output. Also, CTRL+Z is interpreted as an end-of-file character on input. In files opened for reading/writing, fopen checks for a CTRL+Z at the end of the file and removes it, if possible. This is done because using the fseek and ftell functions to move within a file that ends with a CTRL+Z may cause fseek to behave improperly near the end of the file.
b | Open in binary (untranslated) mode; the above translations are suppressed.
c | Enable the commit flag for the associated filename so that the contents of the file buffer are written directly to disk if either fflush or flushall is called.
n | Reset the commit flag for the associated filename to “no-commit.” This is the default.

Returns

A pointer to the open stream or NULL to indicate an error.


strncat

Function: _filelength

Synopsis
#include <io.h>
int _filelength(int handle);

Description

Determines the size in bytes of the given file represented by the "handle" argument.

Returns

The total number of bytes in the file. Note that this will be correct with files smaller than 2GB only.


strncat

Function: fileno

Synopsis
#include <stdio.h>
int fileno(FILE *);

Description

Returns the file handle associated with a file stream.

Returns

The file handle.


getc

Function: _getw

Synopsis
#include <stdio.h>
int _getw(FILE *stream);

Description

The getw function reads the next binary value of type int from the file associated with stream and increments the associated file pointer to point to the next unread character.

_getw does not assume any special alignment of items in the stream. Problems with porting can occur with _getw because the size of the int type and the ordering of bytes within the int type differ across systems..

Returns

_getw returns the integer value read. A return value of EOF indicates either an error or end of file. However, because the EOF value is also a legitimate integer value, use feof or ferror to verify an end-of-file or error condition.


mktemp

Function: mktemp

Synopsis

#include <io.h>
char *mktemp(char *template);

Description

Makes a unique file name.

mktemp replaces the string pointed to by template with a unique file name and returns template.

template should be a null-terminated string with six trailing Xs. These Xs are replaced with a unique collection of letters plus a period, so that there are two letters, a period, and three suffix letters in the new file name.

Starting with AA.AAA, the new file name is assigned by looking up the name on the disk and avoiding pre-existing names of the same format.

Return Value

If template is well-formed, mktemp returns the address of the template string. Otherwise, it returns null.


_findfirst

Structure:Session

Synopsis
#include <netutils.h>

Description

typedef struct {
    char *Host;    // Host name
    int port;      // Connection port
    int Socket;    // Socket for communicating
    int BytesReceived; // Number of bytes received in last Receive()
    int BytesSent;    // Number of bytes sent with the last Send()
    int ErrorCode;    // Error code as returned with GetLastError()
    int Flags;        // Internal flags
}


atof

Function: atof

Synopsis
#include <math.h>
double atof(const char *nptr);

Description

The atof function converts the initial portion of the string pointed to by nptr to double representation.

Except for the behavior on error, it is equivalent to strtod(nptr, (char **)NULL)

Returns

The atof function returns the converted value.

Example
#include <stdlib.h>
int main(void)
{
    char *s;
    s = "-2309.12E-5";
    printf("%15.13g",atof(s));
return 0;
}
-0.0230912


asin

Function: carg

Synopsis
#include <complex.h>
long double carg(long double complex x);

Description

The carg function computes the argument (also called phase angle) of z.

Returns

The phase angle.


asin

Function: cexp

Synopsis
#include <complex.h>
long double _Complex cexp(long double _Complex x);

Description

The cexp function computes the base e complex exponent of x.

Returns

The base e exponent.


asin

Function: cimagl cimag cimagf

Synopsis
#include <complex.h>
long double cimagl(long double complex x);
double cimag(long double complex x);
float cimagf(long double complex x);

Description

The cimag function computes the imaginary part of its argument and coerces the result to the right type.

Returns

The imaginary part.


asin

Function: conj

Synopsis
#include <complex.h>
long double conj(long double complex x);

Description

The conj function computes the complex conjugate of its argument by reversing the sign of its imaginary part.

Returns

The conjugate of x.


asin

Function: cproj

Synopsis
#include <complex.h>
long double cproj(long double complex z);

Description

The cproj functions compute a projection of z onto the Riemann sphere: z projects to z except that all complex infinities (even those with one infinite part and one NaN part) project to positive infinity on the real axis. If z has an infinite part, then cproj(z) is equivalent to

INFINITY + I * copysign(0.0, cimag(z)).

Returns

The projection into the Rieman Sphere.


asin

Function: creall creal crealf

Synopsis
#include <complex.h>
long double creall(long double complex z);
double creal(long double complex z);
float crealf(long double complex z);

Description

The creal functions return the real part of the complex argument, coerced into the right return type.

Returns

The real part of z.


sin

Function: csinh

Synopsis
#include <complex.h>
double complex csinh(double complex x);
long double complex csinhl(long double complex x);
float complex csinhf(float complex x);
#include <qfloat.h>
qfloat complex csinhq(qfloat complex x);

Description

The csinh functions compute the complex hyperbolic sine of x.

Returns

The csinh functions return the complex hyperbolic sine value.

Note that the generic function csinh can be used instead of the above functions.

Example

#include <math.h>
#include <complex.h>
#include <qfloat.h>

// Help function to print a complex chain
void printComplex(char *which,qfloat _Complex &qcr,long double _Complex &ldr,double _Complex &dcr)
{
    printf("%s(1.5+2.3i)= %.25qf %.25qf qfloat\n",which,creal(qcr),cimag(qcr));
    printf("%s(1.5+2.3i)= %.25Lf %.25Lf long double\n",which,creal(ldr),cimag(ldr));
    printf("%s(1.5+2.3i)= %.15f %.15f double\n\n",which,creal(dcr),cimag(dcr));
}

int main(void)
{
qfloat complex qc = 1.5+2.3i;
long double _Complex ldc = 1.5+2.3i;
double _Complex dc = 1.5+2.3i;

    printComplex("csin(1.5+2.3i)",csinh(qc),csinh(ldc),csinh(dc));
    return 0;
}

Output:

csinh(1.5+2.3i)(1.5+2.3i)= -1.4186878435334470853133789 1.7542041112615224231869069 qfloat
csinh(1.5+2.3i)(1.5+2.3i)= -1.4186878435334470850000000 1.7542041112615224230000000 long double
csinh(1.5+2.3i)(1.5+2.3i)= -1.418687843533447 1.754204111261523 double


exp

Function: exp2

Synopsis
#include <math.h>
#include <qfloat.h>
qfloat exp2q(qfloat x);
double exp2l(double x);
float exp2f(float x);
long double exp2l(long double x);

Description

The exp2 family functions compute the base 2 exponential of x. A range error occurs if the magnitude of x is too large.

The generic function exp2 will accept any floating argument.

Returns

The exp2 function returns the exponential value base 2. The type of the return value depends on the arguments given.


exp10l

Function: exp10l

Synopsis
#include <math.h>
long double exp10l(long double x);

Description

The exp10l function computes 10^x.

Returns

The exp10l function returns the 10^x.


logb

Function: FLT_ROUNDS

Synopsis
#include <float.h>
extern int __fltrounds(void);
#define FLT_ROUNDS __fltrounds

Description

The FLT_ROUNDS symbol returns the current rounding mode. It will return:

0 Roundinging is set towards zero

1 Rounding is towards nearest

2 Rounding is set towards positive infinity

3 Rounding is set towards negative infinity

Returns

The rounding mode


nextafter

Function: fma fmal fmaf

Synopsis
#include <math.h>
double fma(double x, double y,double z);
long double fmal(long double x,long double y,long double z);
float fmaf(float x,float y,float z);

Description

The fma functions return the result of doing (x * y) + z in a single operation

Returns

The result is (x*y)+z


nextafter

Function: fmin fminl fminf fminq

Synopsis
#include <math.h>
double fmin(double x, double y);
float fminf(float x, float y);
long double fminl(float x,float y);

Description

The fmin functions determine the minimum value of their arguments

Returns

The result is the minimum value of x and y.


abs

Function: gamma_distribution gamma_distribution_c

Synopsis
#include <stats.h>
long double gamma_distribution(int
    a,int b,long double x);
long double gamma_distribution_c(int a,int b, long double x);
long double gamma_incomplete(long double a,long double x);

Description

The gamma distribution function gama_distribution returns the integral from zero to x of the gamma probability density function:

The incomplete gamma integral is used according to the relation:

y = gamma_incomplete(b,a*x)

The complemented gamma distribution function gamma_distribution_c returns the integral from x to infinity of the gamma probability density function

The incomplete gamma integral is used according to the relation:

y = gamma_incomplete(b,a*x)

The incomplete gamma integral gamma_incomplete is defined by:

Returns

The evaluated integrals.

Notes:

The implementation of this function is derived from the one in the Cephes mathematical library.


isnan

Function: imaxabs

Synopsis
#include <inttypes.h>
intmax_t imaxabs(intmax_t x);

Description

The imaxabs function returns the absolute value of its argument. Under lcc-win32 intmax_t is a long long integer (64 bits).

Returns

Returns returns the absolute value of its argument.


tanh

Function: isgreaterequal

Synopsis
#include <math.h>
int isgreaterequal(long double x,long double y);

Description

The isgreaterequal macro returns 1 if x >= y, zero otherwise. This macro doesn't raise the "invalid" floating point exception when one of its arguments is a NAN

Returns

This macro returns 1 if x >= Y


fabs

Function: llrint llrintf llrintl

Synopsis
#include <math.h>
long long llrint(double x);
long long llrintf(float x);
long long llrintl(long double x);

Description

The lrint functions round the given number to an integer according to the current rounding mode.

Returns

The llrint functions return the rounded value of x.


erf

Function: llround lloundf llroundl

Synopsis
#include <math.h>
long long llroundl(long double x);
long long llround(double x);
long long llroundf(float x);

Description

The llround functions will return a rounded long long integer that will be rounded to the nearest integer regardless of the current rounding mode.

The generic function llround will accept any floating argument.

Returns

The rounded value as a long long integer.


fabs

Function: lrint lrintf lrintl

Synopsis
#include <math.h>
long lrint(double x);
long lrintf(float x);
long lrintl(long double x);

Description

The lrint functions round the given number to an integer according to the current rounding mode.

Returns

The lrint functions return the rounded value of x.


The Mersenne Twister

From "A cryptographic compendium" by John Savard

First described in a paper by Makoto Matsumoto and Takuji Nishimura published in 1998, and available on the web site of one of the authors, this random number generator has a period of 2^19937-1, and its output is free of long-term correlations when considered from a viewpoint of 623 dimensions. In comparison, when even a two-dimensional plot is used of the successive members of pairs of numbers produced by a conventional linear congruential pseudorandom number generator, obvious patterns are visible.

The algorithm operates on a seed value which is 19,937 bits long; this value is stored in an array with 624 elements which contain 32-bit values. There are 31 unused bits in the array, which migrate through the array as the next seed is calculated, so no single array element can be replaced with a one-bit storage cell. It is based on the fact that 2^19937-1 is a prime number (and, as it is one less than a power of two, it is also a Mersenne prime). As noted in the main page on ciphers based on shift registers, if a shift register has a number of cells which correspond to the exponent for a Mersenne prime, the process of testing that shift register for maximum period is simplified. A more advanced simplification of this testing process, known as the inversive decimation method, is used to permit the construction of a maximum-period shift register of the particular form dealt with here. It was the development of this method by the developers of the Mersenne Twister that made the creation of such a large maximum-period shift register possible.

The Algorithm

The algorithm has two distinct phases; the recurrence which changes one 19,937-bit state to its successor, and the procedure for extracting multiple 32-bit values from that state.

The state succession algorithm is a kind of shift register:

 for i = 0 to 623
  temp = first bit of a(i) followed by last 31 bits of a(i+1) ;
  a(i) = temp shifted right one bit xor
         X'9908B0DF' if temp is odd xor
         a(i+397) ;
 next i

where all subscripts of a are modulo 624; thus, in practical implementations, the loop is broken into three pieces, one break occuring when i+397 falls off the end of the array, and one break before the last iteration, where i+1 falls off the end of the array.

Thus, a practical implementation looks like this, and several implementations in C are available on the Internet:

 for i = 0 to 226
  temp = first bit of a(i) followed by last 31 bits of a(i+1) ;
  a(i) = temp shifted right one bit xor
         X'9908B0DF' if temp is odd xor
         a(i+397) ;
 next i
 for i = 227 to 622
  temp = first bit of a(i) followed by last 31 bits of a(i+1) ;
  a(i) = temp shifted right one bit xor
         X'9908B0DF' if temp is odd xor
         a(i-227) ;
 next i
 temp = first bit of a(623) followed by last 31 bits of a(0) ;
 a(i) = temp shifted right one bit xor
        X'9908B0DF' if temp is odd xor
        a(396) ;

This particular Mersenne Twister belongs to a parameterized family of generators, whose parameters can be viewed as the following:

L = 19937
W = 32
M = 397
A = X'9908B0DF'

where W is the width in bits of the cells of the basic array, and L is the length in bits of the desired shift register, which has to be the exponent for a Mersenne prime; additional parameters can be derived from these:

N = floor( L/W ) + 1
R = L mod W

thus, after dividing L by W, R is the remainder, and N is one more than the integer quotient. These equations only apply when R is not zero, which is true in all but the trivial case for a prime N, and N must be prime to be a valid Mersenne exponent.

This makes the parametrizable code have the following appearance:

 for i = 0 to N-M-1
  temp = first R bits of x(i) followed by last W-R bits of x(i+1) ;
  x(i) = temp shifted right one bit xor
         A if temp is odd xor
         x(i+M) ;
 next i
 for i = N-M to N-2
  temp = first R bits of x(i) followed by last W-R bits of x(i+1) ;
  x(i) = temp shifted right one bit xor
         A if temp is odd xor
         x(i+M-N) ;
 next i
 temp = first R bits of x(N-1) followed by last W-R bits of x(0) ;
 x(N-1) = temp shifted right one bit xor
          A if temp is odd xor
          x(M-1) ;

and, indeed, the C implementations usually look like this, with bit masks with names like UM and LM (perhaps U and LL, or UPPER_MASK and LOWER_MASK) defined to obtain the upper R and the lower W-R bits of W-bit words, following the notation used in the original paper.

Note that the first step of the algorithm discards all but the first bit of a(0); thus, although the other bits of a(0) as calculated are used in the algorithm, the actual amount of information preserved from iteration to iteration is only 19937 bits (623*32 + 1). The second step discards all but the first bit of a(1), but the rest of a(1) was copied to a(0) by the first step. Thus, all 32 bits of all the elements of the array are needed, but the total information retained is 31 bits less than its total size.


erf

Function: remainder remainderl remainderf

Synopsis
#include <math.h>
long double remainderl(long double x);
double remainder(double x);
qfloat remainderq(qfloat x);
float remainderf(float x);

Description

The remainder functions compute the remainder x REM y required by IEC 60559.

When y 0, the remainder r = x REM y is defined regardless of the rounding mode by the mathematical relation r = x - ny, where n is the integer nearest the exact value of x/y; whenever | n - x/y | = 1/2, then n is even. Thus, the remainder is always exact. If r = 0, its sign shall be that x. This definition is applicable for all implementations.

Returns

The remainder functions return x REM y.


erf

Function: round roundf roundl

Synopsis
#include <math.h>
long double roundl(long double x);
double round(double x);
float roundf(float x);

Description

The round functions will return a rounded integer in the specified format that will be rounded to the nearest integer regardless of the current rounding mode.

Returns

The rounded value.


lgamma

Function: tgamma

Synopsis
#include <math.h>
double tgamma(double x);
long double tgammal(long double x);
float tgammaf(float x);
#include <qfloat.h>
qfloat tgammaq(qfloat &x);

Description

The tgamma functions compute the value of gamma of x. An error occurs if x is too large or if x is a negative number or zero.

Returns

The tgamma function returns the value of gamma of x.


erf

Function: trunc truncf truncl

Synopsis
#include <math.h>
long double truncl(long double x);
double trunc(double x);
float truncf(float x);

Description

The trunc functions round their argument to the nearest integer value, rounding halfway cases away from zero, regardless of the current rounding direction. If the rounded value is outside the range of the return type, the numeric result is unspecified.
A range error may occur if the magnitude of x is too large.

Returns

The rounded value in the same floating type as their input.


asin

Function: _m_exp

Synopsis
#include <matrix.h>
MAT *_m_exp(MAT *A,double eps,MAT *out,int *q_out,int *j_out);

Description

_m_exp -- compute matrix exponential of A and save it in out .
-- uses Pade approximation followed by repeated squaring
-- eps is the tolerance used for the Pade approximation
-- A is not changed
-- q_out - degree of the Pade approximation (q_out,q_out)
-- j_out - the power of 2 for scaling the matrix A such that ||A/2^j_out|| <= 0.5

Returns

The result matrix out.


asin

Function: band2mat

Synopsis
#include <matrix.h>
MAT *band2mat(BAND *bA,MAT *A);

Description

The band2mat function converts band matrix to dense matrix.

Returns

The converted matrix.


asin

Function: bd_free

Synopsis
#include <matrix.h>
int bd_free(BAND *A);

Description

The bd_free function releases the storage used by its input argument, destroying it.

Returns

Returns zero for successful return, -1 otherwise.

Errors

Input matrix pointer is NULL or has incorrect band parameters.


asin

Function: bd_get

Synopsis
#include <matrix.h>
BAND *bd_get(int lb,int ub,int n);

Description

The bd_get function generates a band matrix for a matrix with n columns,
lb subdiagonals and ub superdiagonals;

Returns

Returns a pointer to the new band matrix

Errors

Incorrect parameters (negative inputs) or not enough memory..


asin

Function: bd_resize

Synopsis
#include <matrix.h>
BAND *bd_resize(BAND *A,int new_lb,int new_ub,int new_n);

Description

The bd_resize function resizes a band matrix for a matrix with n columns, new_lb subdiagonals and new_ub superdiagonals.

Returns

Returns a pointer to the transposed band matrix.


asin

Function: bd_transp

Synopsis
#include <matrix.h>
BAND *bd_transp(BAND *in,BAND *out);

Description

The bd_transp function transposes a matrix in, into out, matrix after transposition. Can be done in situ.

Returns

Returns a pointer to the transposed band matrix.


asin

Function: bdLDLfactor

Synopsis
#include <matrix.h>
BAND *bdLDLfactor(BAND *A);

Description

Band LDL^T factorisation. L.D.L' factorisation of A in-situ; A is a band matrix. It works using only lower bandwidth and main diagonal so it is possible to set A->ub = 0

Returns

Returns a pointer to the factorized band matrix.


asin

Function: bdLDLsolve

Synopsis
#include <matrix.h>
VEC *bdLDLsolve(BAND *A,VEC *b,VEC *x);

Description

Solve A*x=b using band LDL^T factors, where A is factorized by Choleski LDL^T factorization.

Returns

The result vector.


asin

Function: bisvd

Synopsis
#include <matrix.h>
VEC *bisvd(VEC *d,VEC *f,MAT *U,MAT *V);

Description

svd of a bidiagonal m x n matrix represented by d (diagonal) and f (super-diagonals).

  • returns with d set to the singular values, f zeroed
  • if U, V non-NULL, the orthogonal operations are accumulated in U, V; if U, V == I on entry, then SVD == U^T.A.V
    where A is initial matrix
  • returns d on exit

Returns

The result vector d.


asin

Function: BKPfactor

Synopsis
#include <matrix.h>
MAT *BKPfactor(MAT *A,PERM *pivot,PERM *blocks);

Description

Bunch-Kaufman-Parlett factorization.of A in-situ.

  • A is factored into the form P'AP = MDM' where P is a permutation matrix, M lower triangular and D is block
    diagonal with blocks of size 1 or 2
  • P is stored in pivot; blocks[i]==i iff D[i][i] is a block

Returns

The result matrix.


asin

Function: BKPsolve

Synopsis
#include <matrix.h>
VEC *BKPsolve(MAT *A,PERM *pivot,PERM *block,VEC *b,VEC *x);

Description

Solves A.x = b where A has been factored a la BKPfactor()

Returns

Returns x, which is created if NULL


asin

Function: CHfactor

Synopsis
#include <matrix.h>
MAT *CHfactor(MAT *A);

Description

CHfactor -- Cholesky L.L' factorisation of A in-situ

Returns

The result matrix.

Errors:

  • Input matrix is NULL
  • Input matrix is not square.


asin

Function: CHsolve

Synopsis
#include <matrix.h>
VEC *CHsolve(MAT *A,VEC *b,VEC *x);

Description

Given a CHolesky factorisation in A, solve A.x=b

Returns

The result vector.

Errors:

  • Input matrix is NULL
  • Input vector is NULL
  • Input matrix is not square.


asin

Function: d_save

Synopsis
#include <matrix.h>
double d_save(FILE *fp,double x,char *name);

Description

Save real in MATLAB format.

Returns

The input number.


asin

Function: Dsolve

Synopsis
#include <matrix.h>
VEC *Dsolve(MAT *A,VEC *b,VEC *x);

Description

Solve D*x=y , D diagonal where D is diagonal of A. In situ.

Returns

The result vector.


asin

Function: err_is_list_attached

Synopsis
#include <matrix.h>
int err_is_list_attached(int list_num);

Description

Check if list_num is attached;

Returns

Returns TRUE if the list is attached, FALSE otherwise.


asin

Function: err_list_attach

Synopsis
#include <matrix.h>
int err_list_attach(int list_num,int list_len,char **err_ptr,int warn);

Description

Attach new list of errors pointed by err_ptr or change a previous one;

  • list_len is the number of elements in the list;
  • list_num is the list number;
  • warn == FALSE - errors (stop the program),
    warn == TRUE - warnings (continue the program);

Note: lists numbered 0 and 1 are attached automatically, you do not need to do it.

Returns

The list number is successful, -1 otherwise.


asin

Function: err_list_free

Synopsis
#include <matrix.h>
int err_list_free(int list_num);

Description

Release the error list numbered list_num

Returns

The list number is successful, -1 otherwise.

Errors:

list_num is negative or wasn't attached.


asin

Function: ev_err

Synopsis
#include <matrix.h>
int ev_err(char *file,err_num,int line_num,char *fn_name,int list_num);

Description

Reports error (err_num) in file "file" at line "line_num" and returns to user error handler;
list_num is an error list number (0 is the basic list pointed by err_mesg, 1 is the basic list of warnings)

Returns

Returns always zero.


asin

Function: fft

Synopsis
#include <matrix.h>
void fft(VEC *x_re,VEC *x_im);

Description

Computes Fast Fourier Transform.
-- radix-2 FFT only
-- vector extended to a power of 2

Returns

No explicit return value.


asin

Function: finput

Synopsis
#include <matrix.h>
int finput(FILE *fp,char *prompt,char *scanfFormat,void *variable);

Description

General purpose input routine; skips comments # ... \n. Its definition is:

#define finput(fp,prompt,fmt,var) \
( ( isatty(fileno(fp)) ? fprintf(stderr,prompt) : skipjunk(fp) ), \
fscanf(fp,fmt,var) )

Returns

The return value of fscanf.


asin

Function: fprompter

Synopsis
#include <matrix.h>
fprompter(FILE *fp,char *prompt);

Description

Print prompt to stderr. Macro. Its definition is:

#define fprompter(fp,prompt) \
( isatty(fileno(fp)) ? fprintf(stderr,prompt) : skipjunk(fp) )

Returns

The return value of fprintf or skipjunk..


asin

Function: get_col

Synopsis
#include <matrix.h>
VEC *get_col(MAT *mat,unsigned int col,VEC *vec);

Description

Extract a column from a matrix.

Returns

The extracted column as a vector.


asin

Function: get_row

Synopsis
#include <matrix.h>
VEC *get_row(MAT *mat,unsigned int row,VEC *vec);

Description

Extract a row from a matrix.

Returns

The extracted row as a vector.


asin

Function: givens

Synopsis
#include <matrix.h>
void givens(double x,double y,Real *c,Real *s);

Description

Compute Givens parameters. Returns c,s parameters for Givens rotation to eliminate y in the vector [ x y ]'

Returns

No explicit return value. The result is stored in c and s.


asin

Function: hhtrcols

Synopsis
#include <matrix.h>
MAT *hhtrcols(MAT *M,unsigned int i0,unsigned int j0,VEC *hh,double beta);

Description

Compute AP^T where P is a Householder matrix. Transform a matrix by a Householder vector by columns starting at
row i0 from column j0 -- in-situ.

Returns

The transformed matrix.


asin

Function: hhtrrows

Synopsis
#include <matrix.h>
MAT *hhtrrows(MAT *M,unsigned int i0,unsigned int j0,VEC *hh,double beta);

Description

Compute PA where P is a Householder matrix. Transform a matrix by a Householder vector by rows starting at
row i0 from column j0 -- in-situ.

Returns

The transformed matrix.


asin

Function: hhtrvec

Synopsis
#include <matrix.h>
VEC *hhtrvec(VEC *hh,double beta,unsigned int i0,VEC *in,VEC *out);

Description

Compute parameters for a Householder matrix..

Returns

The Householder vector.


asin

Function: hhvec

Synopsis
#include <matrix.h>
VEC *hhvec(VEC *vec,unsigned int i0,Real *beta,VEC *out,Real *newval)

Description

hhvec -- calulates Householder vector to eliminate all entries after the i0 entry of the vector vec. It is returned as out. May be in-situ.

Returns

The result vector.


The Housholder transformation.

The most frequently applied algorithm for QR decomposition uses the Householder transformation u = H v, where the Householder matrix H is a symmetric and orthogonal matrix of the form:

H = I - 2xx^T

with the identity matrix I and any normalized vector x with || x||22 = x^Tx = 1.

Householder transformations zero the m-1 elements of a column vector v below the first element:

with

One can verify that

with

fulfils xTx=1 and that with H=I-xxT one obtains the vector [ c 0 ... 0]T

To perform the decomposition of the m x n matrix A = QR (with m >= n) we construct in this way an m x m matrix H(1) to zero the m-1 elements of the first column. An m-1 x m-1 matrix G(2) will zero the m-2 elements of the second column. With G(2) we produce the m x m matrix

etc.

After n ( n-1 for m = n) such orthogonal transforms H(i) we obtain:

R = H(n) ... H(2) H(1) A

R is upper triangular and the orthogonal matrix Q becomes:

Q = H(1) H(2) ... H(n)

In practice the H(i) are never explicitly computed.

Example:

       1 2 3

A =    4 5 6

       7 8 9

alpha = (1 4 7)T

beta = (-7.124,4,7)

normalize to b0 = (-0.662, 0.372, 0.651)T

The Householder matrix is:

        0.123  0.492  0.862

P1  =   0.492  0.724 -0.484

        0.862 -0.484  0.153

Multiplying P1 * A we obtain:

        8.124  2.708  11.078

P1*A =  0      4.602  1.464

        0     -0.696  1.062

Treat the lower right 2 x 2 submatrix of P1 * A. From (4.602 -0.696) construct a 2 x 2 Householder matrix which is promoted to a 3 x 3 matrix by adding a trivial first line and column:

         1     0       0

 P2 =    0     0.989  -0.149

         0    -0.149  -0.989

Result:

         8.124 2.708  11.078

P2*P1*A= 0     4.655   1.289

         0     0      -1.269


asin

Function: ifft

Synopsis
#include <matrix.h>
void ifft(VEC *x_re,VEC *x_im);

Description

Compute the inverse Fourier Transform.

Returns

No explicit return value.


asin

Function: in_prod

Synopsis
#include <matrix.h>
double in_prod(VEC *a, VEC *b);

Description

Inner product of vectors.

Returns

The result number.


asin

Function: input

Synopsis
#include <matrix.h>
#define input(prompt,fmt,var) finput(stdin,prompt,fmt,var)

Description

Input a simple data item from stdin (macro, uses finput)

Returns

The result of finput..


asin

Typedef: ITER

Synopsis
#include <iter.h>

typedef struct Iter_data {
    int shared_x; /* if TRUE then x is shared and it will not be free'd */
    int shared_b; /* if TRUE then b is shared and it will not be free'd */
    unsigned k; /* no. of direction (search) vectors; =0 - none */
    int limit; /* upper bound on the no. of iter. steps */
    int steps; /* no. of iter. steps done */
    Real eps; /* accuracy required */
    VEC *x; /* input: initial guess; output: approximate solution */
    VEC *b; /* right hand side of the equation A*x = b */
    Fun_Ax Ax; /* function computing y = A*x */
    void *A_par; /* parameters for Ax */
    Fun_Ax ATx; /* function computing y = A^T*x; T = transpose */
    void *AT_par; /* parameters for ATx */
    Fun_Ax Bx; /* function computing y = B*x; B - preconditioner */
    void *B_par; /* parameters for Bx */
    /* function giving some information for a user;nres - a norm of a residual res */
    void (*info)(struct Iter_data *, double, VEC *,VEC *);
    /* stopping criterion:nres - a norm of res;
res - residual;if returned value == TRUE then stop;if returned value == FALSE then continue; */
   int (*stop_crit)(struct Iter_data *, double, VEC *,VEC *);
   Real init_res; /* the norm of the initial residual */
} ITER;


asin

Function: iter_arnoldi

Synopsis
#include <matrix.h>
MAT *iter_arnoldi(ITER *ip,Real *h_rem,MAT *Q,MAT *H);

Description

Arnoldi iterative method. Modified Gram-Schmidt algorithm.

Returns

Returns H.


asin

Function: iter_arnoldi_iref

Synopsis
#include <matrix.h>
MAT *iter_arnoldi_iref(ITER *ip,Real *h_rem,MAT *Q,MAT *H);

Description

Arnoldi iterative method with refinement.

Returns

Returns H.


asin

Function: iter_ATx

Synopsis
#include <matrix.h>
#define iter_Atx(ip,fun,fun_par)

Description

Set A in ITER structure.

typedef VEC *(*Fun_Ax)(void *,VEC *,VEC *);

#define iter_ATx(ip,fun,fun_par) \
             (ip->ATx=(Fun_Ax)(fun),ip->AT_par=(void *)(fun_par),0)

Returns

Always zero.


asin

Function: iter_Ax

Synopsis
#include <matrix.h>
#define iter_Ax(ip,fun,fun_par)

Description

Set ip->Ax=fun and ip->A_par=fun_par in the ITER structure.

typedef VEC *(*Fun_Ax)(void *,VEC *,VEC *);

#define iter_Ax(ip,fun,fun_par) \
   (ip->Ax=(Fun_Ax)(fun),ip->A_par=(void *)(fun_par),0)

 Returns

Always zero.


asin

Function: iter_Bx

Synopsis
#include <iter.h>
#define iter_Bx(ip,fun,fun_par)

Description

Set preconditioner in ITER structure

#define iter_Bx(ip,fun,fun_par) \
(ip->Bx=(Fun_Ax)(fun),ip->B_par=(void *)(fun_par),0)

 Returns

Always zero.


asin

Function: iter_cg

Synopsis
#include <matrix.h>
VEC *iter_cg(ITER *ip);

Description

Conjugate gradient iterative method.

Returns

The result vector stored in ip->x;


asin

Function: iter_cgne

Synopsis
#include <iter.h>
VEC *iter_cgne(ITER *ip);

Description

Conjugate gradients method for a normal equation a preconditioner B must be symmetric

Returns

The result vector stored in ip->x;


asin

Function: iter_cgs

Synopsis
#include <iter.h>
VEC *iter_cgs(ITER *ip,VEC *r0)

Description

iter_cgs -- uses CGS to compute a solution x to A.x=b.

Returns

The result vector stored in ip->x;


asin

Function: iter_copy

Synopsis
#include <iter.h>
ITER *iter_copy(ITER *ip1,ITER *ip2);

Description

Copy the structure ip1 to ip2 copying also the vectors x and b.

Returns

Always returns ip2.


asin

Function: iter_copy2

Synopsis
#include <iter.h>
ITER *iter_copy2(ITER *ip1,ITER *ip2);

Description

Copy the structure ip1 to ip2 preserving vectors x and b of ip2 (vectors x and b in ip2 are the same before and after iter_copy2) if ip2 == NULL then a new structure is created with x and b being NULL and other members are taken from ip1

Returns

Always returns ip2.


asin

Function: iter_dump

Synopsis
#include <iter.h>
int iter_dump(FILE *fp,ITER *ip);

Description

Print out ip structure - for diagnostic purposes mainly.

Returns

Returns the number of characters written.


asin

Function: iter_free

Synopsis
#include <iter.h>
int iter_free(ITER *ip);

Description

Frees the structure ITER. If allowed, the vectors in it will be released too.

Returns

Returns always zero.


asin

Function: iter_get

Synopsis
#include <iter.h>
VEC *iter_get(int lb,int lx)

Description

Constructs a new ITER structure. The two integer parameters define the length of the B and X member vectors. If they are zero a NULL is stored and nothing is allocated.

Returns

Returns a pointer to the new structure.


asin

Function: iter_gmres

Synopsis
#include <iter.h>
VEC *iter_gmres(ITER *ip)

Description

gmres -- generalised minimum residual algorithm of Saad & Schultz SIAM J. Sci. Stat. Comp. v.7, pp.856--869 (1986).

The Generalized Minimal Residual method [189] is an extension of MINRES (which is only applicable to symmetric systems) to unsymmetric systems. Like MINRES, it generates a sequence of orthogonal vectors, but in the absence of symmetry this can no longer be done with short recurrences; instead, all previously computed vectors in the orthogonal sequence have to be retained. For this reason, ``restarted '' versions of the method are used.

In the Conjugate Gradient method, the residuals form an orthogonal basis for the space [image] . In GMRES, this basis is formed explicitly:

The reader may recognize this as a modified Gram-Schmidt orthogonalization. Applied to the Krylov sequence [image] this orthogonalization is called the ``Arnoldi method'' [6]. The inner product coefficients [image] and [image] are stored in an upper Hessenberg matrix.

The GMRES iterates are constructed as

where the coefficients yk have been chosen to minimize the residual norm . The GMRES algorithm has the property that this residual norm can be computed without the iterate having been formed. Thus, the expensive action of forming the iterate can be postponed until the residual norm is deemed small enough.

Returns

Returns a pointer to the result vector.


asin

Function: iter_lsqr

Synopsis
#include <iter.h>
VEC *iter_lsqr(ITER *ip);

Description

"LSQR: an algorithm for sparse linear equations and sparse least squares", ACM Trans. Math. Soft., v. 8 pp. 43--71 (1982).

LSQR minimizes the norm of the residual Af(k) - g at each iteration.

Returns

Returns a pointer to the result vector.


asin

Function: iter_mgcr

Synopsis
#include <iter.h>
VEC *iter_lsqr(ITER *ip);

Description

iter_mgcr -- modified generalized conjugate residual algorithm; fast version of GCR;

Returns

Returns a pointer to the result vector.


asin

Function: iter_resize

Synopsis
#include <iter.h>
ITER *iter_resize(ITER *ip,int new_lenb,int new_lenx);

Description

Resizes tyhe vectors B and X in the given ITER structure.

Returns

Returns a pointer to the resized structure.


asin

Function: iter_spcg

Synopsis
#include <iter.h>
VEC *iter_spcg(SPMAT *A,SPMAT *LLT,VEC *b,double eps,VEC *x,int limit,int *steps);

Description

iter_spcg -- a simple interface to iter_cg() which uses sparse matrix data structures
-- assumes that LLT contains the Cholesky factorisation of the actual preconditioner;
use always as follows:
x = iter_spcg(A,LLT,b,eps,x,limit,steps);
or
x = iter_spcg(A,LLT,b,eps,VNULL,limit,steps);
In the second case the solution vector is created.

Returns

Returns a pointer to the result vector.


asin

Function: iter_spcgne

Synopsis
#include <iter.h>
VEC *iter_spcgne(SPMAT *A,SPMAT *B,VEC *b,double eps,VEC *x,int limit,int *steps)

Description

iter_spcgne -- a simple interface to iter_cgne() which uses sparse matrix data structures
-- assumes that B contains an actual preconditioner (or NULL)
use always as follows:
x = iter_spcgne(A,B,b,eps,x,limit,steps);
or
x = iter_spcgne(A,B,b,eps,VNULL,limit,steps);
In the second case the solution vector is created.

Returns

Returns a pointer to the result vector.


asin

Function: iter_spcgs

Synopsis
#include <iter.h>
VEC *iter_spcgs(SPMAT *A,SPMAT *B,VEC *b,VEC *r0,double tol,VEC *x,int limit,int *steps);

Description

iter_spcgs -- simple interface for SPMAT data structures
use always as follows:
x = iter_spcgs(A,B,b,r0,tol,x,limit,steps);
or
x = iter_spcgs(A,B,b,r0,tol,VNULL,limit,steps);
In the second case the solution vector is created.
If B is not NULL then it is a preconditioner.

Returns

Returns a pointer to the result vector.


asin

Function: iter_spgmres

Synopsis
#include <iter.h>
VEC *iter_spgmres(SPMAT *A,SPMAT *B,VEC *b,double tol,VEC *x,int k,int limit,int *steps);

Description

iter_spgmres - a simple interface to iter_gmres using sparse matrices.

Returns

Returns a pointer to the result vector.


asin

Function: iter_splsqr

Synopsis
#include <iter.h>
VEC *iter_splsqr(SPMAT *A,VEC *b,double tol,VEC *x,int limit,int *steps);

Description

iter_splsqr -- simple interface for SPMAT data structures.

Returns

Returns a pointer to the result vector.


asin

Function: iter_spmgcr

Synopsis
#include <iter.h>
VEC *iter_spmgcr(SPMAT *A,SPMAT *B,VEC *b,double tol,VEC *x,int k,int limit,int *steps);

Description

iter_spmgcr - a simple interface to iter_mgcr No preconditioner

Returns

Returns a pointer to the result vector.


asin

Function: iv_add

Synopsis
#include <iter.h>
IVEC *iv_add(IVEC *iv1,IVEC *iv2,IVEC *out);

Description

iv_add -- integer vector addition -- may be in-situ

Returns

Returns a pointer to the result vector.


asin

Function: iv_copy

Synopsis
#include <iter.h>
IVEC *iv_copy(IVEC *in,IVEC *out);

Description

iv_copy -- copy integer vector in to out. Output vector is created/resized if necessary

Returns

Returns a pointer to the result vector.


asin

Function: iv_dump

Synopsis
#include <iter.h>
void iv_dump(FILE *fp,IVEC *iv);

Description

iv_dump -- dumps all the contents of IVEC iv onto stream fp.

Returns

No return value


asin

Function: iv_finput

Synopsis
#include <iter.h>
IVEC *iv_finput(FILE *fp,IVEC *x);

Description

iv_finput -- input integer vector from stream fp

Returns

The vector read in.


asin

Function: iv_foutput

Synopsis
#include <iter.h>
void iv_foutput(FILE *fp,IVEC *iv);

Description

iv_foutput -- print a representation of iv on stream fp

Returns

No return value


asin

Function: IV_FREE

Synopsis
#include <iter.h>
#define IV_FREE(iv) ( iv_free(iv), (iv)=(IVEC *)NULL )

Description

This macro frees the given integer vector.

Returns

Always NULL.


asin

Function: iv_free_vars

Synopsis
#include <iter.h>
int iv_free_vars(IVEC **ipv,...);

Description

Frees a list of integer vector variables. The list is terminated with a NULL pointer.

Returns

Returns the number of variables freed.


asin

Function: iv_free

Synopsis
#include <iter.h>
int iv_free(IVEC *iv);

Description

iv_free -- returns iv & asoociated memory back to memory heap

Returns

Returns zero if successful, -1 otherwise.


asin

Function: iv_get

Synopsis
#include <iter.h>
IVEC *iv_get(int dim);

Description

Constructs a new integer vector with the given dimension.

Returns

A pointer to the vector.


asin

Function: iv_get_vars

Synopsis
#include <iter.h>
int iv_get_vars(int dim,...);

Description

Constructs several integer vector with the given dimension. The arguments should be pointers to integer vectors that will get allocated.

Returns

The number of vectors allocated


asin

Function: iv_input

Synopsis
#include <iter.h>
#define iv_input(iv) iv_finput(stdin,iv)

Description

Reads an integer vector from stdin

Returns

The vector


asin

Function: iv_output

Synopsis
#include <iter.h>
#define iv_output(iv) iv_foutput(stdout,iv)

Description

Writes an integer vector to stdout

Returns

No return value


asin

Function: iv_resize

Synopsis
#include <matrix.h>
IVEC *iv_resize(IVEC *iv,int new_dim);

Description

iv_resize -- returns the IVEC with dimension new_dim. -- iv is set to the zero vector

Returns

The resized vector.


asin

Function: iv_resize_vars

Synopsis
#include <matrix.h>
int iv_resize_vars(int new_dim,...);

Description

Resizes a list of integer vectors to a new dimension.

Returns

The number of vectors resized.

Example:

n = iv_resize_vars(10,&ix,&iy,&iz,NULL);
if ( n != 3) errmesg("IVEC copy/resize");


asin

Function: iv_sub

Synopsis
#include <matrix.h>
IVEC *iv_sub(IVEC *iv1,IVEC *iv2,IVEC *out);

Description

Subtracts each element from the iv2 vector from the corresponding element of the iv1 vector. May be in situ.

Returns

A pointer to the out vector.


asin

Function: LDLfactor

Synopsis
#include <matrix.h>
MAT *LDLfactor(MAT *A);

Description

Factorisation of A in-situ

Returns

The result matrix.


asin

Function: LDLsolve

Synopsis
#include <matrix.h>
VEC *LDLsolve(MAT *LDL,VEC *b,VEC *x);

Description

Solve routines assume that the corresponding factorisation routine has already been applied to the matrix along with auxiliary objects (such as pivot permutations)

These solve the system A.x = b, except for LUTsolve and QRTsolve which solve the transposed system A^T.x. = b.
If x is NULL on entry, then it is created.

Returns

The result vector.


asin

Function: LDLupdate

Synopsis
#include <matrix.h>
MAT *LDLupdate(MAT *CHmat,VEC *w,double alpha);

Description

LDLupdate -- updates a CHolesky factorisation, replacing LDL' by MD~M' = LDL' + alpha.w.w' Note: w is overwritten
Ref: Gill et al Math Comp 28, p516 Algorithm C1

Returns

The result matrix.


asin

Function: Lsolve

Synopsis
#include <matrix.h>
VEC *Lsolve(MAT *matrix,VEC *b,VEC *out,double diag);

Description

Lsolve -- forward elimination with (optional) default diagonal value

Returns

The result vector.


asin

Function: LTsolve

Synopsis
#include <matrix.h>
VEC *LTsolve(MAT *L,VEC *b,VEC *out,double diag);

Description

LTsolve -- back substitution with optional over-riding diagonal using the LOWER triangular part of matrix
-- can be in-situ but doesn't need to be.

Returns

The result vector.


asin

Function: LUcondtest

Synopsis
#include <matrix.h>
double LUcondest(MAT *LU,PERM *pivot);

Description

LUcondest -- returns an estimate of the condition number of LU given the LU factorisation in compact form.

Returns

The result vector.


asin

Function: LUfactor

Synopsis
#include <matrix.h>
MAT *LUfactor(MAT *A,PERM *pivot);

Description

LUfactor -- gaussian elimination with scaled partial pivoting Note: returns LU matrix which is A.

Returns

The result matrix.


asin

Function: LUsolve

Synopsis
#include <matrix.h>
VEC *LUsolve(MAT *A,PERM *pivot,VEC *b,VEC *x);

Description

LUsolve -- given an LU factorisation in A, solve Ax=b

Returns

The result vector


asin

Function: LUTsolve

Synopsis
#include <matrix.h>
VEC *LUTsolve(MAT *LU,PERM *pivot,VEC *b,VEC *x);

Description

LUTsolve -- given an LU factorisation in A, solve A^T.x=b

Returns

The result vector.


asin

Function: m_add

Synopsis
#include <matrix.h>
MAT *m_add(MAT *mat1,MAT *mat2,MAT *out);

Description

m_add -- matrix addition -- may be in-situ

Returns

The result matrix.


asin

Function: m_copy

Synopsis
#include <matrix.h>
#define m_copy(in,out) _m_copy(in,out,0,0);

Description

Copy of in to out

Returns

The result matrix out.


asin

Function: m_dump

Synopsis
#include <matrix.h>
void m_dump(FILE *fp,MAT *a);

Description

Write matrix "a" into stream fp.

Returns

No return value.


asin

Function: m_exp

Synopsis
#include <matrix.h>
MAT *m_exp(MAT *A,double eps,MAT *out);

Description

Matrix exponentiation. A simpler interface for _m_exp.

Returns

The result matrix


asin

Function: m_finput

Synopsis
#include <matrix.h>
MAT *m_finput(FILE *fp,MAT *a);

Description

Reads a matrix from the given input stream.

Returns

The result matrix.


asin

Function: m_foutput

Synopsis
#include <matrix.h>
void m_foutput(FILE *fp,MAT *a);

Description

Writes a matrix to a stream.

Returns

No explicit return value


asin

Function: M_FREE

Synopsis
#include <matrix.h>
#define M_FREE(mat) ( m_free(mat), (mat)=(MAT *)NULL )

Description

Frees the storage used by mat.

Returns

Always NULL.


asin

Function: m_free_vars

Synopsis
#include <matrix.h>
int m_free_vars(MAT **va,...);

Description

Frees a list of matrices.

Returns

The number of variables freed.

Example

k = m_free_vars(&A,&B,&C,NULL);
if ( k != 3 )
    errmesg("MAT free");


asin

Function: m_free

Synopsis
#include <matrix.h>
int m_free(MAT *mat);

Description

m_free -- returns mat and the associated memory back to memory heap..

Returns

Zero if successful, -1 otherwise


asin

Function: m_get

Synopsis
#include <matrix.h>
MAT *m_get(int m,int n);

Description

m_get -- gets an m x n matrix (in MAT form) by dynamic memory allocation

Returns

The new matrix.


asin

Function: m_get_vars

Synopsis
#include <matrix.h>
int m_get_vars(int m,int n,...);

Description

m_get -- gets a list of matrices.

Returns

The number of matrices allocated

Example:

n = m_get_vars(10,10,&A,&B,&C,NULL);
if (n != 3) {
    errmesg("m_get_vars");
    printf(" n = %d (should be 3)\n",n);
}


asin

Function: m_ident

Synopsis
#include <matrix.h>
MAT *m_ident(MAT *A);

Description

set A to being closest to identity matrix as possible -- i.e. A[i][j] == 1 if i == j and 0 otherwise

Returns

The transformed matrix.


asin

Function: m_input

Synopsis
#include <matrix.h>
#define m_input(mat) m_finput(stdin,mat)

Description

Read a matrix from stdin.

Returns

The matrix read.


asin

Function: m_inverse

Synopsis
#include <matrix.h>
MAT *m_inverse(MAT *A,MAT *out)

Description

m_inverse -- returns inverse of A, provided A is not too rank deficient. Uses LU factorisation

Returns

The inverted matrix.


asin

Function: m_load

Synopsis
#include <matrix.h>
MAT *m_load(FILE *fp,char **name);

Description

m_load -- loads in a ".mat" file variable as produced by MATLAB matrix returned; imaginary parts ignored.

Returns

The matrix reloaded....


asin

Function: m_mlt

Synopsis
#include <matrix.h>
MAT *m_mlt(MAT *A,MAT *B,MAT *OUT);

Description

m_mlt -- matrix-matrix multiplication

Returns

The result matrix..


asin

Function: m_norm1

Synopsis
#include <matrix.h>
double m_norm1(MAT *A);

Description

m_norm1 -- compute matrix 1-norm -- unscaled

Returns

The norm.


asin

Function: m_norm_frob

Synopsis
#include <matrix.h>
double m_norm_frob(MAT *A);

Description

m_norm_frob -- compute matrix frobenius-norm -- unscaled

Returns

The norm.


asin

Function: m_norm_inf

Synopsis
#include <matrix.h>
double m_norm_inf(MAT *A);

Description

m_norm_frob -- compute matrix infinity-norm -- unscaled

Returns

The norm.


asin

Function: m_ones

Synopsis
#include <matrix.h>
MAT *m_ones(MAT *A);

Description

Fills the matrix A with ones.

Returns

The transformed matrix.


asin

Function: m_output

Synopsis
#include <matrix.h>
#define m_output(mat) m_foutput(stdout,mat)

Description

Writes the matrix to stdout

Returns

No return value


asin

Function: m_poly

Synopsis
#include <matrix.h>
MAT *m_poly(MAT *A,VEC *a,MAT *out);

Description

m_poly -- computes sum_i a[i].A^i, where i=0,1,...dim(a);
Uses C. Van Loan's fast and memory efficient method

Returns

The result matrix.


asin

Function: m_pow

Synopsis
#include <matrix.h>
MAT *m_pow(MAT *A,int p,MAT * out);

Description

m_pow -- computes integer powers of a square matrix A, A^p.

Returns

The result matrix.


asin

Function: m_rand

Synopsis
#include <matrix.h>
double m_rand(MAT *A);

Description

Fills the given matrix with random numbers distributed uniformly between 0 and 1.

Returns

The filled matrix.


asin

Function: m_resize

Synopsis
#include <matrix.h>
MAT *m_resize(MAT *A,int new_m,int new_n);

Description

m_resize -- returns the matrix A of size new_m x new_n; A is zeroed.
If A == NULL on entry then the effect is equivalent to m_get()

Returns

The resized matrix.


asin

Function: m_resize_vars

Synopsis
#include <matrix.h>
int m_resize_vars(int m,int n,...);

Description

Resizes a list of matrices. The list must be finished by a NULL pointer.

Returns

The number of matrices resized.

Example:

n = m_resize_vars(5,5,&A,&B,&C,NULL);
if ( n != 3 )
    errmesg("MAT copy/resize");


asin

Function: m_save

Synopsis
#include <matrix.h>
MAT *m_save(FILE *fp,MAT *A,char *name);

Description

m_save -- save matrix in ".mat" file for MATLAB.

Returns

Returns matrix to be saved


asin

Function: m_sub

Synopsis
#include <matrix.h>
MAT *m_sub(MAT *mat1,MAT *mat2,MAT *out);

Description

m_sub -- matrix subtraction -- may be in-situ

Returns

Returns result matrix.


asin

Function: m_transp

Synopsis
#include <matrix.h>
MAT *m_transp(MAT *in,MAT *out);

Description

m_transp -- transpose matrix

Returns

Returns the transposed matrix.


asin

Function: m_zero

Synopsis
#include <matrix.h>
MAT *m_zero(MAT *A);

Description

Fills the given matrix with zeroes.

Returns

The result matrix.


asin

Function: makeQ

Synopsis
#include <matrix.h>
MAT *makeQ(MAT *QR,VEC *diag,MAT *Qout);

Description

makeQ -- constructs orthogonal matrix from Householder vectors stored in compact QR form

Returns

The result matrix.


asin

Function: makeR

Synopsis
#include <matrix.h>
MAT *makeR(MAT *QR,MAT *Rout);

Description

makeR constructs upper triangular matrix from QR (compact form) may be in-situ (all it does is zero the lower 1/2)

Returns

The result matrix.


asin

Function: mat2band

Synopsis
#include <matrix.h>
BAND *mat2band(MAT *A,int lb,int ub,BAND *bA);

Description

copy a square matrix to a band matrix with lb subdiagonals and ub superdiagonals

Returns

The result band matrix.


asin

Function: MCHfactor

Synopsis
#include <matrix.h>
MAT *MCHfactor(MAT *A,double tol);

Description

MCHfactor -- Modified Cholesky L.L' factorisation of A in-situ.

Returns

The result matrix.


asin

Function: mmtr_mlt

Synopsis
#include <matrix.h>
MAT *mmtr_mlt(MAT *A,MAT *B,MAT *OUT);

Description

mmtr_mlt -- matrix-matrix transposed multiplication. A.B^T is returned, and stored in OUT

Returns

The result matrix.


asin

Function: mrand

Synopsis
#include <matrix.h>
double mrand(void);

Description

mrand -- pseudo-random number generator

Returns

The random number


asin

Function: mrandlist

Synopsis
#include <matrix.h>
void mrandlist(Real a[],int len);

Description

Fills the given vector with random numbers distributed uniformly between 0 and 1.

Returns

No explicit return value.


asin

Function: mtrm_mlt

Synopsis
#include <matrix.h>
MAT *mtrm_mlt(MAT *A,MAT *B,MAT *OUT);

Description

mtrm_mlt -- matrix transposed-matrix multiplication A^T.B is returned, result stored in OUT

Returns

The result matrix.


asin

Function: mv_mlt

Synopsis
#include <matrix.h>
VEC *mv_mlt(MAT *A,VEC *b,VEC *out);

Description

mv_mlt -- matrix-vector multiplication
-- Note: b is treated as a column vector

Returns

The result vector.


asin

Function: mv_mltadd

Synopsis
#include <matrix.h>
VEC *mv_mltadd(MAT *A,VEC *b, double s,VEC *out);

Description

ms_mltadd -- matrix-scalar multiply and add
-- may be in situ
-- returns out == A1 + s*A2

Returns

The result vector.


asin

Function: prompter

Synopsis
#include <matrix.h>
#define prompter(prompt) fprompter(stdin,prompt)

Description

Writes the prompt (a character string) to stdout

Returns

No result value


asin

Function: px_cols

Synopsis
#include <matrix.h>
MAT *px_cols(PERM *px,MAT *A,MAT *out);

Description

px_cols -- permute columns of matrix A; out = A.px'
-- May NOT be in situ, i.e. px != out.

Returns

The result matrix.


asin

Function: px_copy

Synopsis
#include <matrix.h>
PERM *px_copy(PERM *in,PERM *out);

Description

px_copy -- copies permutation 'in' to 'out'

Returns

The result permutation.


asin

Function: px_dump

Synopsis
#include <matrix.h>
void px_dump(FILE *fp,PERM *px);

Description

Writes the given permutation px to the given stream.

Returns

No result value


asin

Function: px_finput

Synopsis
#include <matrix.h>
PERM *px_finput(FILE *fp,PERM *px);

Description

Reads a permutation from a stream.

Returns

The read permutation.


asin

Function: px_foutput

Synopsis
#include <matrix.h>
void px_foutput(FILE *fp,PERM *px);

Description

Writes a permutation to a stream.

Returns

No return value.


asin

Function: PX_FREE

Synopsis
#include <matrix.h>
#define PX_FREE(px) ( px_free(px), (px)=(PERM *)NULL )

Description

Releases the memory used by a permutation

Returns

Always NULL.


asin

Function: px_free_vars

Synopsis
#include <matrix.h>
int px_free_vars(PERM **vpx,...);

Description

Releases the memory used by a permutation list. The list must be finished by a NULL pointer.

Returns

The number of variables freed.

Example:

n = px_free_vars(&pi1,&pi2,&pi3,NULL);
if ( n != 3 )
    errmesg("PERM px_free_vars");


asin

Function: px_free

Synopsis
#include <matrix.h>
int px_free(PERM *px);

Description

Releases the memory used by a permutation

Returns

Zero if successful, -1 otherwise.


asin

Function: px_get

Synopsis
#include <matrix.h>
PERM *px_get(int size);

Description

px_get -- gets a PERM of given 'size' by dynamic memory allocation
-- Note: initialized to the identity permutation

Returns

A pointer to the new permutation.


asin

Function: px_get_vars

Synopsis
#include <matrix.h>
int px_get_vars(int dim,...);

Description

Initializes a NULL terminated list of permutation variables.

Returns

The number of variables initialized.

Example:

n = px_get_vars(15,&pi1,&pi2,&pi3,NULL);
if (n != 3) {
    errmesg("px_get_vars");
    printf(" n = %d (should be 3)\n",n);
}


asin

Function: px_ident

Synopsis
#include <matrix.h>
PERM *px_ident(PERM *px);

Description

Sets px to the identity permutation.

Returns

The transformed permutation.


asin

Function: px_input

Synopsis
#include <matrix.h>
#define px_input(px) px_finput(stdin,px)

Description

Inputs a permutation from standard input.

Returns

The new permutation.


asin

Function: px_inv

Synopsis
#include <matrix.h>
PERM *px_inv(PERM *px,PERM *out);

Description

Inverts a permutation.
-- taken from ACM Collected Algorithms #25

Returns

The inverted permutation.


asin

Function: px_mlt

Synopsis
#include <matrix.h>
PERM *px_mlt(PERM *px1,PERM *px2,PERM *out);

Description

px_mlt -- permutation multiplication (composition)

Returns

The result permutation (out)..


asin

Function: px_output

Synopsis
#include <matrix.h>
#define px_output(px) px_foutput(stdout,px)

Description

Writes a permutation to standard output

Returns

No return value


asin

Function: px_resize

Synopsis
#include <matrix.h>
PERM *px_resize(pPERM *x,int new_size);

Description

px_resize -- returns the permutation px with size new_size
-- px is set to the identity permutation.

Returns

Returns the resized permutation.


asin

Function: px_resize_vars

Synopsis
#include <matrix.h>
int px_resize_vars(int new_dim,...);

Description

Resizes a NULL terminated list of permutation variables.

Returns

The number of resized variables.

Example:

n = px_resize_vars(20,&pi1,&pi2,&pi3,NULL);

if (n != 3) error(...)


asin

Function: px_rows

Synopsis
#include <matrix.h>
MAT *px_rows(PERM *px,MAT *A,MAT *out);

Description

px_rows -- permute columns of matrix A; out = px.A
-- May NOT be in situ (A != out)

Returns

The permuted matrix


asin

Function: px_sign

Synopsis
#include <matrix.h>
int px_sign(PERM *px);

Description

px_sign -- compute the ``sign'' of a permutation = +/-1 where
px is the product of an even/odd # transpositions

Returns

Either -1 or 1.


asin

Function: px_transp

Synopsis
#include <matrix.h>
PERM *px_transp(PERM *px,unsigned i1,unsigned i2);

Description

px_transp -- transpose elements of permutation
-- Really multiplying a permutation by a transposition

px permutation to transpose
i1,i2; elements to transpose

Returns

The result permutation.


asin

Function: px_vec

Synopsis
#include <matrix.h>
VEC *px_vec(PERM *px,VEC *vector,VEC *out);

Description

px_vec -- permute vector

Returns

The result vector.


asin

Function: px_zvec

Synopsis
#include <matrix.h>
ZVEC *px_zvec(PERM *px,ZVEC *vector,ZVEC *out);

Description

px_vec -- permute complex vector

Returns

The resulting complex vector.


asin

Function: pxinv_vec

Synopsis
#include <matrix.h>
VEC *pxinv_vec(PERM *px,VEC *x,VEC *out);

Description

pxinv_vec -- apply the inverse of px to x, returning the result in out

Returns

The inverted permutation.


asin

Function: pxinv_zvec

Synopsis
#include <matrix.h>
ZVEC *pxinv_zvec(PERM *px,ZVEC *x,ZVEC *out);

Description

pxinv_zvec -- apply the inverse of px to x, returning the result in out
-- may NOT be in situ (px != out)

Returns

The inverted complex permutation.


asin

Function: QRCPfactor

Synopsis
#include <matrix.h>
MAT *QRCPfactor(MAT *A,VEC *diag,PERM *px);

Description

RCPfactor -- forms the QR factorisation of A with column pivoting -- factorisation stored in compact form ( not quite standard format ).

The internal "factored form" of a matrix A is not quite standard. The diagonal of A is replaced by the diagonal of R -- not by the 1st non-zero entries of the Householder vectors. The 1st non-zero entries are held in the diag parameter of QRfactor(). The reason for this non-standard representation is that it enables direct use of the Usolve() function rather than requiring that a separate function be written just for this case. See, e.g., QRsolve for more details.

Returns

The resulting matrix.


asin

Function: QRCPsolve

Synopsis
#include <matrix.h>
VEC *QRCPsolve(MAT *QR,VEC *diag,PERM *pivot,VEC *b,VEC *x);

Description

QRCPsolve -- solves A.x = b where A is factored by QRCPfactor()
-- assumes that A is in the compact factored form

Returns

The resulting vector.


asin

Function: QRfactor

Synopsis
#include <matrix.h>
MAT *QRfactor(MAT *A,VEC *diag);

Description

QRfactor -- forms the QR factorisation of A -- factorisation stored in compact form as described below ( not quite standard format )

The internal "factored form" of a matrix A is not quite standard. The diagonal of A is replaced by the diagonal of R -- not by the 1st non-zero entries of the Householder vectors. The 1st non-zero entries are held in the diag parameter of QRfactor(). The reason for this non-standard representation is that it enables direct use of the Usolve() function rather than requiring that a seperate function be written just for this case.

Returns

The result matrix


asin

Function: QRsolve

Synopsis
#include <matrix.h>
VEC *QRsolve(MAT *QR,VEC *diag,VEC *b,VEC *x);

Description

QRsolve -- solves the system Q.R.x=b where Q & R are stored in compact form
-- returns x, which is created if necessary

Returns

The resulting vector.


asin

Function: QRTsolve

Synopsis
#include <matrix.h>
VEC *QRTsolve(MAT *A,VEC *diag,VEC *c,VEC *sc);

Description

QRTsolve -- solve A^T.sc = c where the QR factors of A are stored in
compact form
-- returns sc
-- original due to Mike Osborne

Returns

The resulting vector.


asin

Function: QRupdate

Synopsis
#include <matrix.h>
MAT *QRupdate(MAT *Q,MAT *R,VEC *u,VEC *v);

Description

QRupdate -- updates QR factorization in expanded form (separate matrices)
Finds Q+, R+ s.t. Q+.R+ = Q.(R+u.v') and Q+ orthogonal, R+ upper triangle
Ref: Golub & van Loan Matrix Computations pp437-443
-- does not update Q if it is NULL

Returns

The resulting matrix


asin

Function: rot_cols

Synopsis
#include <matrix.h>
MAT *rot_cols(MAT *mat,unsigned i,unsigned k,double c,double s,MAT *out);

Description

rot_cols -- postmultiply mat by givens rotation described by c, and s.

Returns

The resulting matrix


asin

Function: rot_rows

Synopsis
#include <matrix.h>
MAT *rot_cols(MAT *mat,unsigned i,unsigned k,double c,double s,MAT *out);

Description

rot_cols -- postmultiply mat by givens rotation described by c and s

Returns

The resulting matrix


asin

Function: rot_vec

Synopsis
#include <matrix.h>
VEC *rot_vec(VEC *x,unsigned i,unsigned k,double c,double s,VEC *out);

Description

rot_vec -- apply Givens rotation to x's i & k components

Returns

The resulting vector


asin

Function: rot_zvec

Synopsis
#include <matrix.h>
ZVEC *rot_zvec(ZVEC *x,int i,int k,double c,complex s,ZVEC *out);

Description

rot_zvec -- apply Givens rotation to x's i & k components

Returns

The resulting complex vector


asin

Function: schur

Synopsis
#include <matrix.h>
MAT *schur(MAT *A,MAT *Q);

Description

schur -- computes the Schur decomposition of the matrix A in situ
-- optionally, gives Q matrix such that Q^T.A.Q is upper triangular
-- returns upper triangular Schur matrix

Returns

The resulting matrix


asin

Function: schur_evals

Synopsis
#include <matrix.h>
void schur_evals(MAT *T,VEC *real_pt,VEC *imag_pt);

Description

schur_evals -- compute real & imaginary parts of eigenvalues
-- assumes T contains a block upper triangular matrix
as produced by schur()
-- real parts stored in real_pt, imaginary parts in imag_pt

Returns

No return value.


asin

Function: schur_vecs

Synopsis
#include <matrix.h>
MAT *schur_vecs(MAT *T,MAT *Q,MAT *X_re,MAT *X_im);

Description

schur_vecs -- returns eigenvectors computed from the real Schur decomposition of a matrix
-- T is the block upper triangular Schur matrix
-- Q is the orthognal matrix where A = Q.T.Q^T
-- if Q is null, the eigenvectors of T are returned
-- X_re is the real part of the matrix of eigenvectors,
and X_im is the imaginary part of the matrix.
-- X_re is returned

Returns

The real value matrix X_re.


asin

Function: set_col

Synopsis
#include <matrix.h>
#define set_col(mat,col,vec) _set_col(mat,col,vec,0);

Description

Sets column "col" to the vector "vec" in the matrix "mat".

Returns

No return value


asin

Function: set_err_flag

Synopsis
#include <matrix.h>
int set_err_flag(int flag);

Description

Controls the behavior of ev_err. Possible values are:

EF_SILENT Ignore

EF_ABORT Aborts program

EF_JUMP Jumps to a restart jump buffer

Returns

The old value of the error flag.


asin

Function: set_row

Synopsis
#include <matrix.h>
#define set_row(mat,row,vec) _set_row(mat,row,vec,0)

Description

Sets the row "row" to the vector "vec" in the matrix "mat".

Returns

No return value


asin

Function: sm_mlt

Synopsis
#include <matrix.h>
MAT *sm_mlt(double scalar,MAT *matrix,MAT *out);

Description

sm_mlt -- scalar-matrix multiply -- may be in-situ

Returns

The result matrix


asin

Function: sp_col_access

Synopsis
#include <matrix.h>
SPMAT *sp_col_access(SPMAT *A);

Description

sp_col_access -- set column access path; i.e. nxt_row, nxt_idx fields

Returns

The same input sparse matrix.


asin

Function: sp_compact

Synopsis
#include <matrix.h>
SPMAT *sp_compact(SPMAT *A,double tol);

Description

sp_compact -- removes zeros and near-zeros from a sparse matrix

Returns

The same input sparse matrix.


asin

Function: sp_copy

Synopsis
#include <matrix.h>
SPMAT *sp_copy(SPMAT *A);

Description

sp_copy -- constructs a copy of a given matrix
-- note that the max_len fields (etc) are no larger in the copy than necessary
-- result is returned

Returns

The new matrix.


asin

Function: sp_copy2

Synopsis
#include <matrix.h>
SPMAT *sp_copy2(SPMAT *A,SPMAT *OUT);

Description

sp_copy2 -- copy sparse matrix (type 2)
-- keeps structure of the OUT matrix

Returns

The new matrix.


asin

Function: sp_diag_access

Synopsis
#include <matrix.h>
SPMAT *sp_diag_access(SPMAT *A);

Description

sp_diag_access -- set diagonal access path(s)

Returns

The input matrix.


asin

Function: sp_dump

Synopsis
#include <matrix.h>
void sp_dump(FILE *fp,SPMAT *A);

Description

sp_dump -- prints ALL relevant information about the sparse matrix A

Returns

No return value


asin

Function: sp_finput

Synopsis
#include <matrix.h>
SPMAT *sp_finput(FILE *fp);

Description

sp_finput -- input sparse matrix from stream/file fp
-- uses friendly input routine if fp is a tty
-- uses format identical to output format otherwise

Returns

The new sparse matrix


asin

Function: sp_foutput

Synopsis
#include <matrix.h>
void sp_foutput(FILE *fp,SPMAT *A);

Description

sp_foutput -- output sparse matrix A to file/stream fp

Returns

No return value


asin

Function: sp_free

Synopsis
#include <matrix.h>
int sp_free(SPMAT *A);

Description

sp_free -- frees up the memory for a sparse matrix

Returns

Zero if successful, -1 othewise.


asin

Function: sp_get

Synopsis
#include <matrix.h>
SPMAT *sp_get(int m,int n,int maxlen);

Description

sp_get -- get sparse matrix
-- maxlen is number of elements available for each row without allocating further memory

Returns

The newly constructed matrix.


asin

Function: sp_get_val

Synopsis
#include <matrix.h>
double sp_get_val(SPMAT *A,int i,int j);

Description

sp_get_val -- returns the (i, j) entry of the sparse matrix A

Returns

The value at the given location.


asin

Function: sp_input

Synopsis
#include <matrix.h>
#define sp_input() sp_finput(stdin)

Description

Inputs a matrix from stdin.

Returns

The new matrix.


asin

Function: sp_mv_mlt

Synopsis
#include <matrix.h>
VEC *sp_mv_mlt(SPMAT *A,VEC *x,VEC *out);

Description

sp_mv_mlt -- sparse matrix/dense vector multiply
-- result is in out, which is returned unless out==NULL on entry
-- if out==NULL on entry then the result vector is created

Returns

The result vector.


asin

Function: sp_output

Synopsis
#include <matrix.h>
#define sp_output(A) sp_foutput(stdout,(A))

Description

Writes a sparse matrix to the standard output

Returns

No result value


asin

Function: sp_resize

Synopsis
#include <matrix.h>
SPMAT *sp_resize(SPMAT *A,int m,int n);

Description

sp_resize -- resize a sparse matrix
-- don't destroying any contents if possible

Returns

The resized matrix.


asin

Function: sp_set_val

Synopsis
#include <matrix.h>
double sp_set_val(SPMAT *A,int i,int j,double val);

Description

sp_set_val -- sets the (i,j) entry of the sparse matrix A

Returns

Returns val or zero if there was an error (index < 0).


asin

Function: sp_vm_mlt

Synopsis
#include <matrix.h>
VEC *sp_vm_mlt(SPMAT *A,VEC *x,VEC *out);

Description

sp_vm_mlt -- sparse matrix/dense vector multiply from left
-- result is in out, which is returned unless out==NULL on entry
-- if out==NULL on entry then result vector is created and returned

Returns

The resulting vector.


asin

Function: sp_zero

Synopsis
#include <matrix.h>
SPMAT *sp_zero(SPMAT *A);

Description

sp_zero -- zero all the (represented) elements of a sparse matrix

Returns

The input sparse matrix A.


asin

Function: spBKPfactor

Synopsis
#include <matrix.h>
SPMAT *spBKPfactor(SPMAT *A,PERM *pivot,PERM *blocks,double tol);

Description

pBKPfactor -- sparse Bunch-Kaufman-Parlett factorisation of A in-situ
-- A is factored into the form P'AP = MDM' where
P is a permutation matrix, M lower triangular and D is block
diagonal with blocks of size 1 or 2
-- P is stored in pivot; blocks[i]==i iff D[i][i] is a block

Returns

The resulting sparse matrix


asin

Function: spBKPsolve

Synopsis
#include <matrix.h>
VEC *spBKPsolve(SPMAT *A,PERM *pivot,PERM *block,VEC *b,VEC *x);

Description

pBKPsolve -- solves A.x = b where A has been factored a la BKPfactor()
-- returns x, which is created if NULL

Returns

The resulting vector


asin

Function: spCHfactor

Synopsis
#include <matrix.h>
SPMAT *spCHfactor(SPMAT *A);

Description

spCHfactor -- sparse Cholesky factorisation
-- only the lower triangular part of A (incl. diagonal) is used

Returns

The resulting sparse matrix.


asin

Function: spCHsolve

Synopsis
#include <matrix.h>
VEC *spCHsolve(SPMAT *L,VEC *b,VEC *out);

Description

spCHsolve -- solve L.L^T.out=b where L is a sparse matrix,
-- out, b dense vectors
-- returns out; operation may be in-situ

Returns

The resulting vector.


asin

Function: spCHsym

Synopsis
#include <matrix.h>
SPMAT *spCHsymb(SPMAT *A);

Description

spCHsymb -- symbolic sparse Cholesky factorisation
-- does NOT do any floating point arithmetic; just sets up the structure
-- only the lower triangular part of A (incl. diagonal) is used

Returns

The resulting sparse matrix.


asin

Function: spICHfactor

Synopsis
#include <matrix.h>
SPMAT *spICHfactor(SPMAT *A);

Description

spICHfactor -- sparse Incomplete Cholesky factorisation
-- does a Cholesky factorisation assuming NO FILL-IN
-- as for spCHfactor(), only the lower triangular part of A is used

Returns

The factorized matrix.


asin

Function: spLUfactor

Synopsis
#include <matrix.h>
SPMAT *spLUfactor(SPMAT *A,PERM *px,double alpha);

Description

spLUfactor -- sparse LU factorisation with pivoting
-- uses partial pivoting and Markowitz criterion |a[p][k]| >= alpha * max_i |a[i][k]|
-- creates fill-in as needed
-- in situ factorisation

Returns

The result matrix.


asin

Function: spLUsolve

Synopsis
#include <matrix.h>
VEC *spLUsolve(SPMAT *A,PERM *pivot,VEC *b,VEC *x);

Description

spLUsolve -- solve A.x = b using factored matrix A from spLUfactor()
-- returns x
-- may not be in-situ

Returns

The result vector.


asin

Function: spLUTsolve

Synopsis
#include <matrix.h>
VEC *spLUTsolve(SPMAT *A,PERM *pivot,VEC *b,VEC *x);

Description

spLUTsolve -- solve A.x = b using factored matrix A from spLUfactor()
-- returns x
-- may not be in-situ

Returns

The result vector.


asin

Typedef: row_elt SPROW SPMAT

typedef struct row_elt {
    int col, nxt_row, nxt_idx;
    Real val;
} row_elt;

typedef struct SPROW {
    int len, maxlen, diag;
    row_elt *elt; /* elt[maxlen] */
} SPROW;

typedef struct SPMAT {
    int m, n, max_m, max_n;
    char flag_col, flag_diag;
    SPROW *row; /* row[max_m] */
    int *start_row; /* start_row[max_n] */
    int *start_idx; /* start_idx[max_n] */
} SPMAT;


asin

Function: sprow_add

Synopsis
#include <matrix.h>
SPROW *sprow_add(SPROW *r1,SPROW *r2,int j0,SPROW *r_out,int type);

Description

sprow_add -- sets r_out to r1 + r2
-- cannot be in situ
-- only for columns j0, j0+1, ...
-- type must be SPMAT or SPROW depending on
whether r_out is a row of a SPMAT structure
or a SPROW variable

Returns

Returns r_out.


asin

Function: sprow_foutput

Synopsis
#include <matrix.h>
void sprow_foutput(FILE *fp,SPROW *r);

Description

sprow_foutput -- print a representation of r on stream fp

Returns

No return value


asin

Function: sprow_get

Synopsis
#include <matrix.h>
SPROW *sprow_get(int maxlen);

Description

sprow_get -- gets, initialises and returns a SPROW structure. Maximum. length is maxlen

Returns

The newly allocated row.


asin

Function: sprow_idx

Synopsis
#include <matrix.h>
int sprow_idx(SPROW *r,int col);

Description

sprow_idx -- get index into row for a given column in a given row.

Returns

-- return -1 on error
-- return -(idx+2) where idx is index to insertion point


asin

Function: sprow_merge

Synopsis
#include <matrix.h>
SPROW *sprow_merge(SPROW *r1,SPROW *r2,SPROW *r_out, int type);

Description

sprow_merge -- merges r1 and r2 into r_out
-- cannot be done in-situ
-- type must be SPMAT or SPROW depending on whether r_out is a row of a SPMAT structure or a SPROW variable

Returns

Rreturns r_out


asin

Function: sprow_mltadd

Synopsis
#include <matrix.h>
SPROW *sprow_mltadd(SPROW *r1,SPROW *r2,double alpha,int j0,SPROW *r_out,int type);

Description

sprow_mltadd -- sets r_out to r1 + alpha.r2
-- cannot be in situ
-- only for columns j0, j0+1, ...
-- type must be SPMAT or SPROW depending on whether r_out is a row of a SPMAT structure or a SPROW variable

Returns

Returns r_out


asin

Function: sprow_set_val

Synopsis
#include <matrix.h>
double sprow_set_val(SPROW *r,int j,double val);

Description

sprow_set_val -- sets the j-th column entry of the sparse row r
-- Note: destroys the usual column & row access paths

Returns

Returns the value or zero if an error was found (the index was < 0).


asin

Function: sprow_smlt

Synopsis
#include <matrix.h>
SPROW *sprow_smlt(SPROW *r1,double alpha,int j0,SPROW *r_out,int type);

Description

sprow_smlt -- sets r_out to alpha*r1
-- can be in situ
-- only for columns j0, j0+1, ...

Returns

Returns r_out.


asin

Function: sprow_sub

Synopsis
#include <matrix.h>
SPROW *sprow_sub(SPROW *r1,SPROW *r2,int j0,SPROW *r_out,int type);

Description

sprow_sub -- sets r_out to r1 - r2
-- cannot be in situ
-- only for columns j0, j0+1, ...
-- type must be SPMAT or SPROW depending on whether r_out is a row of a SPMAT structure or a SPROW variable

Returns

Returns r_out.


asin

Function: sprow_xpd

Synopsis
#include <matrix.h>
SPROW *sprow_xpd(SPROW *r,int n,int type);

Description

sprow_xpd -- expand row by means of realloc()
-- type must be TYPE_SPMAT if r is a row of a SPMAT structure, otherwise it must be TYPE_SPROW

Returns

Rreturns r.


asin

Function: sv_mlt

Synopsis
#include <matrix.h>
VEC *sv_mlt(double scalar,VEC *vector,VEC *out);

Description

sv_mlt -- scalar-vector multiply -- may be in-situ

Returns

The resulting vector "out".


asin

Function: svd

Synopsis
#include <matrix.h>
VEC *svd(MAT *A,MAT *U,MAT *V,VEC *d);

Description

svd -- returns vector of singular values in d
-- also updates U and/or V, if one or the other is non-NULL
-- destroys A

Returns

The resulting vector d


asin

Function: symeigen

Synopsis
#include <matrix.h>
VEC *symmeig(MAT *A,MAT *Q,VEC *out);

Description

symmeig -- computes eigenvalues of a dense symmetric matrix
-- A **must** be symmetric on entry
-- eigenvalues stored in out
-- Q contains orthogonal matrix of eigenvectors

Returns

Vector of eigenvalues


asin

Function: trieigen

Synopsis
#include <matrix.h>
VEC *trieig(VEC *a,VEC *b,MAT *Q);

Description

trieig -- finds eigenvalues of symmetric tridiagonal matrices
-- matrix represented by a pair of vectors a (diagonal entries) and b (sub- and super-diagonal entries)
-- eigenvalues in a on return

Returns

The eigenvalues vector "a".


asin

Function: Usolve

Synopsis
#include <matrix.h>
VEC *Usolve(MAT *matrix,VEC *b,VEC *out,double diag);

Description

Usolve -- back substitution with optional over-riding diagonal
-- can be in-situ but doesn't need to be

Returns

The vector "out".


asin

Function: UTsolve

Synopsis
#include <matrix.h>
VEC *UTsolve(MAT *U,VEC *b,VEC *out,double diag);

Description

UTsolve -- forward elimination with (optional) default diagonal value using UPPER triangular part of matrix

Returns

The result vector "out".


asin

Function: v_add

Synopsis
#include <matrix.h>
VEC *v_add(VEC *vec1,VEC *vec2,VEC *out);

Description

v_add -- vector addition -- may be in-situ

Returns

The result vector "out".


asin

Function: v_conv

Synopsis
#include <matrix.h>
VEC *v_conv(VEC *x1,VEC *x2,VEC *out);

Description

Convolution product of two vectors

Returns

The result vector "out".


asin

Function: v_copy

Synopsis
#include <matrix.h>
#define v_copy(in,out) _v_copy(in,out,0)

Description

Copies vector in to vector out

Returns

No return value


asin

Function: v_dump

Synopsis
#include <matrix.h>
void v_dump(FILE *fp,VEC *x);

Description

Writes the vector "x" into stream "fp".

Returns

No return value


asin

Function: v_finput

Synopsis
#include <matrix.h>
VEC *v_finput(FILE *fp,VEC *x);

Description

Reads a vector from the given stream into vector "x"

Returns

The new vector


asin

Function: v_foutput

Synopsis
#include <matrix.h>
void v_foutput(FILE *fp,VEC *x);

Description

Writes the given vector into the given stream

Returns

No return value


asin

Function: V_FREE

Synopsis
#include <matrix.h>
#define V_FREE(vec) ( v_free(vec), (vec)=(VEC *)NULL )

Description

Releases the storage used by "vec".

Returns

No return value


asin

Function: v_free_vars

Synopsis
#include <matrix.h>
int v_free_vars(VEC **pv,...);

Description

Frees the memory used by the arguments.
The function should be called:
v_free_vars(&x,&y,&z,...,NULL);
 where
VEC *x, *y, *z,...;
 The last argument should be NULL There must be at least one not NULL argument.
Returned value of x,y,z,.. is VNULL.

Returns

The number of freed variables.


asin

Function: v_free

Synopsis
#include <matrix.h>
int v_free(VEC *vec);

Description

Releases the storage used by "vec".

Returns

Zero if successful, -1 otherwise.


asin

Function: v_get

Synopsis
#include <matrix.h>
VEC *v_get(int size);

Description

Allocates a new vector with the given dimensions.

Returns

The new vector


asin

Function: v_get_vars

Synopsis
#include <matrix.h>
int v_get_vars(int dim,...)

Description

To allocate memory to many arguments.
The function should be called:
v_get_vars(dim,&x,&y,&z,...,NULL);
where
int dim;
VEC *x, *y, *z,...;
 The last argument should be NULL. dim is the length of vectors x,y,z,...

Returns

The number of allocated variables


asin

Function: v_input

Synopsis
#include <matrix.h>
#define v_input(vec) v_finput(stdin,vec)

Description

Reads a vector from stdin

Returns

The new vector


asin

Function: v_lincomb

Synopsis
#include <matrix.h>
VEC *v_lincomb(int n,VEC *v[],Real a[],VEC *out);

Description

v_lincomb -- returns sum_i a[i].v[i], a[i] real, v[i] vectors
n = number of a's and v's

Returns

The result vector "out".


asin

Function: v_linlist

Synopsis
#include <matrix.h>
VEC *v_linlist(VEC *out,VEC *v1,double a1,...);

Description

v_linlist -- linear combinations taken from a list of arguments;
calling:
v_linlist(out,v1,a1,v2,a2,...,vn,an,NULL);
where vi are vectors (VEC *) and ai are numbers (double)

Returns

The result vector "out".

Example:

v_linlist(temp, v1, 1.0, v2, 2.0, v3, 2.0, v4, 1.0, VNULL);


asin

Function: v_map

Synopsis
#include <matrix.h>
VEC *v_map(double (*f)(double),VEC *x,VEC *out);

Description

v_map -- maps function f over components of x: out[i] = f(x[i])
-- _v_map sets out[i] = f(params,x[i])

Returns

The result vector "out".


asin

Function: v_max

Synopsis
#include <matrix.h>
double v_max(VEC *x,int *max_idx);

Description

v_max -- computes maximum component of x, which is returned
-- also sets max_idx to the index of this maximum

Returns

The maximum value.


asin

Function: v_min

Synopsis
#include <matrix.h>
double v_min(VEC *x,int *min_idx);

Description

v_min -- computes minimum component of x, which is returned
-- also sets max_idx to the index of this minimum

Returns

The minimum value.


asin

Function: v_mltadd

Synopsis
#include <matrix.h>
VEC *v_mltadd(VEC *v1,VEC *v2,double scale,VEC *out);

Description

v_mltadd -- scalar/vector multiplication and addition out = v1 + scale.v2

Returns

The resulting vector.


asin

Function: v_norm1 _v_norm1

Synopsis
#include <matrix.h>
double _v_norm1(VEC *x,VEC *scale);
#define v_norm1(x) _v_norm1(x,VNULL)

Description

_v_norm1 -- computes (scaled) 1-norms of vectors

Returns

The resulting norm.


asin

Function: v_norm2 _v_norm2

Synopsis
#include <matrix.h>
double _v_norm2(VEC *x,VEC *scale);
#define v_norm2(x) _v_norm2(x,VNULL)

Description

_v_norm2 -- computes (scaled) 2-norm (Euclidean norm) of vectors

Returns

The resulting norm.


asin

Function: v_norm_inf _v_norm_inf

Synopsis
#include <matrix.h>
double _v_norm_inf(VEC *x,VEC *scale);
#define v_norm_inf(x) _v_norm_inf(x,VNULL)

Description

_v_norm_inf -- computes (scaled) infinity-norm (supremum norm) of vectors

Returns

The resulting norm.


asin

Function: v_ones

Synopsis
#include <matrix.h>
VEC *v_ones(VEC *x);

Description

Fills x with one's

Returns

The filled vector.


asin

Function: v_output

Synopsis
#include <matrix.h>
#define v_output(vec) v_foutput(stdout,vec)

Description

Writes the given vectopr to stdout

Returns

No return value


asin

Function: v_pconv

Synopsis
#include <matrix.h>
VEC *v_pconv(VEC *x1,VEC *x2,VEC *out);

Description

v_pconv -- computes a periodic convolution product
-- the period is the dimension of x2

Returns

The result vector "out".


asin

Function: v_rand

Synopsis
#include <matrix.h>
VEC *v_rand(VEC *x);

Description

v_rand -- initialises x to be a random vector, components independently and uniformly distributed between 0 and 1

Returns

The result vector x


asin

Function: v_resize

Synopsis
#include <matrix.h>
VEC *v_resize(VEC *x,int new_dim);

Description

v_resize -- returns the vector x with dim new_dim
-- x is set to the zero vector

Returns

The resized vector x


asin

Function: v_resize_vars

Synopsis
#include <matrix.h>
int v_resize_vars(int new_dim,...);

Description

Resizes memory for many arguments.
The function should be called:
v_resize_vars(new_dim,&x,&y,&z,...,NULL);
where
int new_dim;
VEC *x, *y, *z,...;
 The last argument should be NULL. rdim is the resized length of vectors x,y,z,... If one of x,y,z,.. arguments is NULL then memory is allocated to this argument.

Returns

The number of allocated variables.


asin

Function: v_save

Synopsis
#include <matrix.h>
VEC *v_save(FILE *fp,VEC *x,char *name);

Description

v_save -- save vector in ".mat" file for MATLAB
-- saves it as a row vector

Returns

Returns the vector saved


asin

Function: v_slash

Synopsis
#include <matrix.h>
VEC *v_slash(VEC *x1,VEC *x2,VEC *out);

Description

v_slash -- computes componentwise ratio of x2 and x1
-- out[i] = x2[i] / x1[i]
-- if x1[i] == 0 for some i, then raise E_SING error

Returns

Returns the result vector "out".


asin

Function: v_sort

Synopsis
#include <matrix.h>
VEC *v_sort(VEC *x,PERM *order);

Description

v_sort -- sorts vector x, and generates permutation that gives the order of the components;
 x = [1.3, 3.7, 0.5] -> [0.5, 1.3, 3.7] and the permutation is order = [2, 0, 1].
-- if order is NULL on entry then it is ignored

Returns

The sorted vector x is returned


asin

Function: v_star

Synopsis
#include <matrix.h>
VEC *v_star(VEC *x1,VEC *x2,VEC *out);

Description

v_star -- computes componentwise (Hadamard) product of x1 and x2

Returns

The sorted vector out is returned


asin

Function: v_sub

Synopsis
#include <matrix.h>
VEC *v_sub(VEC *vec1,VEC *vec2,VEC *out);

Description

v_sub -- vector subtraction -- may be in-situ

Returns

The result vector "out".


asin

Function: v_sum

Synopsis
#include <matrix.h>
double v_sum(VEC *x);

Description

v_sum -- returns sum of entries of a vector

Returns

The sum.


asin

Function: v_zero

Synopsis
#include <matrix.h>
VEC *v_zero(VEC *x);

Description

Sets all elements of "x" to zero.

Returns

The input vector.


asin

Function: vm_mlt

Synopsis
#include <matrix.h>
VEC *vm_mlt(MAT *A,VEC *b,VEC *out);

Description

vm_mlt -- vector-matrix multiplication
-- Note: b is treated as a row vector

Returns

The resulting vector.


asin

Function: vm_mltadd

Synopsis
#include <matrix.h>
VEC *vm_mltadd(VEC *v1,VEC *v2,MAT *A,double alpha,VEC *out);

Description

vm_mltadd -- vector-matrix multiply and add
-- may not be in situ
-- returns out' == v1' + v2'*A

Returns

The resulting vector.


asin

Function: z_finput

Synopsis
#include <matrix.h>
complex z_finput(FILE *fp);

Description

Reads a complex from the stream fp.

Returns

The complex number


asin

Function: z_output

Synopsis
#include <matrix.h>
void z_foutput(FILE *fp,complex z);

Description

Writes a complex from the stream fp.

Returns

No return value


asin

Function: z_input

Synopsis
#include <matrix.h>
#define z_input() z_finput(stdin)

Description

Reads a complex from stdin.

Returns

The result complex


asin

Function: z_save

Synopsis
#include <matrix.h>
complex z_save(FILE *fp,complex z,char *name);

Description

z_save -- saves complex number in ".mat" file for MATLAB

Returns

The saved number.


asin

Function: zgivens

Synopsis
#include <matrix.h>
void zgivens(complex x,complex y,Real *c,complex *s);

Description

zgivens -- returns c,and s parameters for Givens rotation to eliminate y in the column vector [ x y ]

Returns

No return value


asin

Function: zhhtrcols

Synopsis
#include <matrix.h>
ZMAT *zhhtrcols(ZMAT *M,int i0,int j0,ZVEC *hh,double beta);

Description

zhhtrcols -- transform a matrix by a Householder vector by columns starting at row i0 from column j0
-- in-situ

Returns

The result complex matrix. (M)


asin

Function: zhhtrrvec

Synopsis
#include <matrix.h>
ZVEC *zhhtrvec(ZVEC *hh,double beta,int i0,ZVEC *in,ZVEC *out);

Description

zhhtrvec -- apply Householder transformation to vector -- may be in-situ

Returns

The result complex vector "out".


asin

Function: zin_prod _zin_prod

Synopsis
#include <matrix.h>
#define zin_prod(x,y) _zin_prod(x,y,0,Z_CONJ)
complex _zin_prod(ZVEC *a,ZVEC *b,unsigned i0,unsigned flag);

Description

_zin_prod -- inner product of two vectors from i0 downwards
-- flag != 0 means compute sum_i a[i]*.b[i];
-- flag == 0 means compute sum_i a[i].b[i]

Returns

The result complex


asin

Function: zLAsolve

Synopsis
#include <matrix.h>
ZVEC *zLAsolve(ZMAT *L,ZVEC *b,ZVEC *out,double diag);

Description

zLAsolve -- back substitution with optional over-riding diagonal using the LOWER triangular part of matrix
-- can be in-situ but doesn't need to be

Returns

The result complex vector


asin

Function: zLsolve

Synopsis
#include <matrix.h>
ZVEC *zLsolve(ZMAT *matrix,ZVEC *b,ZVEC *out,double diag);

Description

zLsolve -- forward elimination with (optional) default diagonal value

Returns

The result complex vector


asin

Function: zLsolve

Synopsis
#include <matrix.h>
ZVEC *zLUAsolve(ZMAT *LU,PERM *pivot,ZVEC *b,ZVEC *x);

Description

zLUAsolve -- given an LU factorisation in A, solve A^*.x=b

Returns

The result complex vector


asin

Function: zLUcondtest

Synopsis
#include <matrix.h>
double zLUcondest(ZMAT *LU,PERM *pivot);

Description

zLUcondest -- returns an estimate of the condition number of LU given the LU factorization in compact form

Returns

The estimated condition number.


asin

Function: zLUfactor

Synopsis
#include <matrix.h>
ZMAT *zLUfactor(ZMAT *A,PERM *pivot);

Description

zLUfactor -- Gaussian elimination with scaled partial pivoting

Returns

Returns LU matrix which is A


asin

Function: zLUsolve

Synopsis
#include <matrix.h>
ZVEC *zLUsolve(ZMAT *A,PERM *pivot,ZVEC *b,ZVEC *x);

Description

zLUsolve -- given an LU factorisation in A, solve Ax=b

Returns

Returns the complex vector x.


asin

Function: zm_add

Synopsis
#include <matrix.h>
ZMAT *zm_add(ZMAT *mat1,ZMAT *mat2,ZMAT *out);

Description

Adds complex matrices mat1 + mat2. Result in out.

Returns

Returns the resulting matrix.


asin

Function: zm_adjoint

Synopsis
#include <matrix.h>
ZMAT *zm_adjoint(ZMAT *in,ZMAT *out);

Description

Calculates the adjoint matrix

Returns

Returns the resulting matrix.


asin

Function: zm_dump

Synopsis
#include <matrix.h>
void zm_dump(FILE *fp,ZMAT *a);

Description

Writes the given matrix to the indicated stream.

Returns

No result value


asin

Function: zm_finput

Synopsis
#include <matrix.h>
ZMAT *zm_finput(FILE *fp,ZMAT *mat);

Description

Reads the matrix from the indicated stream

Returns

The new matrix.


asin

Function: ZM_FREE

Synopsis
#include <matrix.h>
#define ZM_FREE(A) ( zm_free(A), (A) = ZMNULL )

Description

Releases the storage used by the given matrix

Returns

No result value


asin

Function: zm_free_vars

Synopsis
#include <matrix.h>
int zm_free_vars(ZMAT **va,...);

Description

Function to free memory of several arguments.
The function should be called:
zm_free_vars(&x,&y,&z,...,NULL);
where
ZMAT *x, *y, *z,...;
 The last argument should be NULL.

Returns

The number of variables freed


asin

Function: zm_free

Synopsis
#include <matrix.h>
int zm_free(ZMAT *mat);

Description

Releases the storage used by the given matrix

Returns

Zero if successful, -1 otherwise


asin

Function: zm_get_vars

Synopsis
#include <matrix.h>
int zm_get_vars(int m,int n,...):

Description

Allocates an m x n complex matrix.for each argument given

Returns

The number of matrices allocated.

Example:

assert( 3 == zm_get_vars(8,5,&zA,&zB,&zC,NULL));


asin

Function: zm_input

Synopsis
#include <matrix.h>
#define zm_input(A) zm_finput(stdin,A);

Description

Reads a complex matrix from stdin.

Returns

The new complex matrix


asin

Function: zm_inverse

Synopsis
#include <matrix.h>
ZMAT *zm_inverse(ZMAT *A,ZMAT *out);

Description

zm_inverse -- returns inverse of A, provided A is not too rank deficient
-- uses LU factorisation

Returns

The inverted complex matrix "out"


asin

Function: zm_load

Synopsis
#include <matrix.h>
ZMAT *zm_load(FILE *fp,char **name);

Description

zm_load -- loads in a ".mat" file variable as produced by MATLAB
-- matrix returned; imaginary parts ignored

Returns

The matrix reloaded...


asin

Function: zm_mlt

Synopsis
#include <matrix.h>
ZMAT *zm_mlt(ZMAT *A,ZMAT *B,ZMAT *OUT);

Description

Complex matrix multiplication.

Returns

The result complex matrix ("out").


asin

Function: zm_norm1

Synopsis
#include <matrix.h>
double zm_norm1(ZMAT *A);

Description

zm_norm1 -- compute matrix 1-norm -- unscaled

Returns

The norm


asin

Function: zm_norm_frob

Synopsis
#include <matrix.h>
double zm_norm_frob(ZMAT *A);

Description

zm_norm_frob -- compute matrix frobenius-norm -- unscaled

Returns

The norm


asin

Function: zm_norm_inf

Synopsis
#include <matrix.h>
double zm_norm_inf(ZMAT *A);

Description

zm_norm_inf -- compute matrix infinity-norm -- unscaled

Returns

The norm


asin

Function: zm_rand

Synopsis
#include <matrix.h>
ZMAT *zm_rand(ZMAT *A);

Description

zm_rand -- randomise a complex matrix; uniform in [0,1)+[0,1)*i

Returns

The result matrix (A)


asin

Function: zm_resize

Synopsis
#include <matrix.h>
ZMAT *zm_resize(ZMAT *A,int new_m,int new_n);

Description

m_resize -- returns the matrix A of size new_m x new_n; A is zeroed
-- if A == NULL on entry then the effect is equivalent to m_get()

Returns

The resized matrix


asin

Function: zm_resize_vars

Synopsis
#include <matrix.h>
int zv_resize_vars(int m, int n,...);

Description

Resize memory for several arguments.
The function should be called:
zm_resize_vars(new_dim_x,new_dim_y,,&x,&y,&z,...,NULL);
 where
int new_dim_x,new_dim_y;
ZMAT *x, *y, *z,...;
The last argument should be NULL.
If one of x,y,z,.. arguments is NULL then memory is allocated to this argument.

Returns

The number of variables resized.


asin

Function: zm_save

Synopsis
#include <matrix.h>
ZMAT *zm_save(FILE *fp,ZMAT *A,char *name);

Description

zm_save -- save matrix in ".mat" file for MATLAB

Returns

The matrix saved.


asin

Function: zm_sub

Synopsis
#include <matrix.h>
ZMAT *zm_sub(ZMAT *mat1,ZMAT *mat2,ZMAT *out);

Description

zm_sub: subtract matrices mat1 from mat2 and store result in out.

Returns

The result complex matrix.


asin

Function: zm_zero

Synopsis
#include <matrix.h>
ZMAT *zm_zero(ZMAT *A);

Description

zm_zero -- zeros all entries of a complex matrix

Returns

The zeroed matrix


asin

Function: zmakeQ

Synopsis
#include <matrix.h>
ZMAT *zmakeQ(ZMAT *QR,ZVEC *diag,ZMAT *Qout);

Description

zmakeQ -- constructs orthogonal matrix from Householder vectors stored in compact QR form

Returns

Returns the resulting matrix.


asin

Function: zmakeR

Synopsis
#include <matrix.h>
ZMAT *zmakeR(ZMAT *QR,ZMAT *Rout);

Description

makeR -- constructs upper triangular matrix from QR (compact form)
-- may be in-situ (all it does is zero the lower 1/2)

Returns

Returns the resulting matrix.


asin

Function: zmam_mlt

Synopsis
#include <matrix.h>
ZMAT *zmam_mlt(ZMAT *A,ZMAT *B,ZMAT *OUT);

Description

zmam_mlt -- matrix adjoint-matrix multiplication
-- A*.B is returned, result stored in OUT

Returns

Returns the resulting complex matrix.


asin

Function: zm_get

Synopsis
#include <matrix.h>
ZMAT *zm_get(int m,int n);

Description

Allocates an m x n complex matrix.

Returns

The new matrix


asin

Function: zmma_mlt

Synopsis
#include <matrix.h>
ZMAT *zmma_mlt(ZMAT *A,ZMAT *B,ZMAT *OUT);

Description

zmma_mlt -- matrix-matrix adjoint multiplication
-- A.B* is returned, and stored in OUT

Returns

The result complex matrix ("out").


asin

Function: zmv_mlt

Synopsis
#include <matrix.h>
ZVEC *zmv_mlt(ZMAT *A,ZVEC *b,ZVEC *out);

Description

zmv_mlt -- matrix-vector multiplication
-- Note: b is treated as a column vector

Returns

The result complex matrix.


asin

Function: zmv_mltadd

Synopsis
#include <matrix.h>
ZVEC *zmv_mltadd(ZVEC *v1,ZVEC *v2,ZMAT *A,complex alpha,ZVEC *out);

Description

zmv_mltadd -- matrix-vector multiply and add
-- may not be in situ
-- returns out == v1 + alpha*A*v2

Returns

The result complex vector


asin

Function: zQRAsolve

Synopsis
#include <matrix.h>
ZVEC *zQRAsolve(ZMAT *QR,ZVEC *diag,ZVEC *b,ZVEC *x);

Description

zQRAsolve -- solves the system (Q.R)*.x = b

Returns

The result complex vector.


asin

Function: zQRCPfactor

Synopsis
#include <matrix.h>
ZMAT *zQRCPfactor(ZMAT *A,ZVEC *diag,PERM *px);

Description

zQRCPfactor -- forms the QR factorisation of A with column pivoting

Returns

The result complex matrix.


asin

Function: zQRCPsolve

Synopsis
#include <matrix.h>
ZVEC *zQRCPsolve(ZMAT *QR,ZVEC *diag,PERM *pivot,ZVEC *b,ZVEC *x);

Description

zQRCPsolve -- solves A.x = b where A is factored by QRCPfactor()
-- assumes that A is in the compact factored form

Returns

The result complex vector.


asin

Function: zQRfactor

Synopsis
#include <matrix.h>
ZMAT *zQRfactor(ZMAT *A,ZVEC *diag);

Description

zQRfactor -- forms the QR factorization of A

Returns

The result complex matrix.


asin

Function: zQRsolve

Synopsis
#include <matrix.h>
ZVEC *zQRsolve(ZMAT *QR,ZVEC *diag,ZVEC *b,ZVEC *x);

Description

zQRsolve -- solves the system Q.R.x=b where Q & R are stored in compact form
-- returns x, which is created if necessary

Returns

The result complex vector.


asin

Function: zrot_cols

Synopsis
#include <matrix.h>
ZMAT *zrot_cols(ZMAT *mat,int i,int k,double c,complex s,ZMAT *out);

Description

zrot_cols -- postmultiply mat by adjoint Givens rotation described by c,s

Returns

The result complex matrix.


asin

Function: zrot_rows

Synopsis
#include <matrix.h>
ZMAT *zrot_rows(ZMAT *mat,int i,int k,double c,complex s,ZMAT *out);

Description

zrot_rows -- premultiply mat by givens rotation described by c,s

Returns

The result complex matrix.


asin

Function: zschur

Synopsis
#include <matrix.h>
ZMAT *zschur(ZMAT *A,ZMAT *Q);

Description

zschur -- computes the Schur decomposition of the matrix A in situ
-- optionally, gives Q matrix such that Q^*.A.Q is upper triangular

Returns

Returns upper triangular Schur matrix


asin

Function: zset_col

Synopsis
#include <matrix.h>
ZMAT *zset_col(ZMAT *mat,int col,ZVEC *vec);

Description

zset_col -- sets column of matrix to values given in vec (in situ)

Returns

Returns the input matrix


asin

Function: zset_row

Synopsis
#include <matrix.h>
ZMAT *zset_row(ZMAT *mat,int row,ZVEC *vec);

Description

zset_col -- sets the given row of matrix to values given in vec (in situ)

Returns

Returns the input matrix


asin

Function: zsm_mlt

Synopsis
#include <matrix.h>
ZMAT *zsm_mlt(complex scalar,ZMAT *matrix,ZMAT *out);

Description

zsm_mlt -- scalar-matrix multiply -- may be in-situ

Returns

Returns the result matrix


asin

Function: zUAsolve

Synopsis
#include <matrix.h>
ZVEC *zUAsolve(ZMAT *U,ZVEC *b,ZVEC *out,double diag);

Description

zUAsolve -- forward elimination with (optional) default diagonal value using UPPER triangular part of matrix. The optional diag value is 0.0.

Returns

Returns the result vector


asin

Function: zUsolve

Synopsis
#include <matrix.h>
ZVEC *zUsolve(ZMAT *matrix,ZVEC *b,ZVEC *out,double diag);

Description

zUsolve -- back substitution with optional over-riding diagonal
-- can be in-situ but doesn't need to be. The optional diag value is 0.0.

Returns

Returns the result vector


asin

Function: zv_add

Synopsis
#include <matrix.h>
ZVEC *zv_add(ZVEC *vec1,ZVEC *vec2,ZVEC *out);

Description

zv_add -- vector addition -- may be in-situ

Returns

Returns the result vector


asin

Function: zv_copy _zv_copy

Synopsis
#include <matrix.h>
#define zv_copy(x,y) _zv_copy(x,y,0);
ZVEC *_zv_copy(ZVEC *in,ZVEC *out,unsigned i0)

Description

_zv_copy copies thesource vector in into out. The i0 argument is the starting index of the copy.

Returns

Returns the result vector


asin

Function: zv_dump

Synopsis
#include <matrix.h>
void zv_dump(FILE *fp,ZVEC *x);

Description

zv_dump writes the complex vector "x" into the stream fp.

Returns

No return value


asin

Function: zv_finput

Synopsis
#include <matrix.h>
ZVEC *zv_finput(FILE *fp,ZVEC *x);

Description

Reads a complex vector from the stream fp.

Returns

The new complex vector


asin

Function: ZV_FREE

Synopsis
#include <matrix.h>
#define ZV_FREE(x) ( zv_free(x), (x) = ZVNULL )

Description

Frees the storage used by the given complex vector, and sets it to NULL.

Returns

No return value


asin

Function: zv_get

Synopsis
#include <matrix.h>
ZVEC *zv_get(int size);

Description

zv_get -- gets a ZVEC of dimension 'dim'
-- Note: initialized to zero

Returns

The new complex vector.


asin

Function: zv_free

Synopsis
#include <matrix.h>
int zv_free(ZVEC *vec);

Description

Frees the storage used by the given complex vector, and sets it to NULL.

Returns

Zero is successful, -1 othewise


asin

Function: zv_get_vars

Synopsis
#include <matrix.h>
int zv_get_vars(int dim,...);

Description

Allocates several variables. The function should be called:
zv_get_vars(dim,&x,&y,&z,...,NULL);
 where
int dim;
ZVEC *x, *y, *z,...;
 The last argument should be NULL. dim is the length of vectors x,y,z,...

Returns

The number of allocated variables.


asin

Function: zv_input

Synopsis
#include <matrix.h>
#define zv_input(x) zv_finput(stdin,x)

Description

Reads a complex matrix from standard input

Returns

The new matrix.


asin

Function: zv_lincomb

Synopsis
#include <matrix.h>
ZVEC *zv_lincomb(int n,ZVEC *v[],complex a[],ZVEC *out);

Description

zv_lincomb -- returns sum_i a[i].v[i], a[i] real, v[i] vectors
n is the number of a's and v's

Returns

The result complex vector (out)..


asin

Function: zv_linlist

Synopsis
#include <matrix.h>
ZVEC *zv_linlist(ZVEC *out,ZVEC *v1,complex a1,...);

Description

zv_linlist -- linear combinations taken from a list of arguments;

Returns

The result complex vector (out)..

Example:

zv_linlist(out,v1,a1,v2,a2,...,vn,an,NULL);
 where vi are vectors (ZVEC *) and ai are numbers (complex)


asin

Function: zv_map _zv_map

Synopsis
#include <matrix.h>
ZVEC *zv_map(complex (*f)(complex),ZVEC *x,ZVEC *out);
ZVEC *_zv_map(complex (*f)(void *,complex),void *params,ZVEC *x,ZVEC *out)

Description

zv_map -- maps function f over components of x: out[i] = f(x[i])
-- _zv_map sets out[i] = f(x[i],params)

Returns

The result complex vector (out)..


asin

Function: zv_mlt

Synopsis
#include <matrix.h>
ZVEC *zv_mlt(complex scalar,Zvec *vector,ZVEC *out);

Description

zv_mlt -- scalar-vector multiply -- may be in-situ

Returns

The result complex vector (out)..


asin

Function: zv_mltadd

Synopsis
#include <matrix.h>
ZVEC *zv_mltadd(ZVEC *v1,ZVEC *v2,complex scale,ZVEC *out);

Description

zv_mltadd -- scalar/vector multiplication and addition
-- out = v1 + scale x v2

Returns

The result complex vector (out)..


asin

Function: zv_norm1 _zv_norm1

Synopsis
#include <matrix.h>
#define zv_norm1(x) _zv_norm1(x,VNULL)
double _zv_norm1(ZVEC *x,VEC *scale);

Description

zv_norm1 -- computes (scaled) 1-norms of vectors

Returns

The norm


asin

Function: zv_norm2 _zv_norm2

Synopsis
#include <matrix.h>
#define zv_norm2(x) _zv_norm2(x,VNULL)
double _zv_norm2(ZVEC *x,VEC *scale);

Description

_zv_norm2 -- computes (scaled) 2-norm (Euclidean norm) of vectors

Returns

The norm


asin

Function: zv_norm_inf _zv_norm_inf

Synopsis
#include <matrix.h>
#define zv_norm_inf(x) _zv_norm_inf(x,VNULL)
double _zv_norm_inf(ZVEC *x,VEC *scale);

Description

_zv_norm_inf -- computes (scaled) infinity-norm (supremum norm) of vectors

Returns

The norm


asin

Function: zv_rand

Synopsis
#include <matrix.h>
ZVEC *zv_rand(ZVEC *x);

Description

zv_rand -- randomise a complex vector; uniform in [0,1)+[0,1)*i

Returns

The randomized vector.


asin

Function: zv_resize

Synopsis
#include <matrix.h>
ZVEC *zv_resize(ZVEC *x,int new_dim);

Description

Redimentions the vector

Returns

The redimensioned vector.


asin

Function: zv_resize_vars

Synopsis
#include <matrix.h>
int zv_resize_vars(int new_dim,...);

Description

Redimentions the list of vectors to the given dimension new_dim.

Returns

The number of vectors redimensioned.

Example:

v_resize_vars(new_dim,&x,&y,&z,...,NULL);


asin

Function: zv_save

Synopsis
#include <matrix.h>
ZVEC *zv_save(FILE *fp,ZVEC *x,char *name);

Description

zv_save -- save vector in ".mat" file for MATLAB
-- saves it as a row vector
Returns

The vector


asin

Function: zv_slash

Synopsis
#include <matrix.h>
ZVEC *zv_slash(ZVEC *x1,ZVEC *x2,ZVEC *out);

Description

zv_slash -- computes componentwise ratio of x2 and x1
-- out[i] = x2[i] / x1[i]
-- if x1[i] == 0 for some i, then raise E_SING error

Returns

Result out is returned


asin

Function: zv_star

Synopsis
#include <matrix.h>
ZVEC *zv_star(ZVEC *x1,ZVEC *x2,ZVEC *out);

Description

zv_star -- computes componentwise (Hadamard) product of x1 and x2

Returns

Result out is returned


asin

Function: zv_sub

Synopsis
#include <matrix.h>
ZVEC *zv_sub(ZVEC *vec1,ZVEC *vec2,ZVEC *out);

Description

zv_sub -- vector subtraction -- may be in-situ

Returns

Result out is returned


asin

Function: zv_sum

Synopsis
#include <matrix.h>
complex zv_sum(ZVEC *x);

Description

Sums a vector
Returns

The sum


asin

Function: zv_zero

Synopsis
#include <matrix.h>
ZVEC *zv_zero(ZVEC *x);

Description

zv_zero -- zeros all entries of a complex vector

Returns

The zeroed input vector


asin

Function: zvm_mlt

Synopsis
#include <matrix.h>
ZVEC *zvm_mlt(ZMAT *A,ZVEC *b,ZVEC *out);

Description

zvm_mlt -- vector adjoint-matrix multiplication

Returns

The result complex vector (out)..


asin

Function: zvm_mltadd

Synopsis
#include <matrix.h>
ZVEC *zvm_mltadd(ZVEC *v1,ZVEC *v2,ZMAT *A,complex alpha,ZVEC *out);

Description

zvm_mltadd -- vector-matrix multiply and add a la zvm_mlt()
-- may not be in situ
-- returns out == v1 + v2 * A

Returns

The result complex vector (out)..


asin

Function: zhhtrrows

Synopsis
#include <matrix.h>
ZMAT *zhhtrrows(ZMAT *M,int i0,int j0,ZVEC *hh,double beta);

Description

zhhtrrows -- transform a matrix by a Householder vector by rows starting at row i0 from column j0
-- in-situ

Returns

The result complex matrix. (M)


strncat

Function: pcre_copy_substring pcre_get_substring pcre_get_substring_list

Synopsis
#include <pcre.h>
int pcre_copy_substring(const char *subject, int *ovector, int stringcount, int stringnumber, char *buffer, int buffersize);
int pcre_get_substring(const char *subject, int *ovector, int stringcount, int stringnumber, const char **stringptr);
int pcre_get_substring_list(const char *subject, int *ovector, int stringcount, const char ***listptr);

Description

Captured substrings can be accessed directly by using the offsets returned by pcre_exec() in its output vector. For convenience, the functions pcre_copy_substring(), pcre_get_substring(), and pcre_get_substring_list() are provided for extracting captured substrings as new, separate, zero-terminated strings. These functions identify substrings by number. The next section describes functions for extracting named sub- strings. A substring that contains a binary zero is correctly extracted and has a further zero added on the end, but the result is not, of course, a C string.

The first three arguments are the same for all three of these functions: subject is the subject string which has just been successfully matched, ovector is a pointer to the vector of integer offsets that was passed to pcre_exec(), and stringcount is the number of substrings that were cap- tured by the match, including the substring that matched the entire regular expression. This is the value returned by pcre_exec if it is greater than zero. If pcre_exec() returned zero, indicating that it ran out of space in ovec- tor, the value passed as stringcount should be the size of the vector divided by three. The functions pcre_copy_substring() and pcre_get_substring() extract a single substring, whose number is given as string- number. A value of zero extracts the substring that matched the entire pattern, while higher values extract the captured substrings. For pcre_copy_substring(), the string is placed in buffer, whose length is given by buffersize, while for pcre_get_substring() a new block of memory is obtained via pcre_malloc, and its address is returned via stringptr.

Returns

The result of the function is the length of the string, not including the terminating zero, or one of

PCRE_ERROR_NOMEMORY (-6)

The buffer was too small for pcre_copy_substring(), or the attempt to get memory failed for pcre_get_substring().

PCRE_ERROR_NOSUBSTRING (-7)

There is no substring whose number is stringnumber.

The pcre_get_substring_list() function extracts all avail- able substrings and builds a list of pointers to them. All this is done in a single block of memory which is obtained via pcre_malloc. The address of the memory block is returned via listptr, which is also the start of the list of string pointers. The end of the list is marked by a NULL pointer. The yield of the function is zero if all went well, or

PCRE_ERROR_NOMEMORY (-6)

if the attempt to get the memory block failed.

When any of these functions encounter a substring that is unset, which can happen when capturing subpattern number n+1 matches some part of the subject, but subpattern n has not been used at all, they return an empty string. This can be distinguished from a genuine zero-length substring by inspecting the appropriate offset in ovector, which is nega- tive for unset substrings.

The two convenience functions pcre_free_substring() and pcre_free_substring_list() can be used to free the memory returned by a previous call of pcre_get_substring() or pcre_get_substring_list(), respectively. They do nothing more than call the function pointed to by pcre_free, which of course could be called directly from a C program. How- ever, PCRE is used in some situations where it is linked via a special interface to another programming language which cannot use pcre_free directly; it is for these cases that the functions are provided.


New Page 1

/*************************************************
*           PCRE DEMONSTRATION PROGRAM           *
*************************************************/
/* This is a demonstration program to illustrate the most straightforward ways
of calling the PCRE regular expression library from a C program. See the
pcresample documentation for a short discussion.
Compile like this:
lc pcredemo.c pcre.lib
*/

#include <stdio.h>
#include <string.h>
#include <pcre.h>
#define OVECCOUNT 30    /* should be a multiple of 3 */

int main(int argc, char **argv)
{
    pcre *re;
    const char *error;
    char *pattern;
    char *subject;
    unsigned char *name_table;
    int erroffset;
    int find_all;
    int namecount;
    int name_entry_size;
    int ovector[OVECCOUNT];
    int subject_length;
    int rc, i;

    /*************************************************************************
    * First, sort out the command line. There is only one possible option at *
    * the moment, "-g" to request repeated matching to find all occurrences, *
    * like Perl's /g option. We set the variable find_all non-zero if it is  *
    * present. Apart from that, there must be exactly two arguments.         *
    *************************************************************************/
    find_all = 0;
    for (i = 1; i < argc; i++)
    {
        if (strcmp(argv[i], "-g") == 0) find_all = 1;
        else break;
    }
    /* After the options, we require exactly two arguments, which are the pattern,
    and the subject string. */
    if (argc - i != 2)
    {
        printf("Two arguments required: a regex and a subject string\n");
        return 1;
    }
    pattern = argv[i];
    subject = argv[i+1];
    subject_length = (int)strlen(subject);

    /*************************************************************************
    * Now we are going to compile the regular expression pattern, and handle *
    * and errors that are detected.                                          *
    *************************************************************************/
    re = pcre_compile(
        pattern,              /* the pattern */
        0,                    /* default options */
        &error,               /* for error message */
        &erroffset,           /* for error offset */
        NULL);                /* use default character tables */
    /* Compilation failed: print the error message and exit */
    if (re == NULL)
    {
        printf("PCRE compilation failed at offset %d: %s\n", erroffset, error);
        return 1;
    }

    /*************************************************************************
    * If the compilation succeeded, we call PCRE again, in order to do a     *
    * pattern match against the subject string. This just does ONE match. If *
    * further matching is needed, it will be done below.                     *
    *************************************************************************/
    rc = pcre_exec(
        re,                   /* the compiled pattern */
        NULL,                 /* no extra data - we didn't study the pattern */
        subject,              /* the subject string */
        subject_length,       /* the length of the subject */
        0,                    /* start at offset 0 in the subject */
        0,                    /* default options */
        ovector,              /* output vector for substring information */
        OVECCOUNT);           /* number of elements in the output vector */
    /* Matching failed: handle error cases */
    if (rc < 0)
    {
        switch(rc)
        {
        case PCRE_ERROR_NOMATCH:
            printf("No match\n");
            break;
            /*
            Handle other special cases if you like
            */
        default:
            printf("Matching error %d\n", rc);
            break;
        }
        return 1;
    }
    /* Match succeded */
    printf("\nMatch succeeded at offset %d\n", ovector[0]);

    /*************************************************************************
    * We have found the first match within the subject string. If the output *
    * vector wasn't big enough, set its size to the maximum. Then output any *
    * substrings that were captured.                                         *
    *************************************************************************/
    /* The output vector wasn't big enough */
    if (rc == 0)
    {
        rc = OVECCOUNT/3;
        printf("ovector only has room for %d captured substrings\n", rc - 1);
    }
    /* Show substrings stored in the output vector by number. Obviously, in a real
    application you might want to do things other than print them. */
    for (i = 0; i < rc; i++)
    {
        char *substring_start = subject + ovector[2*i];
        int substring_length = ovector[2*i+1] - ovector[2*i];
        printf("%2d: %.*s\n", i, substring_length, substring_start);
    }

    /*************************************************************************
    * That concludes the basic part of this demonstration program. We have   *
    * compiled a pattern, and performed a single match. The code that follows*
    * first shows how to access named substrings, and then how to code for   *
    * repeated matches on the same subject.                                  *
    *************************************************************************/
    /* See if there are any named substrings, and if so, show them by name. First
    we have to extract the count of named parentheses from the pattern. */
    (void)pcre_fullinfo(
        re,                   /* the compiled pattern */
        NULL,                 /* no extra data - we didn't study the pattern */
        PCRE_INFO_NAMECOUNT,  /* number of named substrings */
        &namecount);          /* where to put the answer */
    if (namecount <= 0) printf("No named substrings\n");
    else
        {
        unsigned char *tabptr;
        printf("Named substrings\n");
        /* Before we can access the substrings, we must extract the table for
        translating names to numbers, and the size of each entry in the table. */
        (void)pcre_fullinfo(
            re,                       /* the compiled pattern */
            NULL,                     /* no extra data - we didn't study the pattern */
            PCRE_INFO_NAMETABLE,      /* address of the table */
            &name_table);             /* where to put the answer */
        (void)pcre_fullinfo(
            re,                       /* the compiled pattern */
            NULL,                     /* no extra data - we didn't study the pattern */
            PCRE_INFO_NAMEENTRYSIZE,  /* size of each entry in the table */
            &name_entry_size);        /* where to put the answer */
        /* Now we can scan the table and, for each entry, print the number, the name,
        and the substring itself. */
        tabptr = name_table;
        for (i = 0; i < namecount; i++)
        {
            int n = (tabptr[0] << 8) | tabptr[1];
            printf("(%d) %*s: %.*s\n", n, name_entry_size - 3, tabptr + 2,
                ovector[2*n+1] - ovector[2*n], subject + ovector[2*n]);
            tabptr += name_entry_size;
        }
    }

    /*************************************************************************
    * If the "-g" option was given on the command line, we want to continue  *
    * to search for additional matches in the subject string, in a similar   *
    * way to the /g option in Perl. This turns out to be trickier than you   *
    * might think because of the possibility of matching an empty string.    *
    * What happens is as follows:                                            *
    *                                                                        *
    * If the previous match was NOT for an empty string, we can just start   *
    * the next match at the end of the previous one.                         *
    *                                                                        *
    * If the previous match WAS for an empty string, we can't do
    *****************************************/
    if (!find_all) return 0;   /* Finish unless -g was given */
    /* Loop for second and subsequent matches */
    for (;;)
    {
        int options = 0;                 /* Normally no options */
        int start_offset = ovector[1];   /* Start at end of previous match */
        /* If the previous match was for an empty string, we are finished if we are
        at the end of the subject. Otherwise, arrange to run another match at the
        same point to see if a non-empty match can be found. */
        if (ovector[0] == ovector[1])
        {
            if (ovector[0] == subject_length) break;
            options = PCRE_NOTEMPTY | PCRE_ANCHORED;
        }
        /* Run the next matching operation */
        rc = pcre_exec(
            re,                   /* the compiled pattern */
            NULL,                 /* no extra data - we didn't study the pattern */
            subject,              /* the subject string */
            subject_length,       /* the length of the subject */
            start_offset,         /* starting offset in the subject */
            options,              /* options */
            ovector,              /* output vector for substring information */
            OVECCOUNT);           /* number of elements in the output vector */
        /* This time, a result of NOMATCH isn't an error. If the value in "options"
        is zero, it just means we have found all possible matches, so the loop ends.
        Otherwise, it means we have failed to find a non-empty-string match at a
        point where there was a previous empty-string match. In this case, we do what
        Perl does: advance the matching position by one, and continue. We do this by
        setting the "end of previous match" offset, because that is picked up at the
        top of the loop as the point at which to start again. */
        if (rc == PCRE_ERROR_NOMATCH)
        {
            if (options == 0) break;
            ovector[1] = start_offset + 1;
            continue;    /* Go round the loop again */
        }
        /* Other matching errors are not recoverable. */
        if (rc < 0)
        {
            printf("Matching error %d\n", rc);
            return 1;
        }
        /* Match succeded */
        printf("\nMatch succeeded again at offset %d\n", ovector[0]);
        /* The match succeeded, but the output vector wasn't big enough. */
        if (rc == 0)
        {
            rc = OVECCOUNT/3;
            printf("ovector only has room for %d captured substrings\n", rc - 1);
        }
        /* As before, show substrings stored in the output vector by number, and then
        also any named substrings. */
        for (i = 0; i < rc; i++)
        {
            char *substring_start = subject + ovector[2*i];
            int substring_length = ovector[2*i+1] - ovector[2*i];
            printf("%2d: %.*s\n", i, substring_length, substring_start);
        }
        if (namecount <= 0) printf("No named substrings\n");
        else
            {
            unsigned char *tabptr = name_table;
            printf("Named substrings\n");
            for (i = 0; i < namecount; i++)
            {
                int n = (tabptr[0] << 8) | tabptr[1];
                printf("(%d) %*s: %.*s\n", n, name_entry_size - 3, tabptr + 2,
                    ovector[2*n+1] - ovector[2*n], subject + ovector[2*n]);
                tabptr += name_entry_size;
            }
        }
    }      /* End of loop to find second and subsequent matches */
    printf("\n");
    return 0;
}
/* End of pcredemo.c */


strncat

Function: strcat

Synopsis
#include <string.h>
char *strcat(char * restrict s1,const char * restrict s2);

Description

The strcat function appends to the array of characters pointed by s1 characters from the array pointed to by s2. The initial character of s2 overwrites the null character at the end of s1. A terminating null character is always appended to the result. Thus, the maximum number of characters that can end up in the array pointed to by s1 is strlen(s1)+strlen(s2)+1. If copying takes place between objects that overlap, the behavior is undefined.

Returns

The strcat function returns the value of s1.

See also:


strncat

Function: strrepl

Synopsis
#include <string.h>
char *strrepl(char * InputString, char *StringToFind, char *Replacement, char *Output);

Description

The strrepl function replaces in InputString all occurrences of StringToFind by Replacement, writing the modified contents into the Output string. The original input string is not modified.

If the Output argument is NULL, strrepl will return the space that would be needed (including the terminating zero) for the replacement.

If Replacement is NULL and Output is not NULL, all occurrences of StringToFind will be erased.

Returns

The strrepl function returns the needed length for the replacements if its Output argument is NULL. If not, it returns the number of replacements done.

Example

#include <string.h>

#include <stdio.h>

int main(void)
{
    char *p = "This is a string with WORD in it, and then another WORD in it ";
    char a[512];

    strcpy(a,p);
    printf("%s\n",a);
    printf("needed length is %d\n",strrepl(a,"WORD","ANOTHER WORD",NULL));
    strrepl(a,"WORD","ANOTHER WORD",a);
    printf("(%d), %s\n",strlen(a),a);
    strrepl(a,"ANOTHER WORD ",NULL,a);
    printf("(%d), %s\n",strlen(a),a);

    return 0;
}

This will print:

This is a string with WORD in it, and then another WORD in it
needed length is 79
(78), This is a string with ANOTHER WORD in it, and then another ANOTHER WORD in it
(52), This is a string with in it, and then another in it


strstr

Function: strupr

Synopsis
#include <string.h>
char *strupr(const char *s1);

Description

The strupr function transforms in place the null terminated character string pointed to by s1 into uppercase characters

Returns

The strstr function returns a pointer to s1.

See also:

strnupr


system

Function: _cwait

Synopsis
#include <process.h>
int _cwait(int *termstat, int procHandle,int action);

Description

The _cwait function waits for the termination of the process ID of the specified process that is provided by procHandle. The value of procHandle passed to _cwait should be the value returned by the call to the _spawn function that created the specified process. If the process ID terminates before _cwait is called, _cwait returns immediately. _cwait can be used by any process to wait for any other known process for which a valid handle (procHandle) exists.

termstat points to a buffer where the return code of the specified process will be stored. The value of termstat indicates whether the specified process terminated normally by calling the Windows NT ExitProcess API. ExitProcess is called internally if the specified process calls exit or _exit, returns from main, or reaches the end of main. See GetExitCodeProcess for more
information regarding the value passed back through termstat. If _cwait is called with a NULL value for termstat, the return code of the specified process will not be stored.

The action parameter is ignored by Windows NT and Windows 95 because parent-child relationships are not implemented in these environments.

Returns

When the specified process has successfully completed, _cwait returns the handle of the specified process and sets termstat to the result code returned by the specified process. Otherwise, _cwait returns 1 and sets errno to:

ECHILD No specified process exists, procHandle is invalid, or the call to the GetExitCodeProcess or WaitForSingleObject API failed
EINVAL action is invalid


_rotl

Function: _rotl _lrotl

Synopsis:

#include <stdlib.h>
unsigned int _rotl(unsigned int value, int shift);
unsigned long _lrotl(unsigned long value, int shift);

Description

Rotates left the bits in the unsigned int value by the amount indicated by shift

Returns

Returns the rotated value


assert

Function: assert

Synopsis
#include <assert.h>
void assert(_Bool expression);

Description

The assert macro puts diagnostic tests into programs. When it is executed, if expression is false (that is, compares equal to 0), the assert macro writes information about the particular call that failed (including the text of the argument, the name of the source file, the source line number, and the name of the enclosing function the latter are respectively the values of the preprocessing macros __FILE__ and __LINE__ and of the identifier __func__) on the standard error file in an implementation-defined format. It then calls the abort function.

Returns

The assert macro returns no value.


GetExceptionCode

The GetExceptionCode function retrieves a code that identifies the type of exception that occurred. The function can be called only from within the filter expression or exception-handler block of an exception handler.

DWORD GetExceptionCode(void);

Return Values

The return value identifies the type of exception. The following table describes the exception codes that are likely to occur due to common programming errors.

Return Code | Description
EXCEPTION_ACCESS_VIOLATION | The thread attempted to read from or write to a virtual address for which it does not have the appropriate access.
EXCEPTION_BREAKPOINT | A breakpoint was encountered.
EXCEPTION_DATATYPE_MISALIGNMENT | The thread attempted to read or write data that is misaligned on hardware that does not provide alignment. For example, 16-bit values must be aligned on 2-byte boundaries, 32-bit values on 4-byte boundaries, and so on.
EXCEPTION_SINGLE_STEP | A trace trap or other single-instruction mechanism signaled that one instruction has been executed.
EXCEPTION_ARRAY_BOUNDS_EXCEEDED | The thread attempted to access an array element that is out of bounds, and the underlying hardware supports bounds checking.
EXCEPTION_FLT_DENORMAL_OPERAND | One of the operands in a floating-point operation is denormal. A denormal value is one that is too small to represent as a standard floating-point value.
EXCEPTION_FLT_DIVIDE_BY_ZERO | The thread attempted to divide a floating-point value by a floating-point divisor of zero.
EXCEPTION_FLT_INEXACT_RESULT | The result of a floating-point operation cannot be represented exactly as a decimal fraction.
EXCEPTION_FLT_INVALID_OPERATION | This exception represents any floating-point exception not included in this list.
EXCEPTION_FLT_OVERFLOW | The exponent of a floating-point operation is greater than the magnitude allowed by the corresponding type.
EXCEPTION_FLT_STACK_CHECK | The stack overflowed or underflowed as the result of a floating-point operation.
EXCEPTION_FLT_UNDERFLOW | The exponent of a floating-point operation is less than the magnitude allowed by the corresponding type.
EXCEPTION_INT_DIVIDE_BY_ZERO | The thread attempted to divide an integer value by an integer divisor of zero.
EXCEPTION_INT_OVERFLOW | The result of an integer operation caused a carry out of the most significant bit of the result.
EXCEPTION_PRIV_INSTRUCTION | The thread attempted to execute an instruction whose operation is not allowed in the current machine mode.
EXCEPTION_NONCONTINUABLE_EXCEPTION | The thread attempted to continue execution after a noncontinuable exception occurred.

Remarks

The exception code returned is the code generated by a hardware exception, or the code specified in the RaiseException function for a software-generated exception.

The run time ensures that the value returned by this function is correct only within the context of the filter expression of a __try/__except block. This function can be called elsewhere but other threads may modify the value returned.


GetExceptionInformation

The GetExceptionInformation function retrieves a machine-independent description of an exception, and information about the machine state that existed for the thread when the exception occurred. This function can be called only from within the filter expression of an exception handler.

LPEXCEPTION_POINTERS GetExceptionInformation(void);

Return Values

The return value is a pointer to an EXCEPTION_POINTERS structure that contains pointers to two other structures: an EXCEPTION_RECORD structure containing a description of the exception, and a CONTEXT structure containing the machine-state information.

Remarks

The filter expression (from which the function is called) is evaluated if an exception occurs during execution of the __try block, and it determines whether the __except block is executed.

EXCEPTION_POINTERS

The EXCEPTION_POINTERS structure contains an exception record with a machine-independent description of an exception and a context record with a machine-dependent description of the processor context at the time of the exception.

typedef struct _EXCEPTION_POINTERS {
  PEXCEPTION_RECORD ExceptionRecord;
  PCONTEXT ContextRecord;
} EXCEPTION_POINTERS, *PEXCEPTION_POINTERS;

Members

ExceptionRecord
Pointer to an EXCEPTION_RECORDstructure that contains a machine-independent description of the exception.
ContextRecord
Pointer to a CONTEXT structure that contains a processor-specific description of the state of the processor at the time of the exception.

EXCEPTION_RECORD

The EXCEPTION_RECORD structure describes an exception.

typedef struct _EXCEPTION_RECORD {
  DWORD ExceptionCode;
  DWORD ExceptionFlags;
  struct _EXCEPTION_RECORD* ExceptionRecord;
  PVOID ExceptionAddress;
  DWORD NumberOfParameters;
  ULONG_PTR ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];
} EXCEPTION_RECORD, *PEXCEPTION_RECORD;

Members

ExceptionCode
Reason the exception occurred. This is the code generated by a hardware exception, or the code specified in the RaiseException function for a software-generated exception. The following tables describes the exception codes that are likely to occur due to common programming errors.
Value | Meaning
EXCEPTION_ACCESS_VIOLATION | The thread tried to read from or write to a virtual address for which it does not have the appropriate access.
EXCEPTION_ARRAY_BOUNDS_EXCEEDED | The thread tried to access an array element that is out of bounds and the underlying hardware supports bounds checking.
EXCEPTION_BREAKPOINT | A breakpoint was encountered.
EXCEPTION_DATATYPE_MISALIGNMENT | The thread tried to read or write data that is misaligned on hardware that does not provide alignment. For example, 16-bit values must be aligned on 2-byte boundaries; 32-bit values on 4-byte boundaries, and so on.
EXCEPTION_FLT_DENORMAL_OPERAND | One of the operands in a floating-point operation is denormal. A denormal value is one that is too small to represent as a standard floating-point value.
EXCEPTION_FLT_DIVIDE_BY_ZERO | The thread tried to divide a floating-point value by a floating-point divisor of zero.
EXCEPTION_FLT_INEXACT_RESULT | The result of a floating-point operation cannot be represented exactly as a decimal fraction.
EXCEPTION_FLT_INVALID_OPERATION | This exception represents any floating-point exception not included in this list.
EXCEPTION_FLT_OVERFLOW | The exponent of a floating-point operation is greater than the magnitude allowed by the corresponding type.
EXCEPTION_FLT_STACK_CHECK | The stack overflowed or underflowed as the result of a floating-point operation.
EXCEPTION_FLT_UNDERFLOW | The exponent of a floating-point operation is less than the magnitude allowed by the corresponding type.
EXCEPTION_ILLEGAL_INSTRUCTION | The thread tried to execute an invalid instruction.
EXCEPTION_IN_PAGE_ERROR | The thread tried to access a page that was not present, and the system was unable to load the page. For example, this exception might occur if a network connection is lost while running a program over the network.
EXCEPTION_INT_DIVIDE_BY_ZERO | The thread tried to divide an integer value by an integer divisor of zero.
EXCEPTION_INT_OVERFLOW | The result of an integer operation caused a carry out of the most significant bit of the result.
EXCEPTION_INVALID_DISPOSITION | An exception handler returned an invalid disposition to the exception dispatcher. Programmers using a high-level language such as C should never encounter this exception.
EXCEPTION_NONCONTINUABLE_EXCEPTION | The thread tried to continue execution after a noncontinuable exception occurred.
EXCEPTION_PRIV_INSTRUCTION | The thread tried to execute an instruction whose operation is not allowed in the current machine mode.
EXCEPTION_SINGLE_STEP | A trace trap or other single-instruction mechanism signaled that one instruction has been executed.
EXCEPTION_STACK_OVERFLOW | The thread used up its stack.

ExceptionFlags
Exception flags. This member can be either zero, indicating a continuable exception, or EXCEPTION_NONCONTINUABLE indicating a noncontinuable exception. Any attempt to continue execution after a noncontinuable exception causes the EXCEPTION_NONCONTINUABLE_EXCEPTION exception.
ExceptionRecord
Pointer to an associated EXCEPTION_RECORD structure. Exception records can be chained together to provide additional information when nested exceptions occur.
ExceptionAddress
Address where the exception occurred.
NumberParameters
Number of parameters associated with the exception. This is the number of defined elements in the ExceptionInformation array.
ExceptionInformation
Array of additional arguments that describe the exception. The RaiseException function can specify this array of arguments. For most exception codes, the array elements are undefined. The following table describes the exception codes whose array elements are defined.
Exception code Meaning
EXCEPTION_ACCESS_VIOLATION The first element of the array contains a read-write flag that indicates the type of operation that caused the access violation. If this value is zero, the thread attempted to read the inaccessible data. If this value is 1, the thread attempted to write to an inaccessible address.

The second array element specifies the virtual address of the inaccessible data.


signal

Function: psignal

Synopsis
#include <signal.h>
void psignal(int sig, char *errormsg);

Description

The psignal function will print a message in stderr consisting of the string errormsg, a colon, a space, and a string describing the signal number indicated by its parameter sig. If sig is invalid the message displayed will indicate an unknown signal.

If the string errormsg is NULL, it will be replaced by the empty string.


RaiseException

The RaiseException function raises an exception in the calling thread.

void RaiseException(DWORD dwExceptionCode,
  DWORD dwExceptionFlags,
  DWORD nNumberOfArguments,
  const ULONG_PTR* lpArguments);

Parameters

dwExceptionCode
[in] Application-defined exception code of the exception being raised. The filter expression and exception-handler block of an exception handler can use the GetExceptionCode function to retrieve this value.

Note that the system will clear bit 28 of dwExceptionCode before displaying a message This bit is a reserved exception bit, used by the system for its own purposes.

dwExceptionFlags
[in] Exception flags. This can be either zero to indicate a continuable exception, or EXCEPTION_NONCONTINUABLE to indicate a noncontinuable exception. Any attempt to continue execution after a noncontinuable exception causes the EXCEPTION_NONCONTINUABLE_EXCEPTION exception.
nNumberOfArguments
[in] Number of arguments in the lpArguments array. This value must not exceed EXCEPTION_MAXIMUM_PARAMETERS. This parameter is ignored if lpArguments is NULL.
lpArguments
[in] Pointer to an array of arguments. This parameter can be NULL. These arguments can contain any application-defined data that needs to be passed to the filter expression of the exception handler.

Return Values

This function does not return a value.

Remarks

The RaiseException function enables a process to use structured exception handling to handle private, software-generated, application-defined exceptions.

Raising an exception causes the exception dispatcher to go through the following search for an exception handler:

  1. The system first attempts to notify the process's debugger, if any.
  2. If the process is not being debugged, or if the associated debugger does not handle the exception, the system attempts to locate a frame-based exception handler by searching the stack frames of the thread in which the exception occurred. The system searches the current stack frame first, then proceeds backward through preceding stack frames.
  3. If no frame-based handler can be found, or no frame-based handler handles the exception, the system makes a second attempt to notify the process's debugger.
  4. If the process is not being debugged, or if the associated debugger does not handle the exception, the system provides default handling based on the exception type. For most exceptions, the default action is to call the ExitProcess function.

The values specified in the dwExceptionCode, dwExceptionFlags, nNumberOfArguments, and lpArguments parameters can be retrieved in the filter expression of a frame-based exception handler by calling the GetExceptionInformation function.


difftime

Function: difftime64

Synopsis
#include <time64.h>
long double difftime64(time64_t time1, time64_t time0);

Description

The difftime64 function computes the difference between two calendar times: time1-time0.

Returns

The difftime64 function returns the difference expressed in seconds as a long double.


gmtime

Function: _getsystime _setsystime

Synopsis
#include <time.h>
unsigned _getsystime(struct tm *);
unsigend _setsystime(struct tm *timer,unsigned milliseconds);

Description

This functions query or set the system time. The _getsystime function converts the time returned by the windows OS into a structure tm, and _setsystime converts a structure tm into the windows internal format and sets the time.

Returns

The _getsystime returns the milliseconds member of the windows private structure. The _setsystime function returns zero to signal that the time was changed, or an error return code, retrieved using GetLastError().


localtime

Function: localtime64

Synopsis
#include <time64.h>
struct tm *localtime64(const time64_t *timer);

Description

The localtime64 function converts the calendar time pointed to by timer into a broken-down time, expressed as local time.

Returns

The localtime64 function returns a pointer to the broken-down time, or a null pointer if the specified time cannot be converted to local time.


mktime

Function: struct_tm

Synopsis

#include <time.h>
struct tm {
    int tm_sec;   /* seconds after the minute - [0,59] */
    int tm_min;   /* minutes after the hour - [0,59] */
    int tm_hour;  /* hours since midnight - [0,23] */
    int tm_mday;  /* day of the month - [1,31] */
    int tm_mon;   /* months since January - [0,11] */
    int tm_year;  /* years since 1900 */
    int tm_wday;  /* days since Sunday - [0,6] */
    int tm_yday;  /* days since January 1 - [0,365] */
    int tm_isdst; /* daylight savings time flag */
};

Fields:

tm_sec The number of seconds after the minute, normally in the range 0 to 59, but can be up to 61 to allow for leap seconds.
tm_min The number of minutes after the hour, in the range 0 to 59.
tm_hour The number of hours past midnight, in the range 0 to 23.
tm_mday The day of the month, in the range 1 to 31.
tm_mon The number of months since January, in the range 0 to 11.
tm_year The number of years since 1900.
tm_wday The number of days since Sunday, in the range 0 to 6.
tm_yday The number of days since January 1, in the range 0 to 365.
tm_isdst A flag that indicates whether daylight saving time is in effect at the time described. The value is positive if daylight saving time is in effect, zero if it is not, and negative if the information is
not available.


time

Function: time64

Synopsis
#include <time64.h>
time64_t time64(time64_t *timer);

Description

The time function determines the current calendar time.

Under the lcc-win32/windows system, The time64 function returns the number of seconds elapsed since midnight (00:00:00), January 1, 1970, coordinated universal time, according to the system clock. The return value is stored in the location given by timer. This parameter may be NULL, in which case the return value is not stored.

Returns

The time64 function returns the implementations best approximation to the current calendar time. The value (time64_t)-1 is returned if the calendar time is not available. If timer is not a null pointer, the return value is also assigned to the object it points to.


ispunct

Function: compress

Synopsis
#include <zlib.h>
int compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);

Description

Compresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least 0.1% larger than sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the compressed buffer

This function can be used to compress a whole file at once if the input file is mapped into memory with MapViewOfFile.
.

Returns

compress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer.


ispunct

Function: compress2

Synopsis
#include <zlib.h>
int compress2 (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level);

Description

Compresses the source buffer into the destination buffer. The level parameter has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least 0.1% larger than sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.

Returns

compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid.


ispunct

Function: deflate

Synopsis
#include <zlib.h>
int deflate(z_streamp strm,int flush);

Description

deflate compresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush.
The detailed semantics are as follows. deflate performs one or both of the following actions:

  • Compress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in and avail_in are updated and processing will resume at this point for the next call of deflate().
  • Provide more output starting at next_out and update next_out and avail_out accordingly. This action is forced if the parameter flush is non zero. Forcing flush frequently degrades the compression ratio, so this parameter should be set only when necessary (in interactive applications). Some output may be provided even if flush is not set.

Before the call of deflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating avail_in or avail_out accordingly ; avail_out should never be zero before the call. The application can consume the compressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending.

If the parameter flush is set to Z_SYNC_FLUSH, all pending output is flushed to the output buffer and the output is aligned on a byte boundary, so that the decompressor can get all input data available so far. (In particular avail_in is zero after the call if enough output space has been provided before the call.) Flushing may degrade compression for some compression algorithms and so it should be used only when necessary.

.If flush is set to Z_FULL_FLUSH, all output is flushed as with Z_SYNC_FLUSH, and the compression state is reset so that decompression can restart from this point if previous compressed data has been damaged or if random access is desired. Using Z_FULL_FLUSH too often can seriously degrade the compression.

If deflate returns with avail_out == 0, this function must be called again with the same value of the flush parameter and more output space (updated avail_out), until the flush is complete (deflate returns with non-zero avail_out).

If the parameter flush is set to Z_FINISH, pending input is processed, pending output is flushed and deflate returns with Z_STREAM_END if there was enough output space ; if deflate returns with Z_OK, this function must be called again with Z_FINISH and more output space (updated avail_out) but no more input data, until it returns with Z_STREAM_END or an error. After deflate has returned Z_STREAM_END, the only possible operations on the stream are deflateReset or deflateEnd.

Z_FINISH can be used immediately after deflateInit if all the compression is to be done in a single step. In this case, avail_out must be at least 0.1% larger than avail_in plus 12 bytes. If deflate does not return Z_STREAM_END, then it must be called again as described above.

deflate() sets strm-> adler to the adler32 checksum of all input read so far (that is, total_in bytes).

deflate() may update data_type if it can make a good guess about the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered binary. This field is only for information purposes and does not affect the compression algorithm in any manner.

Returns

deflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if all input has been consumed and all output has been produced (only when flush is set to Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible (for example avail_in or avail_out was zero).


ispunct

Function: deflateEnd

Synopsis
#include <zlib.h>
int deflateEnd(z_streamp strm);

Description

All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output.

Returns

deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent, Z_DATA_ERROR if the stream was freed prematurely (some input or output was discarded). In the error case, msg may be set but then points to a static string (which must not be deallocated).


ispunct

Function: deflateInit

Synopsis
#include <zlib.h>
int deflateInit(z_streamp strm,int level);

Description

Initializes the internal stream state for compression. The fields zalloc, zfree and opaque must be initialized before by the caller. If zalloc and zfree are set to Z_NULL, deflateInit updates them to use default allocation functions.

The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time).

Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6).

Returns

Returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if level is not a valid compression level, Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (ZLIB_VERSION). msg is set to null if there is no error message. deflateInit does not perform any compression: this will be done by deflate().


ispunct

Function: gzclose

Synopsis
#include <zlib.h>
int gzclose (gzFile file);

Description

Flushes all pending output if necessary, closes the compressed file and deallocates all the (de)compression state.

Returns

The return value is the zlib error number (see function gzerror).


ispunct

Function: gzdopen

Synopsis
#include <zlib.h>
gzFile gzdopen (int fd, const char *mode);

Description

gzdopen() associates a gzFile with the file descriptor fd. File descriptors are obtained from calls like open, dup, creat, pipe or fileno (in the file has been previously opened with fopen). The mode parameter is as in gzopen.

The next call of gzclose on the returned gzFile will also close the file descriptor fd, just like fclose(fdopen(fd), mode) closes the file descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).

Returns

gzdopen returns NULL if there was insufficient memory to allocate the (de)compression state.


ispunct

Function: gzeof

Synopsis
#include <zlib.h>
int gzeof (gzFile file);

Description

Returns

Returns 1 when EOF has previously been detected reading the given input stream, otherwise zero.


ispunct

Function: gzerror

Synopsis
#include <zlib.h>
const char * gzerror (gzFile file, int *errnum);

Description

Returns the error message for the last error which occurred on the given compressed file. errnum is set to zlib error number. If an error occurred in the file system and not in the compression library, errnum is set to Z_ERRNO and the application may consult errno to get the exact error code.

Returns

The current error value.


ispunct

Function: gzflush

Synopsis
#include <zlib.h>
int gzflush (gzFile file, int flush);

Description

Flushes all pending output into the compressed file. The parameter flush is as in the deflate() function.
gzflush should be called only when strictly necessary because it can degrade compression.

Returns

The return value is the zlib error number (see function gzerror). gzflush returns Z_OK if the flush parameter is Z_FINISH and all output is flushed.


ispunct

Function: gzgetc

Synopsis
#include <zlib.h>
int gzgetc (gzFile file);

Description

Reads one byte from the compressed file.

Returns

gzgetc returns this byte or -1 in case of end of file or error.


ispunct

Function: gzgets

Synopsis
#include <zlib.h>
char * gzgets (gzFile file, char *buf, int len);

Description

Reads bytes from the compressed file until len-1 characters are read, or a newline character is read and transferred to buf, or an end-of-file condition is encountered. The string is then terminated with a null character.

Returns

gzgets returns buf, or Z_NULL in case of error.


ispunct

Function: gzopen

Synopsis
#include <zlib.h>
gzFile gzopen (const char *path, const char *mode);

Description

Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman only compression as in "wb1h". (See the description of deflateInit2 for more information about the strategy parameter.)
gzopen can be used to read a file which is not in gzip format ; in this case gzread will directly read from the file without decompression.

Returns

gzopen returns NULL if the file could not be opened or if there was insufficient memory to allocate the (de)compression state ; errno can be checked to distinguish the two cases (if errno is zero, the zlib error is Z_MEM_ERROR).


ispunct

Function: gzprintf

Synopsis
#include <zlib.h>
int VA gzprintf (gzFile file, const char *format, ...);

Description

Converts, formats, and writes the args to the compressed file under control of the format string, as in fprintf.

Returns

gzprintf returns the number of uncompressed bytes actually written (0 in case of error).


ispunct

Function: gzputc

Synopsis
#include <zlib.h>
int gzputc (gzFile file, int c);

Description

Writes c, converted to an unsigned char, into the compressed file.

Returns

gzputc returns the value that was written, or -1 in case of error.


ispunct

Function: gzputs

Synopsis
#include <zlib.h>
int gzputs (gzFile file, const char *s);

Description

Writes the given null-terminated string to the compressed file, excluding the terminating null character.

Returns

gzputs returns the number of characters written, or -1 in case of error.


ispunct

Function: gzread

Synopsis
#include <zlib.h>
int gzread (gzFile file, voidp buf, unsigned len);

Description

Reads the given number of uncompressed bytes from the compressed file. If the input file was not in gzip format, gzread copies the given number of bytes into the buffer.

Returns

gzread returns the number of uncompressed bytes actually read (0 for end of file, -1 for error).


ispunct

Function: gzrewind

Synopsis
#include <zlib.h>
int gzrewind (gzFile file);

Description

Rewinds the given file. This function is supported only for reading.

Returns


ispunct

Function: gzseek

Synopsis
#include <zlib.h>
z_off_t gzseek (gzFile file, z_off_t offset, int whence);

Description

Sets the starting position for the next gzread or gzwrite on the given compressed file. The offset represents a number of bytes in the uncompressed data stream. The whence parameter is defined as in lseek(2); the value SEEK_END is not supported.
If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported ; gzseek then compresses a sequence of zeroes up to the new starting position.

Returns

gzseek returns the resulting offset location as measured in bytes from the beginning of the uncompressed stream, or -1 in case of error, in particular if the file is opened for writing and the new starting position would be before the current position.


ispunct

Function: gzsetparams

Synopsis
#include <zlib.h>
int gzsetparams (gzFile file, int level, int strategy);

Description

Dynamically update the compression level or strategy. See the description of deflateInit2 for the meaning of these parameters.

Returns

gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not opened for writing.


ispunct

Function: gztell

Synopsis
#include <zlib.h>
z_off_t gztell (gzFile file);

Description

Returns the starting position for the next gzread or gzwrite on the given compressed file. This position represents a number of bytes in the uncompressed data stream.

Returns

Returns the starting position.


ispunct

Function: gzwrite

Synopsis
#include <zlib.h>
int gzwrite (gzFile file, const voidp buf, unsigned len);

Description

Writes the given number of uncompressed bytes into the compressed file. gzwrite returns the number of uncompressed bytes actually written (0 in case of error).

Returns

gzwrite returns the number of uncompressed bytes actually written (0 in case of error).


ispunct

Function: inflate

Synopsis
#include <zlib.h>
int inflate(z_streamp strm,int flush);

Description

inflate decompresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may some introduce some output latency (reading input without producing any output) except when forced to flush.
The detailed semantics are as follows. inflate performs one or both of the following actions:

  • Decompress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in is updated and processing will resume at this point for the next call of inflate().
  • Provide more output starting at next_out and update next_out and avail_out accordingly. inflate() provides as much output as possible, until there is no more input data or no more space in the output buffer (see below about the flush parameter).

Before the call of inflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating the next_* and avail_* values accordingly. The application can consume the uncompressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of inflate(). If inflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending.
If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much output as possible to the output buffer. The flushing behavior of inflate is not specified for values of the flush parameter other than Z_SYNC_FLUSH and Z_FINISH, but the current implementation actually flushes as much output as possible anyway.
inflate() should normally be called until it returns Z_STREAM_END or an error. However if all decompression is to be performed in a single step (a single call of inflate), the parameter flush should be set to Z_FINISH. In this case all pending input is processed and all pending output is flushed ; avail_out must be large enough to hold all the uncompressed data. (The size of the uncompressed data may have been saved by the compressor for this purpose.) The next operation on this stream must be inflateEnd to deallocate the decompression state. The use of Z_FINISH is never required, but can be used to inform inflate that a faster routine may be used for the single inflate() call.
If a preset dictionary is needed at this point (see inflateSetDictionary below), inflate sets strm-adler to the adler32 checksum of the dictionary chosen by the compressor and returns Z_NEED_DICT ; otherwise it sets strm-> adler to the adler32 checksum of all output produced so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described below. At the end of the stream, inflate() checks that its computed adler32 checksum is equal to that saved by the compressor and returns Z_STREAM_END only if the checksum is correct.

Returns

inflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if the end of the compressed data has been reached and all uncompressed output has been produced, Z_NEED_DICT if a preset dictionary is needed at this point, Z_DATA_ERROR if the input data was corrupted (input stream not conforming to the zlib format or incorrect adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if no progress is possible or if there was not enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR case, the application may then call inflateSync to look for a good compression block.


ispunct

Function: inflateEnd

Synopsis
#include <zlib.h>
int inflate(z_streamp strm);

Description

All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output.

Returns

inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent. In the error case, msg may be set but then points to a static string (which must not be deallocated).


ispunct

Function: inflateInit

Synopsis
#include <zlib.h>
int inflateInit(z_streamp strm);

Description

Initializes the internal stream state for decompression. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. If next_in is not Z_NULL and avail_in is large enough (the exact value depends on the compression method), inflateInit determines the compression method from the zlib header and allocates all data structures accordingly ; otherwise the allocation will be deferred to the first call of inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to use default allocation functions.

Returns

inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller. msg is set to null if there is no error message. inflateInit does not perform any decompression apart from reading the zlib header if present: this will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unchanged.)


ispunct

Function: uncompress

Synopsis
#include <zlib.h>
int uncompress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);

Description

Decompresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the compressed buffer.

Returns

uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted.