Appendix 1 - Standard Library Reference

Embed Size (px)

Citation preview

  • 8/11/2019 Appendix 1 - Standard Library Reference

    1/29

    CSC1402 Foundation Computing A1.1

    Appendix A1Simplified C Standard LibraryReference

  • 8/11/2019 Appendix 1 - Standard Library Reference

    2/29

    CSC1402 Foundation Computing A1.2

    Introduction

    This is a limited set of functions and constants from the C Standard Libraries. Thefunctions and constants given are relevant to an introductory programming course in

    C/C++ using a procedural paradigm first approach.

    Table of Contents

    A1.1. Character Handling ......................................................................... 3

    A1.2. Mathematics .................................................................................... 5

    A1.3.

    Input/Output .................................................................................... 7

    A1.4.

    String Conversion, Random Numbers and Other ......................... 15

    A1.5.

    String Handling ............................................................................ 17

    A1.6.

    Date and Time ................................................................................ 20

    A1.7.

    Reserved Words ............................................................................................. 24

    A1.8.

    ASCII Table ................................................................................................... 25

    Standard Library Index ................................................................................................ 26

  • 8/11/2019 Appendix 1 - Standard Library Reference

    3/29

    CSC1402 Foundation Computing A1.3

    A1.1.Character Handling

    int isalnum (int charToTest);

    Returns 1 (equivalent to true) if charToTest is an alphabetic character ornumeric digit character. Returns 0 (equivalent to false) otherwise.

    The following statements output 1.

    printf("%i\n", isalnum('1'));printf("%i\n", isalnum('a'));

    The following outputs 0.

    printf("%i\n", isalnum('#'));

    int isalpha (int charToTest);Returns 1 (equivalent to true) if charToTestis an alphabetic character. Returns 0(equivalent to false) otherwise.

    The following outputs 1.

    printf("%i\n", isalnum('a'));

    The following outputs 0.

    printf("%i\n", isalnum('#'));

    int isdigit (int charToTest);

    Returns 1 (equivalent to true) if charToTestis a numeric digit character. Returns0 (equivalent to false) otherwise.

    The following outputs 1.

    printf("%i\n", isalnum('a'));

    The following outputs 0.

    printf("%i\n", isalnum('#'));

    int islower (int charToTest);

    Returns 1 (equivalent to true) if charToTestis a lower case alphabetic character.Returns 0 (equivalent to false) otherwise.

  • 8/11/2019 Appendix 1 - Standard Library Reference

    4/29

    CSC1402 Foundation Computing A1.4

    The following outputs 1.

    printf("%i\n", isalnum('a'));

    The following outputs 0.

    printf("%i\n", isalnum('A'));

    int isspace (int charToTest);

    Returns 1 (equivalent to true) if charToTestis a whitespace character. Returns 0(equivalent to false) otherwise.

    The following outputs 1.

    printf("%i\n", isalnum(' '));

    The following outputs 0.

    printf("%i\n", isalnum('#'));

    int isupper (int charToTest);

    Returns 1 (equivalent to true) if charToTest is an upper case alphabeticcharacter. Returns 0 (equivalent to false) otherwise.

    The following outputs 1.

    printf("%i\n", isalnum('A'));

    The following outputs 0.

    printf("%i\n", isalnum('a'));

    int tolower (int charToConvert);

    Returns a lower case equivalent of charToConvertif it is an upper case alphabeticcharacter. Returns the value of charToTestotherwise.

    The following outputs the letter a.

    printf("%c\n", tolower('A'));

    int toupper (int charToConvert);Returns an upper case equivalent of charToConvertif it is a lower case alphabeticcharacter. Returns the value of charToTestotherwise.

    The following outputs the letter A.

    printf("%c\n", tolower('a'));

  • 8/11/2019 Appendix 1 - Standard Library Reference

    5/29

    CSC1402 Foundation Computing A1.5

    A1.2.Mathematics

    double ceil (double numberToBeRounded);

    Returns the next whole number after numberToBeRoundedin a positive directionon the number line. For example when numberToBeRoundedis 1.23 ceilreturns2.0; when numberToBeRoundedis -1.23 ceilreturns -1.0.

    The following outputs 2.000000.

    printf("%lf\n", ceil(1.23));

    The following outputs -1.000000.

    printf("%lf\n", ceil(-1.23));

    double cos (double angleInRadians);

    Returns the cosine of angleInRadianswhich is an angle measurement in radians.

    double exp (double x);

    Returns the exponential function of x(ex).

    double fabs (double number);

    Returns the absolute value of number. Where numberis negative, its positive valueis returned.

    double floor (double numberToBeRounded);

    Returns the next whole number after numberToBeRoundedin a positive directionon the number line. For example when numberToBeRoundedis 1.23 ceilreturns2.0; when numberToBeRoundedis -1.23 ceilreturns -1.0.

    The following outputs 6.000000.

    printf("%lf\n", floor(6.78));

    The following outputs -7.000000.

    printf("%lf\n", ceil(-6.78));

    double log (double x);

    Returns the natural logarithm of x(logex).

    double log10 (double x);

    Returns the base-ten logarithm of x(log10x).

  • 8/11/2019 Appendix 1 - Standard Library Reference

    6/29

    CSC1402 Foundation Computing A1.6

    double pow (double base, double exponent);

    Returnsbaseto the power exponent(baseexponent) for examplex2can be achievedbypow(x,2);

    The following outputs 9.000000.

    printf("%lf\n", pow(2.0, 3.0));

    double sin (double angleInRadians);

    Returns the sine of angleInRadianswhich is an angle measurement in radians.

    double sqrt (double x);

    Returns the square root of x. (x)

    The following outputs 3.000000.

    printf("%lf\n", sqrt(9.0));

    double tan (double angleInRadians);

    Returns the tangent of angleInRadians which is an angle measurement inradians.

  • 8/11/2019 Appendix 1 - Standard Library Reference

    7/29

    CSC1402 Foundation Computing A1.7

    A1.3.Input/Output

    EOF Macro value returned by some functions to indicate end of file.

    int fclose (FILE *stream);

    Closes the file opened on streamand returns 0 for success or EOFon failure.

    The following call closes the file attached to stream.

    fclose(stream);

    int feof (FILE *stream);

    Returns 1 (equivalent to true) if the EOFindicator is set for stream(ie. streamhas reached the end of file).

    The following loop will repeat until streamreaches the end of the file it is attachedto.

    while(!feof(stream)) { ...

    int fgetc (FILE *stream);

    Returns the next character from stream, as an unsigned charconverted to anint(as an ASCII code). Returns EOFif an error occurs, for instance, the end of filehas been reached.

    The following call closes inputs a character from stream.

    char inputCharacter;inputCharacter = fgetc(stream);

    char *fgets (char *string, int maxChars, FILE *stream);

    Reads a string from streamto memory at *string up tomaxChars-1 charactersor until the end of line is reached before readingmaxChars-1 characters. If readingstops at the end of a line, the newline character will be read in and may have to be

    removed. Adds a null (\0) character at the end of the string. Returns string (thelocation of the start of the string read in) on success orNULLon failure.

    The following call inputs a string from stream.

    char inputString[256];fgets(inputString, 256, stream);

  • 8/11/2019 Appendix 1 - Standard Library Reference

    8/29

    CSC1402 Foundation Computing A1.8

    FILE *fopen (const char *filename, const char *mode);

    Opens the file named filename; returns the address of a stream on success orNULLon failure. The argumentmodeshould be one of the following strings. Addb to the

    mode to open a binary file.

    r reading opens existing file at start

    w writing creates a file if non-existent or truncates existing file

    a appending creates a file if non-existent or starts at end of existing file

    r+ reading and writing opens existing file at start for updating

    w+ reading and writing creates a file if non-existent or truncates existing file

    a+ reading and writing creates a file if non-existent or starts at end of existing file

    The following call opens the file output.txt for writing.

    FILE *outputStream;outputStream = fopen("output.txt", "w");

    int fprintf (FILE *stream, const char *format, ...);

    Writes to streamaccording to format substituting format sequences with furtherarguments. Returns the number of successfully characters output or a negative value ifan error occurs.

    The following call outputs the value 5 to outputStream.

    fprintf(outputStream, "%i", 5);

    Format Sequence

    The following format sequences are used with expressions of specific types.

    %c char

    %ior %d int

    %s string

    %u unsigned int

    %lior %D long int

    %luor %U long unsigned int

    %hi short int

    %hu short unsigned int

    %f float

    %lf double

    %L long double%% percentage symbol

  • 8/11/2019 Appendix 1 - Standard Library Reference

    9/29

    CSC1402 Foundation Computing A1.9

    Field Width

    Field width can be used to control the output format of expressions where a columnaroutput is needed.

    For Integers, Strings, and Single Characters

    Placing a number between the %and format specifier for a format sequence will causethe integer to be output right-justified in a field width with that number of spaces. For

    example %3iwill output numbers in a field width of 3 spaces. If the integer beingoutput is longer than the field width, the field width will be 'pushed out' toaccommodate the integer.

    The following call outputs the value 5 in a field width of 3.

    fprintf(outputStream, "%3i", 5);

    For Floating Point Numbers

    A field width can be created in the same way as with integers. A precision (numberof decimal places after the decimal point) can be specified by putting a point after the

    field width and a number of decimal places after that. For example %5.2lf willoutput a double with a field width of 5 spaces and a precision of two digits. It is

    possible to specify precision without a field with, for example %.2lf.

    The following call outputs the value 1.23.

    fprintf(outputStream, "%.2lf", 1.23456);

    Field Width From a Variable or Constant

    By placing an asterisk (*

    ) in place of the field width, eg.%*i

    will causefprintf()

    to source the field width from the next argument which will precede the value to be

    output in place of the format sequence. For example, if COLUMN_WIDTHwas definedas the width of columns in a table, the value of int variable columnValue canoutput as follows.

    fprintf(outputStream, "%*i", COLUMN_WIDTH, columnValue);

    Format Flags

    Within the specified filed width the following controls can be added.

    - left justify

    + force printing sign

    0(zero) pads field width with spaces

    The following call outputs 005.

    fprintf(outputStream, "%03i", 5);

  • 8/11/2019 Appendix 1 - Standard Library Reference

    10/29

    CSC1402 Foundation Computing A1.10

    Escape Sequences

    Some characters cannot be created in a format string using the normal keyboard.

    \a alert (bell sound)

    \b backspace

    \f formfeed

    \n newline

    \r carriage return

    \t tab

    \" double quotes

    \\ backslash

    The following call outputs "hello" (including the quotes).

    fprintf(outputStream, "\"hello\"");

    int fputc (char characterToOutput, FILE *stream);

    Writes the character characterToOutput to stream. Returns the characterwritten if successful or EOFif unsuccessful.

    The following call outputs a letter X.

    fputc('X',outputStream);

    int fputs (const char *stringToOutput, FILE *stream);

    Writes the string stringToOutput to stream. Returns a non-negative (zero orpositive) number if successful or EOFif unsuccessful.

    The following call outputs a the string hello.

    fputs("hello",outputStream);

    int fscanf (FILE *stream, const char *format, ...);

    Reads from streamaccording to formatand attempts to assign values described informatby format sequences starting with % to the variables pointed to by the thirdand following arguments. If an item read in does not match a format sequence giventhe function will not assign a value and will stop attempting further input.

    Characters in the format string that are not part of a format sequence are used todescribe the exact format of input expected. If the format does not match input giventhe function will stop and not attempt further input.

    Returns the number of correctly matched, read and assigned values. If fscanf()stops before the end of the format string, the number of assigned values to that point

    is returned.

  • 8/11/2019 Appendix 1 - Standard Library Reference

    11/29

    CSC1402 Foundation Computing A1.11

    The following call inputs an integer into inputInteger.

    fscanf(outputStream, "%i", &inputInteger);

    Format Sequences

    The following format sequences are used with expressions of specific types.

    %c char

    %ior %d int

    %s string

    %u unsigned int

    %lior %D long int

    %luor %U long unsigned int

    %hi short int%hu short unsigned int

    %f float

    %lf double

    %L long double

    %% percentage symbol

  • 8/11/2019 Appendix 1 - Standard Library Reference

    12/29

    CSC1402 Foundation Computing A1.12

    Scansets

    Ascansetallows us to specify exactly which characters we wish to allow or disallow

    when reading in a string. Scansets can only be applied in place of an s formatspecifier in a %s format sequence. It cannot be used to read in numbers or singlecharacters. Instead of an s we place a set bounded by two [ square brackets ]containing the letters we will accept when reading into a string.

    fscanf(inputStream, "%[abc]", myString);

    In the above call to fscanf()a string is being read in. Only the characters a,borc will be accepted. When any other character is encountered, no further characterswill be read intomyString.

    A negatedscanset specifies what characters will not be accepted when reading a

    string. A negated scanset starts with a caret (^). The remaining characters form the

    set of characters that will not be accepted. When reading in a string, all characters(including whitespace characters) will be accepted until one of the characters in thenegated scanset is encountered.

    fscanf(inputStream, "%[^abc]", myString);

    A practical application for a negated scanset is when reading in a line of text. Byallowing all characters except the newline character, input into a string will continueuntil the end of a line is encountered.

    fscanf(inputStream, "%[^\n]", myString);

    We should always restrict the length of a string read in using a scanset in the same

    way that we do for a normal %sformat sequence (by placing an length in between the% and the scanset). The following call to fscanf() will read characters into

    myStringuntil a newline character is met, or 19characters have been read in.

    fscanf(inputStream, "%19[^\n]", myString);

    Ignoring Input

    Placing an asterisk (*) in a format sequence will cause a value to be input but notstored. For example to read in and ignore a character between two integers thefollowing call can be used. Note that the surrounding, non-ignored inputs correspondto addresses given as subsequent arguments.

    fscanf(inputStream, "%i%*c%i", &firstInt, &secondInt);

    Whitespace

    Whitespace includes spaces, tabs carriage returns and newline characters. Whenreading any basic type, except single characters or scansets that allow whitespace,whitespace is skipped before usable input.

    Ignoring Whitespace

    When reading single characters or scansets that allow whitespace, or to explicitly

    ignore whitespace at other times, any amount of whitespace can be ignored by

  • 8/11/2019 Appendix 1 - Standard Library Reference

    13/29

    CSC1402 Foundation Computing A1.13

    including a single space character in a format sequence. For this reason \n, \tand\rcharacters are not normally used in input format strings.

    int getc (FILE *stream);

    Achieves fgetc(stream).

    int getchar (void);

    Achieves fgetc(stdin).

    int printf (const char *format, ...);

    printf(format,args)achieves fprintf(stdout,format,args).

    int putc (int characterToBeOutput, FILE *stream);

    Achieves fputc(characterToBeOutput, stream).

    int putchar (int characterToBeOutput);

    putchar(characterToBeOutput)achievesfputc(characterToBeOutput,stdout).

    int puts (const char *stringToOutput);Writes the string stringToOutput to stdout, and appends a newline. Returnsnon-negative (zero or positive) for success or EOFfor failure.

    The following call outputs hello to standard output.

    puts("hello");

    int remove (const char *filename);

    Deletes the file filename. Returns zero on success or non-zero on failure.

    The following call deletes the file input.txt.remove("input.txt");

    int rename (const char *oldName, const char *newName);

    Renames oldNameto newName. Returns zero on success, non-zero on failure.

  • 8/11/2019 Appendix 1 - Standard Library Reference

    14/29

    CSC1402 Foundation Computing A1.14

    The following call renames the file input.txt to become newInput.txt.

    rename("input.txt","newInput.txt");

    void rewind (FILE *stream);

    Moves streamto the beginning of the file.

    int scanf (const char *format, ...);

    scanf(format,args)achieves fscanf(stdin,format,args).

    int sprintf (char *strToPrintTo,const char *format,

    ...);

    Using the same functionality as fprintf(), but prints to strToPrintToinsteadof an output stream.

    The following call builds a string with content "a string 5" (without quotes).

    char stringToPrintTo[256];sprintf(stringToPrintTo, "%s %i", "a string", 5);

    int sscanf (

    const char *strToRead,const char *format,...

    );

    Using the same functionality fscanf(), but 'reads' from strToRead instead of afile.

    The following call reads a string and an integer from stringToRead.

    char stringToReadFrom = "string 5";char stringToStore[256];

    int integerToStore;sscanf(stringToReadFrom,"%s %i",stringToStore,&integerToStore

    );

    int ungetc (int characterToPutBack, FILE *stream);

    Puts the character characterToPutBackback into the input stream streamso

    that it is the next character to be read in from the stream. Returns the character pushedback if successful or EOFon failure.

  • 8/11/2019 Appendix 1 - Standard Library Reference

    15/29

    CSC1402 Foundation Computing A1.15

    A1.4.String Conversion, Random Numbers and Other

    void abort (void);

    Ends the program and returns an unsuccessful terminationprogram exit status.

    int abs (int positiveOrNegativeInteger);

    Returns the absolute value of positiveOrNegativeInteger. IfpositiveOrNegativeIntegeris negative a positive equivalent is returned.

    The following call outputs 5.

    printf("%i\n", abs(-5));

    double atof (const char *stringContainingNumber);

    Returns the double equivalent of the number found at the beginning of thestringContainingNumber. This function cannot be assume to work when non-numeric data is present in the string.

    The following call assigns 1.23 to numberFromString.

    numberFromString = atof("1.23");

    int atoi (const char *stringContainingNumber);

    Returns the int equivalent of the number found at the beginning of thestringContainingNumber. This function cannot be assume to work when non-numeric data is present in the string.

    The following call assigns 1 to numberFromString.

    numberFromString = atoi("1");

    long int atol (const char *stringContainingNumber);

    Returns the long int equivalent of the number found at the beginning of the

    stringContainingNumber. This function cannot be assume to work when non-numeric data is present in the string.

    The following call assigns 1234567 to numberFromString.

    numberFromString = atoi("1234567");

    void exit (int status);

    Terminates the program returning statusas the success status of the program (usezero or EXIT_SUCCESS to indicate successful termination or a positive number orEXIT_FAILUREfor failure).

  • 8/11/2019 Appendix 1 - Standard Library Reference

    16/29

    CSC1402 Foundation Computing A1.16

    The following call terminates the program and sets the termination status to 1.

    exit(1);

    int rand (void);

    Returns a pseudo-random number in the range 0 to RAND_MAX (which is at least32767 but usually 2147483647). A random sequence should be seeded using

    srand()before using rand().

    The following call generates a random integer and stores it in randomInteger.

    randomInteger = rand();

    The following call generates a random integer between 1 and 10.

    randomInteger = rand()%10+1;

    void srand (unsigned int seed);

    Seeds a random sequence to be used by rand(). To produce a more unpredictablerandom sequence the seed should be taken from a source of information outside thecomputer, for instance the time that the user starts the program as shown below.

    srand(time(NULL));

  • 8/11/2019 Appendix 1 - Standard Library Reference

    17/29

    CSC1402 Foundation Computing A1.17

    A1.5.String Handling

    The type size_tis equivalent to an unsigned integer and used to indicate a numberof bytes. A single ASCII character occupies a single byte of memory so size_t isalso used to measure a number of characters.

    char *strcat (char *strToCatTo, const char *strToCat);

    Concatenates a copy of strToCatonto the end of strToCatTo. You should checkthere is sufficient space in strToCatTobefore performing the concatenation.

    The following call concatenates " world" to the string in stringToAddTo.

    char stringToAddTo[256] = "hello";strcat(stringToAddTo, " world");

    char *strncat (char * strToCatTo,const char * strToCat,size_t numCharsToCat

    );

    Concatenates a copy of the first numCharsToCat of strToCat onto the end ofstrToCatTo. You should check there is sufficient space in strToCatTo before

    performing the concatenation.

    char *strcpy (char *destination, const char *source);

    Copies a string from source to destination. You should check there issufficient space in destinationbefore performing the copy.

    The following call replaces the string in stringToCopyTowith "hello world".

    char stringToCopyTo[256] = "initial string content";strcpy(stringToCopyTo, "hello world");

    char *strncpy (char *destination,const char *source,size_t numCharsToCopy

    );

    Copies the first numCharsToCopy from from source to destination. Youshould check there is sufficient space in destinationbefore performing the copy.

  • 8/11/2019 Appendix 1 - Standard Library Reference

    18/29

    CSC1402 Foundation Computing A1.18

    int strcmp (const char *string1, const char *string2);

    Compares the string string2with the string string1. Returns...

    0 where the two strings contain the same characters

    0 where the first different character is greater in string1than in string2

    The difference for unequal strings is the difference in the ASCII codes of the firstdifferent characters.

    The following statement compares string1and string2to see if they contain thesame string.

    if(strcmp(string1,string2)==0) { ...

    int strncmp (const char *string1,const char *string2,size_t numCharsToCompare

    );

    Compares the first numCharsToCompare characters string1 and string2using the same method of comparison as for strcmp().

    char *strchr (const char *strToSearch, int charToFind);

    Returns the address of (a pointer to) the first occurrence of charToFind in thestring strToSearch. If the character is not foundNULLis returned.

    The following call finds the address of (a pointer to) 'c' in stringToSearch;

    char *locationOfChar;locationOfChar = strchr(stringToSearch, 'c');

    The following statement tests if 'c' is in stringToSearch;

    if(strchr(stringToSearch,'c')!=NULL) { ...

    char *strrchr (const char * strToSearch, int charToFind);

    Returns the address of (a pointer to) the last occurrence (the first from the right) of

    charToFind in the string strToSearch. If the character is not foundNULL isreturned.

    char *strstr (const char *strToSearch,const char *subStrToFind

    );

    Returns the address of (a pointer to) the first occurrence of subStrToFind in thestring strToSearch. If the substring is not foundNULLis returned.

  • 8/11/2019 Appendix 1 - Standard Library Reference

    19/29

    CSC1402 Foundation Computing A1.19

    The following call finds the address of (a pointer to) "abc" in stringToSearch;

    char *locationOfSubstr;locationOfSubstr = strstr(stringToSearch, "abc");

    The following statement tests "abc" is in stringToSearch;

    if(strstr(stringToSearch, "abc")!=NULL) { ...

    size_t strlen (const char *stringToMeasure);

    Returns the length of the string stringToMeasure. This is the number ofcharacters before (not including) the null at the end of the string.

    The following statement outputs the length of stringToMeasure.

    printf("%i\n", strlen(stringToMeasure));

  • 8/11/2019 Appendix 1 - Standard Library Reference

    20/29

    CSC1402 Foundation Computing A1.20

    A1.6.Date and Time

    The type time_t is used to store a number seconds since epoch (1/1/1970); this isreferred to as Unix time. It is useful to store time in this format as it is easily

    compared and used in calculations. The structure type tm is provided to allow timeinformation to be represented in a form useful to humans. Some functions fortranslating to and from these two forms are provided below.

    struct tm {int tm_sec; // Seconds 0-59int tm_min; // Minutes 0-59int tm_hour; // Hours 0-23int tm_mday; // Day of month 1-31int tm_mon; // Month of year 0-11int tm_year; // Years since 1900 (eg 2006=106)

    int tm_wday; // Day of week (Sun=0 Sat=6)int tm_yday; // Day of year (0-366)int tm_isdst; // Daylight savings flag (0 if

    // in not effect, >0 if in// effect,

  • 8/11/2019 Appendix 1 - Standard Library Reference

    21/29

    CSC1402 Foundation Computing A1.21

    The following call creates a time structure with the current time information.

    time_t currentUnixTime = time();tm currentTimeStruct = *localtime(&currentUnixTime);

    time_t mktime (struct tm *timeStructPtr);

    Returns a Unix time of type time_t based on the information in the structurevariable pointed to by timeStructPtr. The first six members of the tm structure(tm_sec, tm_min, tm_hour, tm_mday, tm_monand tm_year) should and thisfunction will fill in the remaining members of the structure. Time-zone information isgathered from the operating system.

    The following call creates a Unix time from a structure containing time information.

    time_t unixTime = mktime(&timeStruct);

    time_t time (time_t *timePtr);

    Returns the current Unix time. If timePtris notNULLthe time is also assigned tothe variable this points to. Returns -1 if time is not available.

    The following outputs the current Unix time.

    printf("%u\n", time(NULL));

    size_t strftime (char *stringToWriteTimeTo,

    size_t capacityOfString,const char *format,const struct tm *timeStructPtr

    );

    Creates a string from a time structure (pointed to by timeStructPtr) according toa specified format. The string is stored in stringToWriteTimeTo and willlimit the string length to capacityOfStringcharacters.

  • 8/11/2019 Appendix 1 - Standard Library Reference

    22/29

    CSC1402 Foundation Computing A1.22

    Format Sequences

    The following format sequences can be used to describe the time format.

    %a abbreviated weekday name

    %A Full weekday name (Sunday, Monday)

    %bor %h Abbreviated month name (Sun, Mon, )

    %B Full month name (January, February, )

    %c, %xor %X Locale appropriate date and time representation

    %d Day of the month (01 to31)

    %D Equivalent to %m / %d / %y

    %e Day of the month (1 to 31); a single digit is preceded by a space

    %F Equivalent to %Y - %m - %d%H Hour (24-hour clock) (00 to 23)

    %I Hour (12-hour clock) (01 to 12)

    %j Day of the year (001 to 366)

    %m Month (01 to 12)

    %M Minute (00 to 59)

    %n A newline character

    %p locale equivalent of either a.m. or p.m.

    %r Equivalent to %I : %M : %S %p

    %R Time in 24 hour representation %H : %M

    %S Second (00 to 59)

    %t Replaced by a tab character

    %T Equivalent to %H : %M : %S

    %u Weekday (1 to 7 where 1 represents Monday)

    %U Week of year (00 to 53) first Sunday in January is start of week 01

    %w Weekday (0 to 6 where 0 represents Sunday)%W Week of year (00 to 53) first Monday in January is start of week 01

    %yor %C Last two digits of year (00 to 99)

    %Y Year (eg 2006)

    %z Offset from UTC (+hhmm or hhmm) (eg., "-0430" means 4 hours 30minutes behind UTC (west of Greenwich))

    %Z Time-zone name or abbreviation

    %% Percentage symbol

  • 8/11/2019 Appendix 1 - Standard Library Reference

    23/29

    CSC1402 Foundation Computing A1.23

    The following outputs the current time in the specified format.

    char stringForTime[256];time_t currentUnixTime = time(NULL);

    strftime(stringForTime,256,"%A %e %B, %Y %r",localtime(&currentUnixTime)

    );printf("%s\n", stringForTime);

  • 8/11/2019 Appendix 1 - Standard Library Reference

    24/29

    CSC1402 Foundation Computing A1.24

    A1.7.Reserved Words

    and and_eq asm auto

    bitand bitor bool break

    case catch char class

    const const_cast continue default

    delete do double dynamic_cast

    else enum explicit export

    extern false float for

    friend goto if inline

    int long mutable namespace

    new not not_eq operator

    or or_eq private protected

    public register reinterpret_cast return

    short signed sizeof static

    static_cast struct switch templatethis throw true try

    typedef typeid typename union

    unsigned using virtual void

    volatile wchar_t while xor

    xor_eq

  • 8/11/2019 Appendix 1 - Standard Library Reference

    25/29

    CSC1402 Foundation Computing A1.25

    A1.8.ASCII Table

    Code Character

    0 null \0

    7 bell sound \a8 backspace \b9 horizontal tab \t10 newline \n13 carriage return \r32 space33 !34 "35 #36 $37 %

    38 &39 '40 (41 )42 *43 +44 ,45 -46 .47 /48 0

    49 150 251 352 453 554 655 756 857 958 :

    59 ;60 63 ?64 @65 A66 B67 C68 D69 E70 F71 G72 H

    73 I74 J75 K76 L77 M78 N79 O80 P81 Q82 R83 S

    84 T85 U86 V87 W88 X89 Y90 Z91 [92 \93 ]

    94 ^95 _

    Code Character

    96 `

    97 a98 b99 c

    100 d101 e102 f103 g104 h105 i106 j107 k

    108 l109 m110 n111 o112 p113 q114 r115 s116 t117 u118 v

    119 w120 x121 y122 z123 {124 |125 }126 ~

  • 8/11/2019 Appendix 1 - Standard Library Reference

    26/29

    CSC1402 Foundation Computing A1.26

    Standard Library Index

    abort .............................................................. 15

    abs................................................................. 15

    Absolute value of

    floating point numbers ............................... 5

    integers .................................................... 15

    All functions

    abort ......................................................... 15

    abs ............................................................ 15

    asctime ..................................................... 20

    atof ........................................................... 15

    atoi ........................................................... 15atol ........................................................... 15

    ceil ............................................................. 5

    cos ............................................................ .. 5

    exit ........................................................... 15

    exp ............................................................. 5

    fabs ............................................................ 5

    fclose ........................................................ .. 7

    feof ........................................................... .. 7

    fgetc ........................................................... 7

    fgets ........................................................... 7

    floor ........................................................... 5

    fopen ........................................................ .. 8

    fprintf ....................................................... .. 8

    fputc ......................................................... 10

    fputs ......................................................... 10

    fscanf ....................................................... 10

    getc .......................................................... 13getchar ..................................................... 13

    isalnum ...................................................... 3

    isalpha ...................................................... .. 3

    isdigit ......................................................... 3

    islower ....................................................... 3

    isspace ...................................................... .. 4

    isupper ....................................................... 4

    localtime .................................................. 20

    log ............................................................ .. 5

    log10 .................... ...................................... 5

    mktime ............................ ......................... 21

    pow. ............................................................ 6

    printf ......................................................... 13

    putc ..................................................... ...... 13

    putchar ...................................................... 13

    puts ..................................................... ...... 13

    rand ...................... .................................... 16

    remove ...................................................... 13

    rename ...................................................... 13

    rewind....................................................... 14

    scanf ......................................................... 14

    sin. .............................................................. 6

    sprintf ................................................. ...... 14

    sqrt ...................................................... ........ 6

    srand ......................................................... 16

    sscanf ........................................................ 14

    strcat ......................................................... 17

    strchr .................... .................................... 18

    strcmp ....................................................... 18

    strcpy ........................................................ 17

    strftime ............................................... ...... 21

    strlen ......................................................... 19

    strncat ....................................................... 17

    strncmp ..................................................... 18

    strncpy ...................................................... 17

    strrchr ................................................. ...... 18

    strstr .......................................................... 18

    tan ............................................................... 6

    time ...................... .................................... 21

    tolower ............................ ........................... 4

    toupper ............................ ........................... 4

    ungetc ....................................................... 14

    ASCII Table .................................................. 25

    asctime .......................................................... 20

    atof .......................................................... ...... 15

    atoi .................................... ............................ 15

  • 8/11/2019 Appendix 1 - Standard Library Reference

    27/29

    CSC1402 Foundation Computing A1.27

    atol ..................................................... ........... 15

    ceil ..................................................... ............. 5

    Character Functions ........................................ 3

    isalnum ...................................................... 3

    isalpha ...................................................... .. 3

    isdigit ......................................................... 3

    islower ....................................................... 3

    isspace ...................................................... .. 4

    isupper ....................................................... 4

    tolower ..................................................... .. 4

    toupper ..................................................... .. 4

    Check if character is

    a letter ........................................................ 3

    a letter or digit............................................ 3

    a lower case letter ...................................... 3

    a numeric digit ........................................... 3

    a whitespace character ............................... 4

    an upper case letter .................................... 4

    Convert a letter to

    a lower case letter ...................................... 4

    an upper case letter .................................... 4

    Converting

    string to floating point number ................ 15

    string to integer ........................................ 15

    string to long integer ................................ 15

    to time structure ....................................... 20

    to Unix time ............................................. 21

    cos................................................................... 5

    EOF ................................................................ 7

    Escape sequences ......................................... 10

    exit ..................................................... ........... 15

    exp ..................................................... ............. 5

    fabs ................................................................. 5

    fclose .............................................................. 7

    feof ................................................................. 7

    fgetc .............................................................. .. 7

    fgets ................................................................ 7

    Field Width ..................................................... 9

    Floating point numbers .............................. 9

    Format flags ............................................... 9

    From a variable or constant ........................ 9

    Integers, strings and single characters ........ 9

    File functions .................................................. 7

    fclose .......................................................... 7

    feof ..................................................... ........ 7

    fopen .................... ...................................... 8

    Files

    Closing ....................................................... 7

    Deleting .................................................... 13

    Detecting end of file ................................... 7

    Opening ...................................................... 8

    Renaming ................................................. 13

    floor ................................................................. 5

    fopen ............................................ ................... 8

    Format Sequences

    date and time ............................................ 22

    Input ................................................... ........ 8

    Output .................. .................................... 11

    fprintf ...................................................... ........ 8

    fputc ........................................................ ...... 10

    fputs .................................. ............................ 10

    fscanf ....................................................... ...... 10

    getc ................................................................ 13

    getchar ..................................................... ...... 13

    Ignoring input ............................................... 12

    Input

    All types .................................. ................. 10

    Controlled string........... ............................ 12

    From standard input ................................. 14

    Ignoring .................................................... 12

    Ignoring Whitespace ................................ 12

    Scansets .................................................... 12

    Single character .................................... 7, 13

    Strings ..................................... ................... 7

    Whitespace ............................................... 12

    Input functions ................................................ 7

    fgetc ............................................................ 7

    fgets ............................................................ 7

    fscanf ........................................................ 10

    getc ........................................................... 13

  • 8/11/2019 Appendix 1 - Standard Library Reference

    28/29

    CSC1402 Foundation Computing A1.28

    getchar ..................................................... 13

    rewind ...................................................... 14

    scanf ......................................................... 14

    ungetc ...................................................... 14

    isalnum ........................................................... 3

    isalpha ........................................................... .. 3

    isdigit ............................................................ .. 3

    islower ............................................................ 3

    isspace ............................................................ 4

    isupper ............................................................ 4

    localtime ....................................................... 20

    log ...................................................... ............. 5

    log10 ............................................................. .. 5

    Mathematical functions .................................. 5

    abs ............................................................ 15

    ceil ............................................................. 5

    cos ............................................................ .. 5

    exp ............................................................. 5

    fabs ............................................................ 5

    floor ........................................................... 5

    log ............................................................ .. 5

    log10 ........................................................ .. 5

    pow. ......................................................... .. 6

    sin. ............................................................. 6

    sqrt ............................................................. 6

    tan .............................................................. 6

    mktime .......................................................... 21

    Output

    All types ..................................................... 8

    Backslash ................................................. 10

    Newline .................................................... 10

    Quotes ...................................................... 10

    Single character ................................. 10, 13

    String ................................................. 10, 13

    Tab ........................................................... 10

    Time ................................................... 20, 21

    To standard output ................................... 13

    Output functions ............................................. 7

    fputc ......................................................... 10

    fputs ......................................................... 10

    printf ..................................................... 8, 13

    putc ..................................................... ...... 13

    putchar ...................................................... 13

    puts ..................................................... ...... 13

    rewind....................................................... 14

    pow ................................................................. 6

    Power ...................................................... ........ 6

    printf ............................................................. 13

    Programs

    Terminating .............................................. 15

    putc ............................................................... 13

    putchar .......................................................... 13

    puts .......................................................... ...... 13

    rand .............................................. ................. 16

    Random number functions

    rand ...................... .................................... 16

    srand ......................................................... 16

    Random numbers

    getting....................................................... 16

    seeding .................................... ................. 16

    remove ................................ .......................... 13

    rename ..................................................... ...... 13

    Reserved words ............................................. 24

    rewind .......................................... ................. 14

    Rounding numbers

    down ........................................................... 5

    up. ....................................................... ........ 5

    scanf .............................................................. 14

    Scanset .......................................................... 12

    sin 6

    sprintf ............................................................ 14

    sqrt .................................... .............................. 6

    Square Root ..................................................... 6

    srand .............................................................. 16

    sscanf ........................................... ................. 14

    strcat .............................................................. 17

    strchr ............................................ ................. 18

    strcmp ....................... .................................... 18

    strcpy ....................................................... ...... 17

    strftime .......................................................... 21

  • 8/11/2019 Appendix 1 - Standard Library Reference

    29/29

    CSC1402 Foundation Computing A1.29

    String functions ............................................ 17

    sprintf ....................................................... 14

    sscanf ....................................................... 14

    strcat ........................................................ 17

    strchr ........................................................ 18

    strcmp ...................................................... 18

    strcpy ....................................................... 17

    strlen ........................................................ 19

    strncat ...................................................... 17

    strncmp .................................................... 18

    strncpy ..................................................... 17

    strrchr ....................................................... 18

    strstr ......................................................... 18

    Strings

    Adding to end .......................................... 17

    Assigning ................................................. 17

    Comparing ............................................... 18

    Concatenating .......................................... 17

    Constructing from parts ........................... 14

    Copying ................................................... 17

    Deconstructing to parts ............................ 14

    Finding characters in............................ 18Finding substrings in............................ 18

    Length of.............................................. 19

    strlen ............................................................. 19

    strncat ........................................................... 17

    strncmp ......................................................... 18

    strncpy .......................................................... 17

    strrchr ........................................................... 18

    strstr .................................. ............................ 18

    tan ............................. ...................................... 6

    Terminating ................................................... 15

    time .............................................. ................. 21

    Time

    Converting .......................................... 20, 21

    Getting current......... ............................ 21

    Output ..................................... ........... 20, 21

    struct tm................ .................................... 20

    time_t .............................. ......................... 20

    Time functions ..................... ......................... 20

    asctime .................................... ................. 20

    localtime ................................................... 20

    mktime ............................ ......................... 21

    strftime ............................................... ...... 21

    time ...................... .................................... 21

    tolower .................................................... ........ 4

    toupper .................................................... ........ 4

    Trigonometric functions

    cos ...................................................... ........ 5

    sin. .............................................................. 6

    tan ............................................................... 6

    Types

    size_t .................................................. ...... 17

    struct tm................ .................................... 20

    time_t .............................. ......................... 20

    ungetc ............................................................ 14

    Whitespace .................................................... 12

    Ignoring .................................................... 12