and C_functions.s5 from http://3lib.ukonline.co.uk/pocketinfo/index.html by Bob Hepple bhepple@freeshell.org Nov 2002
- subtraction, unary minus + addition * multiplication / division % modulus division (returns remainder of integer division) -- decrement ++ increment
Arrays of any datatype may be declared, with multiple dimensions. The general form of a single dimension array is: type varname[size]; Where size specifies the number of elements in the array varname of objects of type type. The elements of the array are numbered from 0 to size-1. Elements are accessed using the element number is square brackets, e.g. the following code sets the ninth element of array a to 1: a[8] = 1; Multidimensional arrays are created by specifying additional dimensions in additional square brackets, e.g. to declare a 7 by 10 integer array: int a[7][10]; Remember that no bounds checking is done, and reads or writes out of bounds are likely to cause memory violations or corruption.
The normal assignment operator is the equals sign (=). Shorthand can be used to apply an operation to a variable, and leave the result in that variable, for the general form: a = a op ... a op= ... For example: x += 5 is x = x + 5 x /= a+1 is x = x / (a+1)
& and | or ^ xor ~ complement >> right shift (sign bit extended) << left shift (sign bit overwritten)
Evaluates several steps, and returns the result of the last, e.g. a = 20; b = (a=a+5, a/5); After this, a = 25 (20 + 5), and b = 5 (25 / 5). This is most often used in for statements.
Constants can be specified for any of the basic datatypes as in the following examples: int 1, 342, 25000, -3186 long int 40000L, 212326L, -37642L short int 5, 54, -63 unsigned int 10000U, 428U, 40000 float 1.24F, 3.24e6F, -45.98F double 1.427, 1246.792, -0.063, 3.23e8 long double 138.538L, -63.3561L char 'A', 'b', '='
Octal constants are specified by giving them a leading zero, for example: 012 ten 043 thirty-five Hexadecimal constants have a leading 0x, for example: 0xA ten 0x23 thirty-five
The & operator returns the address of a variable, e.g. a = &var The * operator sets the variable at the specified address, e.g. *a = 1. This uses the type of the pointer to determine how to set the variable. Pointers can have integer values added and subtracted; the specified value is multiplied by the size of the type to determine the actual change in the pointer. For example, incrementing a pointer to double adds 8 bytes.
== equal != not equal > greater than >= greater than or equal < less than <= less than or equal && and || or ! not
Special backslash constructs can be used in character and string constants to represent characters which cannot be entered from the keyboard: \a alert \b backspace \f form feed \n newline \r carriage return \t horizontal tab \v vertical tab \" double quote \' single quote \0 null \\ backslash \0n Octal constant \xn Hexadecimal constant
Strings are not an explicit builtin datatype in C, but are supported in the libraries as zero terminated arrays of characters. String constants can be specified using double quotes, so the string hello world can be specified as "hello world", which will be compiled as an array of 12 characters the last one being a zero byte.
The . (dot) operator accesses structure/union members from the actual structure, e.g. person.age = 21; The -> (arrow) operator accesses structure/union members from a pointer to the structure, e.g. perptr->age = 21;
Replaces if statements of the general form: if exp1 then x=exp2 else x=exp3; with the form: x = exp1 ? exp2 : exp3;
Turns the argument it precedes into a quoted string, used in macro definitions. #define mkstr(s) # s mkstr(hello) = "hello"
Concatenates two tokens, used in macro definitions. #define concat(a,b) a ## b concat(x,y) = xy
Performs macro substitutions of one piece of text for another. #define name replacement The replacement sequence is terminated only by th end of the line; note especially that a semicolon does not terminate the sequence. Definition of macros can also be done as options to the compiler. The macro can also have arguments, for example: #define MAX(a,b) ((a)>(b) ? (a) : (b))
Stops compilation and displays the line number and specified error message. #error Shouldn't have reached here!
Conditionally compiles a section of code. #if constant-expression code... #elif constant-expression other code... #else more code... #endif The constant expression typically contains macros passed as options to the compiler, e.g. #if DBGLVL==1 debugging code... #elif DBGLVL=2 more debugging code... #endif
Work as for #if but are true if a macro is defined or not defined respectively.
Reads source from another file. #include "filename" #include <filename> Typically, double quotes causes the file to be searched for in the current directory and a user defined path, while angle brackets looks in a system defined path.
Changes the contents of __LINE__ and __FILE__. #line number "filename" Used for debugging and special purposes, or generated by pre-processing steps to retain original line numbers. Filename is optional.
Implementation defined directive, dependent on the compiler being used.
Removes a previously defined definition.
Declares local variables; entirely optional, hence seldom used.
Exits from a do, for, or while loop without evaluating the loop condition. Also used to exit from a switch statement. Always terminates the innermost loop, regardless of the nesting. /* print a list up to a zero value */ for (i=0; i<20; i++) { if (a[i] == 0) break; printf("Value %d=%d", i, a[i])l }
See switch
Data type, used to declare character variables.
Data type modifier; the variable that follows may not be modified, but may be given an initial value when declared. Used in function prototypes to indicate that a parameter will not be changed.
Bypasses remaining code in a loop and forces the conditional test to be evaluated. /* print a list skipping zero values */ for (i=0; i<20; i++) { if (a[i] == 0) break; printf("Value %d=%d", i, a[i])l }
Used in a switch statement to indicate the default block of code if no matches are found.
Indicates the start of a do { ... } while loop. Will always have at least one iteration, because the condition is tested at the end of the loop. /* read from a file until EOF */ do { c = getc(fp); save(c); } whie (!feof(fp));
Data type, used to declare double-precision floating-point variables.
See if.
Type specifier used to create enumeration types, which are simply lists of named integer constants. The first normally has value 0, and each value is one more than the preceding. Values can be specified. enum day {mon,tue,wed, thu,fri,sat,sun}; enum day today; if (today==Mon) { /* the start of the week */ } enum color (red=1,green,blue,white=7,black); /* red=1, green=2, blue=3, white=7, black=8 */
Data type modifier used to indicate variables declared elsewhere; often used for global variables defined in another module and available at link time.
Data type, used to declare floating-point variables.
Loop allowing automatic initialisation and incrementing of a counter. for (i=0; i<10; i++) { printf("%d\n", i); } Each of the three parts of the for statement can be a number of statements separated by commas. for (i=0, j=10; i<10; i++, j--) { a[i] = b[j] }
Jumps to the specified label. Can only be used within the current function. goto label; ... ... ... label:
Conditionally executes a block of code. if (a==1) { printf("a equals one\n"); } else { printf("a doesn't equal one\n"); }
Data type, used to declare integer variables.
Data type, used to declare double length integer variables.
Storage class modifier used to advise the compiler to store the variable in a CPU register or other fast memory.
Returns from a function, with a value if the function is not void. void hello() { printf("Hello\n"); return; } int max(a, b) { return (a>b) ? a : b; }
Data type modifier used to declare short integers.
Data type modifier used to declare and signed char variable.
Compile time operator which returns the length of the variable or type. struct info myinfo; memset(&myinfo, 0, sizeof(info));
Data type modifier indicating the variable should retain its value between function calls.
Defines a structure, a named group of variables. General form is: struct tag { type var1; type var2; ... } var-list; The tag is the type name of the structure; individual elements are accessed using the dot when operating on a structure, or the arrow when operating through a pointer. struct person { char name[50]; int age; char sex; } mum, dad; strcpy(mum.name, "Julia"); mum.age = 50; mum.sex = 'F'; ...
Routes execution depending on an integer or character value, with the option for a default behaviour. General form: switch (var) { case const1: statements 1; break; case const2: statements 2; break; ... case constn: statements n; break; default: default statements; }
Creates a new name for an existing datatype. Often used to create structure or union datatypes. typedef int age; typedef struct person_tag { char name[80]; int age; } person;
Similar to a struct, but the variables use the same memory location. e.g. the following union: union tag { char c1[10]; char c2[6]; } a_union; uses ten bytes of memory: ********** | c1 | | c2 |
Data type modifier which removes the sign bit of an integer. This doubles the maximum positive number which can be held, but prevents negative numbers.
Used to declare functions which return no meaningful value, and void pointers which can point to any type of object.
Data type modifier indicating that the variable may be altered by processes outwith the program. For example, hardware clocks.
Loop where the condition is tested at the start. /* copy memory up to not including a zero */ while (*p!=0) { *p2=*p; p++; p2++; }
Predefined macro - compilation date.
Predefined macro - current source filename.
Predefined macro - line number in current source file.
Predefined macro - set to 1 if this is a standard C implementation.
Predefined macro - compilation time.
#include stdlib.h void abort(void); Causes immediate abnormal termination of the program; does not return. Typically closes but does not flush all open files and other connections.
#include stdlib.h int abs(int num); Returns the absolute (positive) value of num.
#include math.h double acos(double arg); Returns, in radians, the arc cosine of arg, which must be in the range -1 to 1.
#include time.h char * asctime(struct tm *ptr); Returns a pointer to a string representation of the information in the structure pointed to by ptr, in the form: day month date hours:minutes:seconds year\n\0 For example: Thu Oct 28 14:55:20 1999 Note that the buffer used is overwritten by subsequent calls to the function.
#include math.h double asin(double arg); Returns, in radians, the arc sine of arg, which must be in the range -1 to 1.
#include assert.h void assert(int exp); Writes a message to stderr and aborts execution if the expression exp is zero. Output is implementation dependent, but typically looks like this: Assertion failed: expression, file file, line line
#include math.h double atan(double arg); Returns, in radians, the arc tangent of arg.
#include math.h double atan2(double y, double x); Returns, in radians, the arc tangent of y/x, using the signs of the arguments to determine the correct quadrant.
#include stdlib.h int atexit(void (*func)(void)); Registers the function func to be called on normal program termination. At least 32 termination functios may be registered, and they will be called in reverse order of their registering. Returns zero on successful registration, non-zero otherwise.
#include stdlib.h double atof(const char *str); Converts the string pointed to by str into a double. If the string does not contain a valid floating point number, the result is undefined. The number can be terminated by any and character that is not part of a valid floating point number.
#include stdlib.h int atoi(const char *str); Converts the string pointed to by str into an int. If the string does not contain a valid integer number, the result is undefined. The number can be terminated by any and character that is not part of a valid integer number.
#include stdlib.h long atol(const char *str); Converts the string pointed to by str into a long. If the string does not contain a valid integer number, the result is undefined. The number can be terminated by any and character that is not part of a valid integer number.
#include stdlib.h void * bsearch(const void *key, const void *buf, size_t num, size_t size, int (*compare)(const void *, const void *)); Performs a binary search on the sorted array buf and returns a pointer to the first member that matches key, or null if no match is found. The number of elements in the array is specified by num, and the size of each element in bytes is specified by size. The array must be sorted in ascending order. The function compare is used to compare an element of the array with the key, in the following form: int function(const void *arg1, const void *arg2) returning: arg1 < arg2 less than 0 arg1 = arg2 0 arg1 > arg2 greater than 0
#include stdlib.h void * calloc(size_t num, size_t size); Allocates num * size bytes of memory from the heap. Returns a pointer to the allocated memory, or null if allocation fails.
#include math.h double ceil(double num); Returns the smallest integer not less than num.
#include stdio.h void clearerr(FILE *stream); Resets the error flag and end of file flag for the stream pointed to by stream.
#include time.h clock_t clock(void); Returns the amount of time the calling process has been running, in clock ticks. To convert to seconds, divide the result by CLK_TCK. -1 is returned if the time is not available.
#include math.h double cos(double arg); Returns the cosine of arg, where arg is in radians.
#include math.h double cosh(double arg); Returns the hyperbolic cosine of arg, where arg is in radians.
#include time.h char * ctime(const time_t *time); Returns a pointer to a string representation of the calendar time in time, in the form: day month date hours:minutes:seconds year\n\0 For example: Thu Oct 28 14:55:20 1999 Note that the buffer used is overwritten by subsequent calls to the function.
#include time.h double difftime(time_t time2, time_t time1); Returns the difference, in seconds, between time1 and time2. i.e. it returns time2 - time1
#include stdlib.h div_t div(int numerator, int denominator); Returns the quotient and remainder of numerator/denominator in a div_t structure. The div_t structure is defined in stdlib.h and will have at least two integer fields quot and rem.
#include stdlib.h void exit(int exit_code); Causes immediate normal termination of the program, returning exit_code to the calling process.
#include math.h double exp(double arg); Returns the natural logarithm e raised to the arg power.
#include math.h double fabs(double num); Returns the absolute (positive) value of num.
#include stdio.h int fclose(FILE *stream); Closes the file associated with stream and flushes its buffer. After closing the file, stream will no longer be connected with the file. Returns zero on success, or non-zero on failure. Errors can be caused by trying to close already closed files, removing storage media, or lack of disk space.
#include stdio.h int feof(FILE *stream); Checks the position of the file associated with stream to determine if the eof of the file has been reached. Returns non-zero if the position is at end of file.
#include stdio.h int ferror(FILE *stream); Returns the error status for the given stream. Zero indicates no error, otherwise a non-zero error code will be returned.
#include stdio.h int fflush(FILE *stream); Explicitely flushes the buffer associated with stream, causing output buffers to be physically written and input buffers to be cleared. Returns zero on success, non-zero on error. Note that all buffers are automatically flushed on normal program termination, when they are full, or when the file is closed.
#include stdio.h int fgetc(FILE *stream); Returnns the next character from the input stream. On error, or if the end of the file is reached, returns EOF. Note that EOF is a valid character, so feof() or ferror() should be used to check for end-of-file or error conditions.
#include stdio.h int fgetpos(FILE *stream, fpos_t *position); Returns the current file position indicator for stream in the object pointed to by position. The value stored is useful only for restoring the file position with a call to fsetpos(). Returns zero on success, non-zero on error.
#include stdio.h char * fgets(char *str, int num, FILE *stream); Reads up to num-1 characters from stream and puts them in the character array pointed to by str. Characters are read up to a newline character, or end of file. The string will be terminated by a null character, and any newline character will be retained. Returns str on success, or a null pointer on error. Use ferror() and feof() to determine status on error.
#include math.h double floor(double num); Returns the largest integer not greater than num.
#include math.h double fmod(double x, double y); Returns the remainder of x/y.
#include stdio.h FILE * fopen(const char *filename, const char *mode); Opens the file represented by filename for access as specified by mode. Valid values for mode are as follows: "r" open text file for reading "w" create text file for writing "a" append to text file "rb" open binary file for reading "wb" create binary file for writing "ab" append to binary file "r+" open text file for read/write "w+" create text file for read/write "a+" open text file for read/write "rb+" open binary file for read/write "wb+" create binary file for read/write "ab+" open binary file for read/write Returns a FILE pointer on success, or null on failure. If a file is opened in text mode, some character conversions may occur. For example, newline characters may be converted to carriage return/linefeed. This is system dependent. Opening a file for writing will cause a new file to be created; any pre-existing file will be erased first. Opening a file for reading or appending requires it to exist. If opened for appending, the file position will be set to the end of file.
#include stdio.h int fprintf(FILE *stream, const char *format, ...); Prints to stream as specified by string format, using additional parameters as required. Returns the number of characters printed, or a negative value on error. The string format is a combination of characters which will be printed directly, and format commands beginning % which will be replaced by arguments. There must be the same number and type of arguments as there format commands, in the same order. Format commands are: %c character %d signed decimal integer %i signed decimal integer %e scientific notation floating point %E scientific notation floating point %f decimal floating point %g uses %e or %f, whichever is shorted %G uses %E or %f, whichever is shorted %o unsigned octal %s string %u unsigned decimal integer %x unsigned hexadecimal %X unsigned hexadecimal %p pointer %% percent sign Format commands may have modifiers to specify field width, number of decimal places, and justification. The general form is: %<width>.<places><format> Where width specifies the minimum width in characters and places specifies the number of decimal places. For strings and integers, places specifies the maximum width after which output will be truncated. Preceding width with a zero will cause output to be padded with zeros instead of spaces. Output is normally right justified. Placing a minus sign after the % will left justify the field. Modifiers may be used to specify different datatypes, as follows: l long / double h short L long double %n will cause the number of characters printed so far to be written to the corresponding pointer to integer in the argument list. Hash (#) preceding a g, f or e code ensures the decimal point is printed even when there are no decimal digits. Using it with octal or hexadecimal formats o and h will cause them to be prefixed with 0 or 0x respectively. The width and places specifiers may be passed as arguments by placing and asterisk in the format. They are matched in the order they occur, in the same way as the values to be printed.
#include stdio.h int fputc(int ch, FILE *stream); Writes the character ch to the specified stream. Returns ch on success, of EOF on error. Use ferror() to determine error status.
#include stdio.h int fputs(const char *str, FILE *stream); Writes the null terminated string str to the specified stream. The null terminator is not written. Returns a non-negative value on success, and EOF on failure. Use ferror() to determine error status. If the file is opened in text mode, character conversions may take place.
#include stdio.h int fread(void *buf, size_t size, size_t count, FILE *stream); Reads count objects, each size bytes long, into the memory at buf from the specified stream. Returns the number of items actually read. If this is less than the number requested, use feof() and ferror() to determine the status. Character conversions may occur if the file is opened in text mode.
#include stdlib.h void free(void * ptr); Returns the memory pointed to by ptr to the heap, making it available for future allocation. Free must only be called with a pointer obtained from a dynamic allocation function such as malloc or calloc.
#include stdio.h FILE * freopen(const char *filename, const char *mode, FILE *stream); Associates an existing stream with a different filename. The access mode is in the same format as for fopen(). The function first attempts to close the file already associated with stream. However, if this fails it still opens the new file. Returns a pointer to stream on success, or null on failure.
#include math.h double frexp(double num, int *exp); Decomposes num into a mantissa in the range 0.5 to less than 1, and an integer exponent such that num = mantissa * 2exp. The mantissa is returned by the function, and the exponent is stored at exp.
#include stdio.h int fscanf(FILE *stream, const char *format, ...); Read from stream and stores the information in variables in the argument list, using the control string format. The control string contains format specifiers, white space and non-white space separators. Format specifiers indicate the values which should be read into arguments, as follows: %c single character %d decimal integer %i decimal integer %e floating point number %f floating point number %g floating point number %o octal number %s string %x hexadecimal number %p pointer %u unsigned integer %n number of characters read %[] range of characters White space in format causes one or more white space characters from the input to be skipped. Non white space characters in format will be read from the input and discarded; if a matching character is not found, fscanf() will terminate. All variables used to receive values must be passed by address. Strings will be read only up to the first white space. All input data must be separated by white space, unless explicitely specified in format. Placing a * after the % will cause the value to be read but not assigned. This can be used to skip over unrequired fields. Format commands can specify a maximum width after the % to limit the number of characters read for any field. Returns the number of fields assigned to arguments, or EOF if there is an error before any fields are assigned.
#include stdio.h int fseek(FILE *stream, long offset, int origin); Sets the file position for stream as specified by offset and origin. The offset is the number of bytes to seek, from the origin as defined by the following macros: SEEK_SET seek from start of file SEEK_CUR seek from current position SEEK_END seek (backwards) from end of file Returns zero on success, non-zero on failure.
#include stdio.h int fsetpos(FILE *stream, const fpos_t *position); Returns the file position for stream to the point specified by position, which must have been obtained from a call to fgetpos(). Returns zero on success, and non-zero on failure.
#include stdio.h long ftell(FILE *stream); Retuns the current file position for stream, in bytes from the start of the file. May not be meaningful for text files because of character conversions, except as an argument to fseek(). Returns -1L on error, and the result may not be meaningful for files incapable of random seeks such as modems and terminals.
#include stdio.h int fwrite(const void *buf, size_t size, size_t count, FILE *stream); Writes count objects, each size bytes long, from the memory location buf to the specified stream. Returns the number of items actually written; use ferror() to determine the status if this is less then count. Character conversions may occur if the stream is opened in text mode.
#include stdio.h int getc(FILE *stream); Returnns the next character from the input stream. On error, or if the end of the file is reached, returns EOF. Note that EOF is a valid character, so feof() or ferror() should be used to check for end-of-file or error conditions.
#include stdio.h int getchar(void); Equivalent to fgetc(stdin)
#include stdlib.h char * getenv(const char *name); Returns a pointer to the environment variable name, or null if name is not found. Note that the returned string must not be changed.
#include stdio.h char * gets(char *str); Reads characters from stdin until a newline or EOF is reached, placing them in str. The string will be null terminated. Returns str on success, or null on error or end-of-file. Use feof() and ferror() to determine the status if null is returned. Note that there is no limit to the number of characters read.
#include time.h struct tm * gmtime(time_t *time); Returns a pointer to the broken down form of time in a tm structure, based on Greenwich Mean Time. Note the structure will be overwritten by subsequent calls to this function.
#include ctype.h int isalnum(int ch); Returns non-zero if ch is a letter of the alphabet or a digit.
#include ctype.h int isalpha(int ch); Returns non-zero if ch is a letter of the alphabet, which may vary from language to language.
#include ctype.h int iscntrl(int ch); Returns non-zero if ch is a control character (0-31 or 127).
#include ctype.h int isdigit(int ch); Returns non-zero if ch is a digit ('0' through '9').
#include ctype.h int isgraph(int ch); Returns non-zero if ch is a printable character and not a space. This usually means the range 33 - 126.
#include ctype.h int islower(int ch); Returns non-zero if ch is a lowercase letter.
#include ctype.h int isprint(int ch); Returns non-zero if ch is a printable character, including space. This is normally the range 32 - 126.
#include ctype.h int ispunct(int ch); Return non-zero if ch is a punctuation character. Punctuation means all printing characters except alphanumerics and space.
#include ctype.h int isspace(int ch); Returns non-zero if ch is a space, horizontal tab, vertical tab, carriage return or newline character.
#include ctype.h int isupper(int ch); Returns non-zero if ch is an uppercase letter.
#include ctype.h int isxdigit(int ch); Returns non-zero if ch is a hexadecimal digit (A-F, a-f or 0-9)
#include stdlib.h long labs(long num); Returns the absolute (positive) value of num.
#include math.h double ldexp(double num, int exp); Returns num * 2exp.
#include stdlib.h ldiv_t ldiv(long numerator, long denominator); Returns the quotient and remainder of numerator/denominator in a ldiv_t structure. The ldiv_t structure is defined in stdlib.h and will have at least two long integer fields quot and rem.
#include locale.h struct lconv * localeconv(void); Returns a pointer to a structure of type lconv which contains various locale specific values. The contents of the structure must not be changed. See the locale.h file for its contents.
#include time.h struct tm * localtime(time_t *time); Returns a pointer to the broken down form of time in a tm structure, based on Local Time. Note the structure will be overwritten by subsequent calls to this function.
#include math.h double log(double num); Returns the natural logarithm of num.
#include math.h double log10(double num); Returns the base 10 logarithm of num.
#include setjmp.h void longjmp(jmp_buf envbuf, int status); Causes program execution to resume at the point of the last call to setjmp(), allowing for a jump between functions. The value status becomes the return value from the original setjmp() call, and must not be 0.
#include stdlib.h void * malloc(size_t size); Allocates size bytes of memory from the heap. Returns a pointer to the allocated memory, or null if allocation fails.
#include string.h void * memchr(const void *buffer, int ch, size_t count); Searches the first count characters of the buffer pointed to by buffer for the first occurrence of character ch. Return value is pointer to first occurrence of ch or null if not found
#include string.h int memcmp(const void *buf1, const void *buf2, size_t count); Lexicographically compares the first count characters of the buffers pointed to by buf1 and buf2. Return value is: <0 buf1 is less than buf2 =0 buf1 is equal to buf2 >0 buf1 is greater than buf2
#include string.h void * memcpy(void *to, const void *from, size_t count); Copies count characters from the buffer pointed to by from into the buffer pointed to by to. If the buffers overlap behaviour is undefined.
#include string.h void * memmove(void *to, const void *from, size_t count); Copies count characters from the buffer pointed to by from into the buffer pointed to by to. If the buffers overlap the copy will take place correctly, leaving the correct contents in to but modifying from.
#include string.h void * memset(void *buf, int ch, size_t count); Sets count memory locations starting at buf to the low-order byte of ch. Most commonly used to initialise a block of memory, such as a structure.
#include time.h time_t mktime(struct tm *time); Returns the calendar time equivalent of the broken-down time in the structure time. Elements tm_wday and tm_yday are set by the function. Returns -1 if the information cannot be represented as a valid time.
#include math.h double modf(double num, int *i); Decomposes num into its integer and fractional parts, storing the integer at i and returning the fraction.
#include stdio.h void perror(const char *str); Translates the global variable errno to an error message and writes it to stderr. If str is not null, it will be written before the error message.
#include math.h double pow(double base, double exp); Returns base raised to the exp power.
#include stdio.h int printf(const char *format, ...); Equivalent to fprintf(stdout, format, ...)
#include stdio.h int putc(int ch, FILE *stream); Writes the character in the least significant byte of ch to the output stream pointed to by stream. Returns the character written on success, or EOF on failure. Use ferror() to determine the status.
#include stdio.h int putchar(int ch); Equivalent to fputc(ch, stdout)
#include stdio.h int puts(char *str); Equivalent to fputs(str, stdout)
#include stdlib.h void qsort(void *buf, size_t num, size_t size, int (*compare)(const void *, const void *)); Sorts the array pointer to by buf using a quicksort algorithm. The number of elements is specified by num, and the size in bytes of each element is specified by size. The function compare is used to compare two elements of the array, in the following form: int function(const void *arg1, const void *arg2) returning: arg1 < arg2 less than 0 arg1 = arg2 0 arg1 > arg2 greater than 0 The array will be sorted in ascending order.
#include signal.h int raise(int signal); Send the signal specified by signal to the executing program. Return value 0 is successful, otherwise non-zero
#include stdlib.h int rand(void); Returns a pseudo-random number between 0 and RAND_MAX.
#include stdlib.h void * realloc(void *ptr, size_t size); Changes the size of a previously allocated memory block pointed to by ptr to a new number of bytes size. The new size may be greater or less than the original. The block may need to be moved to increase its size, in which case the old contents will be copied to the new location. Returns a pointer to the new block, or null if allocation failed (in which case the old block remains valid). If size is zero, the memory if freed.
#include stdio.h int remove(const char *filename); Erases (deletes) the file specified by filename. Returns 0 on success, and non-zero on failure.
#include stdio.h int rename(const char *oldname, const char *newname); Renames (moves) the specified file from oldname to newname. The new name must not already be used. Returns 0 on success, or non-zero on failure.
#include stdio.h void rewind(FILE *stream); Moves the file position indicator for stream to the beginning of the stream, and clears the end-of-file and error flags.
#include stdio.h int scanf(const char *format, ...); Equivalent to fscanf(stdin, format, ...)
#include stdio.h void setbuf(FILE *stream, char *buf); Sets the buffer used by stream to buf, or turns off buffering if buf is null. If specified, the buffer must be BUFSIZ characters long.
#include setjmp.h int setjmp(jmp_buf envbuf); Saves the contents of the system stack in the buffer envbuf for later use by longjmp(). Returns 0 on invocation, and the value passed to longjmp() after the jump back.
#include locale.h char * setlocale(int type, const char *locale); Sets the current locale for the specified type to locale. If locale is null it returns a pointer to the current locale. The following macros should be used for values of type: LC_ALL refers to all categories LC_COLLATE affects strcoll() LC_CTYPE affects the character functions LC_MONETARY determines the monetary format LC_NUMERIC determines the decimal point format LC_TIME affects strftime()
#include stdio.h int setvbuf(FILE *stream, char *buf, int mode, size_t size); Allows the buffer location, size and mode to be specified for the stream. If buf is null, it will be allocated. The mode can be one of: _IOFBF full buffering _IONBF no buffering _IOLBF line buffering The size must be greater than zero. Returns zero on success, or non-zero on failure.
#include signal.h (*func)(int) signal(int signal, void (*func)(int)); Registers the function func to receive the specified signal. Alternatively, func can be one of the following: SIG_DFL to use default signal handling SIG_IGN ignore the signal Returns func if successful, or SIG_ERR if not.
#include math.h double sin(double arg); Returns the sine of arg, where arg is in radians.
#include math.h double sinh(double arg); Returns the hyperbolic sine of arg, where arg is in radians.
#include stdio.h int sprintf(char *buf, const char *format, ...); As fprintf(), but the output is written to the string buf.
#include math.h double sqrt(double num); Returns the square root of num.
#include stdlib.h void srand(unsigned seed); Sets the starting point for the sequence generated by rand() using the value seed. Using the same value of seed will cause the same sequence of random numbers to be generated.
#include stdio.h int sscanf(const char *buf, const char *format, ...); As fscanf, except the input is taken from the string at buf.
#include string.h char * strcat(char *str1, const char *str2); Concatenates the null-terminated string str2 onto the end of str1. If the strings overlap, behaviour is undefined. Return str1.
#include string.h char * strchr(const char *str, int ch); Searches the null-terminated string str for the first occurrence of character ch. Return value is a pointer to first occurrence of ch or null if not found
#include string.h int strcmp(const char *str1, const char *str2); Compares the two null-terminated strings str1 and str2. Return value is <0 str1 is less than str2 =0 str1 is equal to str2 >0 str1 is greater than str2
#include string.h int strcoll(const char *str1, const char *str2); Compares the strings pointed to by str1 and str2, in accordance with the locale specified using setlocale(). Return value is <0 str1 is less than str2 =0 str1 is equal to str2 >0 str1 is greater than str2
#include string.h char * strcpy(char *str1, const char *str2); Copies the contents of str2 into str1, where str2 must be a pointer to a null-terminated string. Returns str1. If str1 and str2 overlap, the behaviour is undefined.
#include string.h int strcspn(const char *str1, const char *str2); Finds the length of the initial substring of str1 made up only of characters not in str2. Put differently, it returns the index of the first character in str1 which is also in str2.
#include string.h char * strdup(char *str); Duplicates the string pointed to by str, obtaining the memory through a call to malloc(). Returns a pointer to the new string on success, or null on failure.
#include string.h char * strerror(int errnum); Returns a pointer to an implementation specific string associated with errnum.
#include time.h size_t strftime(char *str, size_t maxsize, const char *fmt, const struct tm *time); Formats date, time and other information into the string str from the structure time based on the format string fmt. A maximum of maxsize characters will be written. Format commands beginning with % will be replaced with time and date values in local format. Other characters will be copied. %a abbreviated weekday name %A full weekday name %b abbreviated month name %B full month name %c standard date and time string %d day of month as decimal (1-31) %H hour (0-23) %I hour (1-12) %j day of year as decimal (1-366) %m month as decimal (1-12) %M minute as decimal (0-59) %p locale's equivalent of AM or PM %S second as decimal (0-59) %U week of year, Sunday being first day (0-52) %w weekday as decimal (0-6, Sunday being 0) %W week of year, Monday being first day (0-52) %x standard date string %X standard time string %y year in decimal without century (00-99) %Y year including century as decimal %Z time zone name %% percent sign Returns the number of characters written, or zero on error.
#include string.h size_t strlen(char *str); Returns the length of the null-terminated string str, not including the null.
#include string.h char * strncat(char *str1, char *str2, size_t count); Concatenates up to count characters of str2 onto the end of str1. If the strings overlap, behaviour is undefined. Returns str1.
#include string.g int strncmp(const char *str1, const char *str2, size_t count); Compares two null terminated strings str1 and str2; up to a maximum of count characters are compared. Return value is <0 str1 is less than str2 =0 str1 is equal to str2 >0 str1 is greater than str2
#include string.h char * strncpy(char *str1, const char *str2, size_t count); Copies up to count characters from the null-terminated string str2 to str1. If str2 has less than count characters, then str1 will have nulls appended until count characters have been copied. If str2 has more than count characters then str1 will not be null terminated. Returns str1.
#include string.h char * strpbrk(const char *str1, const char *str2); Returns a pointer to the first character in str1 which matches any character in str2 or null.
#include string.h char * strrchr(const char *str, int ch); Returns a pointer to the last occurence of character ch in the string str or null.
#include string.h size_t strspn(const char *str1, const char *str2); Returns the length of the initial substring of str1 made up of characters found in str2. Stated differently, it returns the index of the first character in str1 which cannot be found in str2.
#include string.h char * strstr(const char *str1, const char *str2); Returns a pointer to the first occurrence of str2 in str1 or null.
#include stdlib.h double strtod(const char *start, char **end); Returns the floating point number found at start, reading up to any character that cannot form part of a floating point number. White space is skipped before the conversion, and end is set to the first character after the number.
#include string.h char * strtok(char *str1, const char *str2); Splits str1 into tokens separated by characters found in str2. The first call finds the first separator and replaces it with a null, returning a pointer to the first token. Subsequent calls should have str1 set to null, and will return a pointer to the next token. Null is returned when there are no more tokens. It is possible to change the set of delimiters for each call.
#include stdlib.h long strtol(const char *start, char **end, int radix); Returns the integer number (in the base specified by radix) found at start, reading up to any character that cannot form part of an integer number in that base. White space is skipped before the conversion, and end is set to the first character after the number. The base radix must be in the range 2 - 36.
#include stdlib.h unsigned long strtoul(const char *start, char **end, int radix); Returns the unsigned integer number (in the base specified by radix) found at start, reading up to any character that cannot form part of an integer number in that base. White space is skipped before the conversion, and end is set to the first character after the number. The base radix must be in the range 2 - 36.
#include string.h size_t strxfrm(char *str1, const char *str2, sie_t count); Transforms the first count characters of str2 and places them in str1. After translation, a comparison using strcmp() on str1 will produce the same results as a strcoll() using the original string str2. Return value is the length of the transformed string.
#include stdlib.h int system(const char *str); Passes the command pointed to by str to the command processor of the operating system. Return value is system dependent. Passing null as str will return non-zero if the command processor is present, and zero otherwise.
#include math.h double tan(double arg); Returns the tangent of arg, where arg is in radians.
#include math.h double tanh(double arg); Returns the hyperbolic tangent of arg, where arg is in radians.
#include time.h time_t time(time_t *time); Returns the current calendar time, or -1 if the system has no time. If time is not null, it will also be set to the return value.
#include stdio.h FILE * tmpfile(void); Opens a temporary file for update and returns a pointer to its stream. The file will automatically have a unique filename to avoid conflicts. Returns a null pointer on failure. The temporary file will be automatically removed when it is closed, or when the program terminates.
#include stdio.h char * tmpnam(char *name); Generates a unique filename and stores it in name. This function can be called at least TMP_MAX times, which will be at least 25. Returns a pointer to name on success, or null on failure.
#include ctype.h int tolower(int ch); Returns the lowercase equivalent of ch, or ch unchanged if it is not an uppercase letter.
#include ctype.h int toupper(int ch); Returns the uppercase equivalent of ch, or ch unchanged if it is not a lowercase letter.
#include stdio.h int ungetc(int ch, FILE *stream); Retuns the character ch to the stream stream, so it will be returned by the next read operation. One character ungetc is guaranteed, some versions may accept more. Returns ch on success, and EOF on failure.
#include stdarg.h type va_arg(va_list argptr, type); Macro used to retrieve arguments to variable argument functions, where argptr has been initialised by a call to va_start() and type is the expected data type of the argument.
#include stdarg.h void va_end(va_list argptr); Stops reading variable arguments, freeing up memory etc
#include stdarg.h void va_start(va_list argptr, last_parm); Initialises the retrieval of variable argument list arguments, where argptr is a control structure used by later calls to va_arg() and last_parm is the last declared argument.
#include stdarg.h #include stdio.h int vfprintf(FILE *stream, char *format, va_list argptr); Equivalent to fprintf(), except the argument list has been replaced by a pointer to a list of arguments.
#include stdarg.h #include stdio.h int vprintf(char *format, va_list argptr); Equivalent to printf(), except the argument list has been replaced by a pointer to a list of arguments.
#include stdarg.h #include stdio.h int vsprintf(char *buf, char *format, va_list argptr); Equivalent to sprintf(), except the argument list has been replaced by a pointer to a list of arguments.