Escolar Documentos
Profissional Documentos
Cultura Documentos
Appendix A1
Simplified C Standard Library
Reference
A1.1
A1.2
Introduction
This is a limited set of functions and constants from the C Standard Libraries. The
functions and constants given are relevant to an introductory programming course in
C/C++ using a procedural paradigm first approach.
Table of Contents
A1.1.
A1.2.
A1.3.
A1.4.
A1.5.
A1.6.
A1.7.
A1.8.
A1.3
A1.4
A1.5
A1.6
A1.7
A1.8
reading
writing
appending
char
%i or %d
int
%s
string
%u
unsigned int
%li or %D
long int
%lu or %U
%hi
short int
%hu
%f
float
%lf
double
%L
long double
%%
percentage symbol
A1.9
Field Width
Field width can be used to control the output format of expressions where a columnar
output is needed.
For Integers, Strings, and Single Characters
Placing a number between the % and format specifier for a format sequence will cause
the integer to be output right-justified in a field width with that number of spaces. For
example %3i will output numbers in a field width of 3 spaces. If the integer being
output is longer than the field width, the field width will be 'pushed out' to
accommodate 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 (number
of 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 will
output 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 cause fprintf()
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_WIDTH was defined
as the width of columns in a table, the value of int variable columnValue can
output as follows.
fprintf(outputStream, "%*i", COLUMN_WIDTH, columnValue);
Format Flags
Within the specified filed width the following controls can be added.
-
left justify
A1.10
Escape Sequences
Some characters cannot be created in a format string using the normal keyboard.
\a
\b
backspace
\f
formfeed
\n
newline
\r
carriage return
\t
tab
\"
double quotes
\\
backslash
char
%i or %d
int
%s
string
%u
unsigned int
%li or %D
long int
%lu or %U
%hi
short int
%hu
%f
float
%lf
double
%L
long double
%%
percentage symbol
A1.11
A1.12
Scansets
A scanset allows 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 format
specifier in a %s format sequence. It cannot be used to read in numbers or single
characters. 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, b or
c will be accepted. When any other character is encountered, no further characters
will be read into myString.
A negated scanset 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 the
negated scanset is encountered.
fscanf(inputStream, "%[^abc]", myString);
A practical application for a negated scanset is when reading in a line of text. By
allowing all characters except the newline character, input into a string will continue
until 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 %s format sequence (by placing an length in between the
% and the scanset). The following call to fscanf() will read characters into
myString until a newline character is met, or 19 characters 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 not
stored. For example to read in and ignore a character between two integers the
following call can be used. Note that the surrounding, non-ignored inputs correspond
to addresses given as subsequent arguments.
fscanf(inputStream, "%i%*c%i", &firstInt, &secondInt);
Whitespace
Whitespace includes spaces, tabs carriage returns and newline characters. When
reading any basic type, except single characters or scansets that allow whitespace,
whitespace is skipped before usable input.
Ignoring Whitespace
A1.13
including a single space character in a format sequence. For this reason \n, \t and
\r characters 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) achieves
fputc(characterToBeOutput,stdout).
int puts (const char *stringToOutput);
Writes the string stringToOutput to stdout, and appends a newline. Returns
non-negative (zero or positive) for success or EOF for 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 oldName to newName. Returns zero on success, non-zero on failure.
A1.14
A1.15
If
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 least
32767 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 unpredictable
random sequence the seed should be taken from a source of information outside the
computer, for instance the time that the user starts the program as shown below.
srand(time(NULL));
A1.17
A1.18
<0
>0
The difference for unequal strings is the difference in the ASCII codes of the first
different characters.
The following statement compares string1 and string2 to see if they contain the
same string.
if(strcmp(string1,string2)==0) { ...
int strncmp (
const char *string1,
const char *string2,
size_t numCharsToCompare
);
Compares the first numCharsToCompare characters string1 and string2
using 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 the
string strToSearch. If the character is not found NULL is 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 found NULL is
returned.
char *strstr (
const char *strToSearch,
const char *subStrToFind
);
Returns the address of (a pointer to) the first occurrence of subStrToFind in the
string strToSearch. If the substring is not found NULL is returned.
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 of
characters before (not including) the null at the end of the string.
The following statement outputs the length of stringToMeasure.
printf("%i\n", strlen(stringToMeasure));
A1.20
//
//
//
//
//
//
//
//
//
//
//
char *__tm_zone; //
int __tm_gmtoff; //
Seconds 0-59
Minutes 0-59
Hours 0-23
Day of month 1-31
Month of year 0-11
Years since 1900 (eg 2006=106)
Day of week (Sun=0 Sat=6)
Day of year (0-366)
Daylight savings flag (0 if
in not effect, >0 if in
effect, <0 if unknown)
Timezone string (start is 2 _s)
Offset to GMT (start 2 _s)
};
char *asctime (const struct tm *timeStructPtr);
Returns a pointer to a string containing the time indicated by the information in the
tm structure pointed to by timeStructPtr using the following standard format.
Day Mon DD HH:mm:ss YYYY\n
For example
Sat Oct 21 23:59:59 2006\n
The following outputs the current time in the standard format.
time_t currentUnixTime = time();
printf("%s", asctime(localtime(¤tUnixTime)));
struct tm *localtime (const time_t *timePtr);
Returns a pointer to a structure containing time information according to the time
given in the variable pointed to by timePtr.
A1.21
The following call creates a time structure with the current time information.
time_t currentUnixTime = time();
tm currentTimeStruct = *localtime(¤tUnixTime);
time_t mktime (struct tm *timeStructPtr);
Returns a Unix time of type time_t based on the information in the structure
variable pointed to by timeStructPtr. The first six members of the tm structure
(tm_sec, tm_min, tm_hour, tm_mday, tm_mon and tm_year) should and this
function will fill in the remaining members of the structure. Time-zone information is
gathered 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 timePtr is not NULL the time is also assigned to
the 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 to
a specified format. The string is stored in stringToWriteTimeTo and will
limit the string length to capacityOfString characters.
A1.22
Format Sequences
The following format sequences can be used to describe the time format.
%a
%A
%b or %h
%B
%D
Equivalent to %m / %d / %y
%e
%F
Equivalent to %Y - %m - %d
%H
%I
%j
%m
%M
%n
A newline character
%p
%r
Equivalent to %I : %M : %S %p
%R
%S
%t
%T
Equivalent to %H : %M : %S
%u
%U
%w
%W
%y or %C
%Y
%z
%Z
%%
Percentage symbol
A1.23
A1.24
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
template
this
throw
true
try
typedef
typeid
typename
union
unsigned
using
virtual
void
volatile
wchar_t
while
xor
xor_eq
Character
null \0
bell sound \a
backspace \b
horizontal tab \t
newline \n
carriage return \r
space
!
"
#
$
%
&
'
(
)
*
+
,
.
/
0
1
2
3
4
5
6
7
8
9
:
;
<
Code
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
Character
=
>
?
@
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
[
\
]
^
_
Code
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
Character
`
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
{
|
}
~
A1.25
A1.26
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
A1.27
atol ................................................................ 15
ceil .................................................................. 5
isalnum ...................................................... 3
fclose .......................................................... 7
isalpha ........................................................ 3
feof ............................................................. 7
isdigit ......................................................... 3
fopen .......................................................... 8
islower ....................................................... 3
Files
isspace........................................................ 4
Closing ....................................................... 7
isupper ....................................................... 4
Deleting .................................................... 13
tolower ....................................................... 4
toupper ....................................................... 4
Opening ...................................................... 8
Check if character is
Renaming ................................................. 13
a letter ........................................................ 3
floor................................................................. 5
a letter or digit............................................ 3
fopen ............................................................... 8
Format Sequences
Input ........................................................... 8
Output ...................................................... 11
Convert a letter to
fprintf .............................................................. 8
fputc .............................................................. 10
fputs .............................................................. 10
Converting
fscanf............................................................. 10
getc ................................................................ 13
getchar ........................................................... 13
Input
cos................................................................... 5
Controlled string....................................... 12
EOF ................................................................ 7
Ignoring .................................................... 12
exit ................................................................ 15
exp .................................................................. 5
Scansets .................................................... 12
fabs ................................................................. 5
fclose .............................................................. 7
Strings ........................................................ 7
feof ................................................................. 7
Whitespace ............................................... 12
fgetc ................................................................ 7
fgets ................................................................ 7
fgetc............................................................ 7
fgets ............................................................ 7
fscanf ........................................................ 10
getc ........................................................... 13
A1.28
getchar ..................................................... 13
printf ..................................................... 8, 13
rewind ...................................................... 14
putc ........................................................... 13
scanf ......................................................... 14
putchar ...................................................... 13
ungetc ...................................................... 14
puts ........................................................... 13
isalnum ........................................................... 3
rewind....................................................... 14
isalpha............................................................. 3
pow ................................................................. 6
isdigit .............................................................. 3
Power .............................................................. 6
islower ............................................................ 3
printf ............................................................. 13
isspace ............................................................ 4
Programs
isupper ............................................................ 4
Terminating .............................................. 15
localtime ....................................................... 20
putc ............................................................... 13
log ................................................................... 5
putchar .......................................................... 13
log10 ............................................................... 5
puts ................................................................ 13
rand ............................................................... 16
abs ............................................................ 15
ceil ............................................................. 5
rand .......................................................... 16
cos .............................................................. 5
srand ......................................................... 16
exp ............................................................. 5
Random numbers
fabs ............................................................ 5
getting....................................................... 16
floor ........................................................... 5
seeding ..................................................... 16
log .............................................................. 5
remove .......................................................... 13
log10 .......................................................... 5
rename ........................................................... 13
pow. ........................................................... 6
sin. ............................................................. 6
rewind ........................................................... 14
sqrt ............................................................. 6
Rounding numbers
tan .............................................................. 6
down ........................................................... 5
mktime .......................................................... 21
up................................................................ 5
Output
scanf .............................................................. 14
Scanset .......................................................... 12
Backslash ................................................. 10
sin 6
Newline .................................................... 10
sprintf ............................................................ 14
Quotes ...................................................... 10
sqrt .................................................................. 6
Square Root..................................................... 6
srand .............................................................. 16
Tab ........................................................... 10
sscanf ............................................................ 14
strcat .............................................................. 17
strchr ............................................................. 18
strcmp ........................................................... 18
fputc ......................................................... 10
strcpy............................................................. 17
fputs ......................................................... 10
strftime .......................................................... 21
A1.29
strstr .............................................................. 18
sprintf ....................................................... 14
tan ................................................................... 6
sscanf ....................................................... 14
Terminating ................................................... 15
strcat ........................................................ 17
time ............................................................... 21
strchr ........................................................ 18
Time
strcmp ...................................................... 18
strcpy ....................................................... 17
strlen ........................................................ 19
strncat ...................................................... 17
struct tm.................................................... 20
strncmp .................................................... 18
time_t ....................................................... 20
strncpy ..................................................... 17
strrchr ....................................................... 18
asctime ..................................................... 20
strstr ......................................................... 18
localtime ................................................... 20
Strings
mktime ..................................................... 21
strftime ..................................................... 21
Assigning ................................................. 17
time .......................................................... 21
Comparing ............................................... 18
tolower ............................................................ 4
Concatenating .......................................... 17
toupper ............................................................ 4
Trigonometric functions
Copying ................................................... 17
cos .............................................................. 5
sin. .............................................................. 6
tan ............................................................... 6
Types
Length of.............................................. 19
size_t ........................................................ 17
strlen ............................................................. 19
struct tm.................................................... 20
strncat ........................................................... 17
time_t ....................................................... 20
strncmp ......................................................... 18
ungetc ............................................................ 14
strncpy .......................................................... 17
Whitespace .................................................... 12
strrchr ........................................................... 18
Ignoring .................................................... 12