About & Overview
This ANSI-C helper collection is compiled from various different sources found on the internet, in particular:
-
C Programming Reference by Martin Leslie (german translation)
-
The C Library Reference Guide by Eric Hus
-
IBM Public Information Center
The examples were tested on Fedora using the GNU C-Compiler.
There are a lost of dirty implemented examples. Several functions from the standard are missing. |
For comments and feedback feel free to contact me at: martin[at]horauer.at, http://www.horauer.at
#include <assert.h>
-
assert - Abort the program if assertion is false.
#include <ctype.h>
-
isalnum - Checks whether a character is alphanumeric (A-Z, a-z, 0-9)
-
isalpha - Checks whether a character is alphabetic (A-Z, a-z )
-
iscntrl - Checks whether a character is a control character or delete ( decimal 0-31 and 127)
-
isdigit - Checks whether a character is a digit (0-9)
-
isgraph - Checks whether a character is a printable character, excluding the space (decimal 32)
-
islower - Checks whether a character is a lower case letter (a-z).
-
isprint - Checks whether a character is printable (decimal 32-126).
-
ispunct - Checks whether a character is punctuation (decimal 32-47, 58-63, 91-96, 123-126)
-
isspace - Checks whether a character is white space - space, CR HT VT NL, FF.
-
isupper - Checks whether a character is an upper case letter (A-Z).
-
isxdigit - Checks whether a character is hex digit (0-9, A-F, a-f).
-
tolower - Convert an uppercase character to lowercase.
-
toupper - Converts a lowercase character to uppercase.
#include <errno.h>
-
errno - The number of the last error.
#include <float.h>
-
float - Determine properties of floating-point type representations.
#include <limits.h>
-
limits - Determine various properties of integer type representations.
#include <locale.h>
-
setlocale - Determine various properties required for different locales (e.g. currencies, special characters, etc.).
#include <math.h>
You also need to link against the math library using -lm .
|
-
acos - Calculate arccosine
-
asin - Calculate arcsine
-
atan - Calculate arctangent
-
atan2 - Calculate arctangent, 2 parameters
-
ceil - Return the smallest integer that is greater or equal to x
-
cos - Calculate cosine
-
cosh - Calculate hyperbolic cosine
-
exp - Calculate exponential
-
fabs - Return absolute value of floating-point
-
floor - Round down value
-
fmod - Return remainder of floating point division
-
frexp - Get mantissa and exponent of floating-point value
-
ldexp - Get floating-point value from mantissa and exponent
-
log - Calculate natural logarithm
-
log10 - Calculate logarithm base 10
-
modf - Split floating-point value into fractional and integer parts
-
pow - Calculate numeric power
-
sin - Calculate sine
-
sinh - Calculate hyperbolic sine
-
sqrt - Calculate square root
-
tan - Calculate tangent
-
tanh - Calculate hyperbolic tangent
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
-
stdarg - Macros for dealing with variable argument lists.
#include <stddef.h>
-
stddef - Dealing with several different standard definitions.
#include <stdio.h>
-
clearerr - Reset error indicators.
-
fclose - Close a file.
-
feof - Check for EOF while reading a file.
-
ferror - Check for errors.
-
fflush - Flush a stream.
-
fgetc - Get next character from a stream.
-
fgetpos - Get position in a stream.
-
fgets - Get string from a stream.
-
fopen - Open a file.
-
fprintf - Print formatted data to a stream.
-
fputc - Write character to a stream.
-
fputchar - Write character to STDOUT.
-
fputs - Write string to a stream.
-
fread - Read block of data from a stream.
-
freopen - Reopen a file using a different file mode.
-
fscanf - Read formatted data from a stream.
-
fseek - Reposition stream’s position indicator.
-
fsetpos - Reposition file pointer to a saved location.
-
ftell - Return the current position of the file pointer.
-
fwrite - Write block of data to a stream.
-
getc - Get the next character.
-
getchar - Get the next character from STDIN.
-
perror - Print an error message.
-
printf - Print formatted data to STDOUT.
-
putc - Write character to a stream.
-
putchar - Write character to STDOUT.
-
puts - Write a string to STDOUT.
-
remove - Delete a file.
-
rename - Rename a file or directory.
-
rewind - Reposition file pointer to the beginning of a stream.
-
scanf - Read formatted data from STDIN.
-
setbuf - Change stream buffering.
-
setvbuf - Change stream buffering.
-
sprintf - Format data to a string.
-
snprintf - Format data to a string.
-
sscanf - Read formatted data from a string.
-
tmpfile - Open a temporary file.
-
tmpnam - Generate a unique temporary filename.
-
ungetc - Push a character back into stream.
-
vfprintf - Sends formatted output to a stream using an argument list.
-
vprintf - Sends formatted output to STDOUT using an argument list.
-
vspnrintf - Sends formatted output to an array using an argument list.
-
vsprintf - Sends formatted output to a string using an argument list.
-
vfscanf - Format file input of a standard argument list.
-
vscanf - Format STDIN input of a standard argument list.
-
vsscanf - Format string input of a standard argument list.
#include <stdlib.h>
-
abort - Abort current process returning error code
-
abs - Return, absolute value of integer parameter
-
atexit - Specifies a function to be executed at exit
-
atof - Convert string to double
-
atoi - Convert string to integer
-
atol - Convert string to long
-
bsearch - Binary search
-
calloc - Allocate array in memory
-
div - Divide two integer values
-
ldiv - Divide two long integer values
-
exit - Terminate calling process
-
free - Deallocate dynamically allocated memory
-
getenv - Get string from environment
-
labs - Return absolute calue of long integer parameter
-
malloc - Allocate memory block
-
mblen - Determine the number of bytes in a character
-
mbstowcs - Convert a multibyte string to a wide character string
-
mbtowc - Convert a multibyte character to a wide character
-
qsort - Sort using quicksort algorithm
-
rand - Generate random number
-
realloc - Reallocate memory block
-
srand - Initialize random number generator
-
strtod - Convert string to double-precision floating-point value
-
strtol - Convert string to long integer
-
strtoul - Convert string to unsigned long integer
-
system - Execute command
-
wcstombs - Convert a wide character string to a multibyte character string
-
wctomb - Convert a wide character to a multibyte character
#include <string.h>
-
memchr - Search buffer for a character
-
memcmp - Compare two buffers
-
memcpy - Copy bytes to buffer from buffer
-
memmove - Copy bytes to buffer from buffer
-
memset - Fill buffer with specified character
-
strcat - Append string
-
strchr - Find character in string
-
strcmp - Compare two strings
-
strcoll - Compare two strings using locale settings
-
strcpy - Copy string
-
strcspn - Search string for occurrence of charcter set
-
strerror - Get pointer to error message string
-
strlen - Return string length
-
strncat - Append substring to string
-
strncmp - Compare some characters of two strings
-
strncpy - Copy characters from one string to another
-
strpbrk - Scan string for specified characters
-
strrchr - Find last occurrence of character in string
-
strspn - Get length of substring composed of given characters
-
strstr - Find substring
-
strtok - Sequentially truncate string if delimiter is found
-
strxfrm - Transform string using locale settings
#include <time.h>
-
asctime - Convert tm structure to string
-
clock - Return number of clock ticks since process start
-
ctime - Convert time_t value to string
-
difftime - Return difference between two times
-
gmtime - Convert time_t value to tm structure as UTC time
-
localtime - Convert time_t value to tm structure as local time
-
mktime - Convert tm structure to time_t value
-
strftime - Format date and time
-
time - Get current time
ASCII Table
assert.h
assert
- NAME
-
assert - Abort the program if assertion is false.
- SYNOPSIS
#include <assert.h>
void assert (scalar expression);
- DESCRIPTION
-
The assert macro allows diagnostic information to be written to the standard error file. If expression evaluates to 0 (false), then the expression, source code file name, and line number are sent to the standard error, and then calls the
abort
to terminate the function. If the identifierNDEBUG
("no debug") is defined with#define NDEBUG
then the macro assert does nothing. - RETURN VALUE
-
No value is returned.
- SEE ALSO
-
exit
,abort
- EXAMPLE
#include <assert.h>
#include <stdlib.h>
void open_record(char *record_name)
{
assert(record_name!=NULL);
/* Rest of the code */
}
int main(int argc, char *argv[])
{
assert(argc==2 && argv[1][0]=='1');
open_record(NULL);
return 0;
}
- OUTPUT
$ gcc -Wall assert.c $ ./a.out a.out: assert.c:12: main: Assertion `argc==2 && argv[1][0]=='1'' failed. Aborted $ ./a.out 21 a.out: assert.c:12: main: Assertion `argc==2 && argv[1][0]=='1'' failed. Aborted $ ./a.out 1 a.out: assert.c:6: open_record: Assertion `record_name!=((void *)0)' failed. Aborted
ctype.h
isalnum
#include <ctype.h>
int isalnum (char c);
- DESCRIPTION
-
The
isalnum
function testsc
to determine if it is an alphanumeric character ('A'-'Z', 'a'-'z', '0'-'9'
). - RETURN VALUE
-
The isalnum function returns a value of 1 if
c
is an alphanumeric character or a value of 0 if it is not. - SEE ALSO
-
isalpha
,iscntrl
,isdigit
,isgraph
,islower
,isprint
,ispunct
,isspace
,isupper
,isxdigit
- EXAMPLE
#include <ctype.h>
#include <stdio.h>
int main (void)
{
unsigned char i;
char *p;
for (i = 45; i < 50; i++) {
p = (isalnum (i) ? "YES" : "NO");
printf ("isalnum (%c) %s\n", i, p);
}
return 0;
}
- OUTPUT
$ gcc -Wall isalnum.c $ ./a.out isalnum (-) NO isalnum (.) NO isalnum (/) NO isalnum (0) YES isalnum (1) YES
isalpha
#include <ctype.h>
int isalpha (char c);
- DESCRIPTION
-
The
isalpha
function testsc
to determine if it is an alphabetic character ('A'-'Z'
or'a'-'z'
). - RETURN VALUE
-
The
isalpha
function returns a value of 1 ifc
is an alphabetic character and a value of 0 if it is not. - SEE ALSO
-
isalnum
,iscntrl
,isdigit
,isgraph
,islower
,isprint
,ispunct
,isspace
,isupper
,isxdigit
- EXAMPLE
#include <ctype.h>
#include <stdio.h>
int main (void)
{
unsigned char i;
char *p;
for (i = 63; i < 67; i++) {
p = (isalpha (i) ? "YES" : "NO");
printf ("isalpha (%c) %s\n", i, p);
}
return 0;
}
- OUTPUT
$ gcc -Wall isalpha.c $ ./a.out isalpha (?) NO isalpha (@) NO isalpha (A) YES isalpha (B) YES
iscntrl
#include <ctype.h>
int iscntrl (char c);
- DESCRIPTION
-
The
iscntrl
function testsc
to determine if it is a control character (0x00-0x1F or 0x7F). - RETURN VALUE
-
The
iscntrl
function returns a value of 1 ifc
is a control character and a value of 0 if it is not. - SEE ALSO
-
isalnum
,isalpha
,isdigit
,isgraph
,islower
,isprint
,ispunct
,isspace
,isupper
,isxdigit
- EXAMPLE
#include <ctype.h>
#include <stdio.h>
int main (void)
{
unsigned char i;
char *p;
for (i = 30; i < 34; i++) {
p = (iscntrl (i) ? "YES" : "NO");
printf ("iscntrl (%i) %s\n", i, p);
}
return 0;
}
- OUTPUT
$ gcc -Wall iscntrl.c $ ./a.out iscntrl (30) YES iscntrl (31) YES iscntrl (32) NO iscntrl (33) NO
isdigit
#include <ctype.h>
int isdigit (char c);
- DESCRIPTION
-
The
isdigit
function testsc
to determine if it is a decimal digit ('0'-'9'
). - RETURN VALUE
-
The
isdigit
function returns a value of 1 ifc
is a decimal digit and a value of 0 if it is not. - SEE ALSO
-
isalnum
,isalpha
,iscntrl
,isgraph
,islower
,isprint
,ispunct
,isspace
,isupper
,isxdigit
- EXAMPLE
#include <ctype.h>
#include <stdio.h>
int main (void)
{
unsigned char i;
char *p;
for (i = 46; i < 50; i++) {
p = (isdigit (i) ? "YES" : "NO");
printf ("isdigit (%c) %s\n", i, p);
}
return 0;
}
- OUTPUT
$ gcc -Wall isdigit.c $ ./a.out isdigit (.) NO isdigit (/) NO isdigit (0) YES isdigit (1) YES
isgraph
#include <ctype.h>
int isgraph (char c);
- DESCRIPTION
-
The
isgraph
function testsc
to determine if it is a printable character (not including space). The character values tested for are 0x21-0x7E. - RETURN VALUE
-
The
isgraph
function returns a value of 1 ifc
is a printable character and a value of 0 if it is not. - SEE ALSO
-
isalnum
,isalpha
,iscntrl
,isdigit
,islower
,isprint
,ispunct
,isspace
,isupper
,isxdigit
- EXAMPLE
#include <ctype.h>
#include <stdio.h>
int main (void)
{
unsigned char i;
char *p;
for (i = 32; i < 34; i++) {
p = (isgraph (i) ? "YES" : "NO");
printf ("isgraph (%c) %s\n", i, p);
}
return 0;
}
- OUTPUT
$ gcc -Wall isgraph.c $ ./a.out isgraph ( ) NO isgraph (!) YES
islower
#include <ctype.h>
int islower (char c);
- DESCRIPTION
-
The
islower
function testsc
to determine if it is a lowercase alphabetic character ('a'-'z'
). - RETURN VALUE
-
The
islower
function returns a value of 1 ifc
is a lowercase letter and a value of 0 if it is not. - SEE ALSO
-
isalnum
,isalpha
,iscntrl
,isdigit
,isgraph
,isprint
,ispunct
,isspace
,isupper
,isxdigit
- EXAMPLE
#include <ctype.h>
#include <stdio.h>
int main (void)
{
unsigned char i;
char *p;
for (i = 95; i < 99; i++) {
p = (islower (i) ? "YES" : "NO");
printf ("islower (%c) %s\n", i, p);
}
return 0;
}
- OUTPUT
$ gcc -Wall islower.c $ ./a.out islower (_) NO islower (`) NO islower (a) YES islower (b) YES
isprint
#include <ctype.h>
int isprint (char c);
- DESCRIPTION
-
The
isprint
function testsc
to determine if it is a printable character (0x20-0x7E). - RETURN VALUE
-
The
isprint
function returns a value of 1 ifc
is a printable character and a value of 0 if it is not. - SEE ALSO
-
isalnum
,isalpha
,iscntrl
,isdigit
,isgraph
,islower
,ispunct
,isspace
,isupper
,isxdigit
- EXAMPLE
#include <ctype.h>
#include <stdio.h>
int main (void)
{
unsigned char i;
char *p;
for (i = 30; i < 34; i++) {
p = (isprint (i) ? "YES" : "NO");
printf ("isprint (%i) %s\n", i, p);
}
return 0;
}
- OUTPUT
$ gcc -Wall isprint.c $ ./a.out isprint (30) NO isprint (31) NO isprint (32) YES isprint (33) YES
ispunct
#include <ctype.h>
int ispunct (char c);
- DESCRIPTION
-
The
ispunct
function testsc
to determine if it is a punctuation character. The following symbols are punctuation characters:! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
- RETURN VALUE
-
The
ispunct
function returns a value of 1 ifc
is a punctuation character and a value of 0 if it is not. - SEE ALSO
-
isalnum
,isalpha
,iscntrl
,isdigit
,isgraph
,islower
,isprint
,isspace
,isupper
,isxdigit
- EXAMPLE
#include <ctype.h>
#include <stdio.h>
int main (void)
{
unsigned char i;
char *p;
for (i = 95; i < 99; i++) {
p = (ispunct (i) ? "YES" : "NO");
printf ("ispunct (%c) %s\n", i, p);
}
return 0;
}
- OUTPUT
$ gcc -Wall ispunct.c $ ./a.out ispunct (_) YES ispunct (`) YES ispunct (a) NO ispunct (b) NO
isspace
#include <ctype.h>
int isspace(char c);
- DESCRIPTION
-
The
isspace
function testsc
to determine if it is a whitespace character (0x09-0x0D or 0x20). - RETURN VALUE
-
The
isspace
function returns a value of 1 ifc
is a whitespace character and a value of 0 if it is not. - SEE ALSO
-
isalnum
,isalpha
,iscntrl
,isdigit
,isgraph
,islower
,isprint
,ispunct
,isupper
,isxdigit
- EXAMPLE
#include <ctype.h>
#include <stdio.h>
int main (void)
{
unsigned char i;
char *p;
for (i = 32; i < 34; i++) {
p = (isspace (i) ? "YES" : "NO");
printf ("isspace (%c) %s\n", i, p);
}
return 0;
}
- OUTPUT
$ gcc -Wall isspace.c $ ./a.out isspace ( ) YES isspace (!) NO
isupper
#include <ctype.h>
int isupper(char c);
- DESCRIPTION
-
The
isupper
function testsc
to determine if it is an uppercase alphabetic character ('A'-'Z'
). - RETURN VALUE
-
The
isupper
function returns a value of 1 ifc
is an uppercase character and a value of 0 if it is not. - SEE ALSO
-
isalnum
,isalpha
,iscntrl
,isdigit
,isgraph
,islower
,isprint
,ispunct
,isspace
,isxdigit
- EXAMPLE
#include <ctype.h>
#include <stdio.h>
int main (void)
{
unsigned char i;
char *p;
for (i = 89; i < 93; i++) {
p = (isupper (i) ? "YES" : "NO");
printf ("isupper (%c) %s\n", i, p);
}
return 0;
}
- OUTPUT
$ gcc -Wall isupper.c $ ./a.out isupper (Y) YES isupper (Z) YES isupper ([) NO isupper (\) NO
isxdigit
#include <ctype.h>
int isxdigit(char c);
- DESCRIPTION
-
The
isxdigit
function testsc
to determine if it is a hexadecimal digit ('A'-'Z', 'a'-'z', '0'-'9'
). - RETURN VALUE
-
The
isxdigit
function returns a value of 1 ifc
is a hexadecimal digit and a value of 0 if it is not. - SEE ALSO
-
isalnum
,isalpha
,iscntrl
,isdigit
,isgraph
,islower
,isprint
,ispunct
,isspace
,isupper
- EXAMPLE
#include <ctype.h>
#include <stdio.h>
int main (void)
{
unsigned char i;
char *p;
for (i = 101; i < 105; i++) {
p = (isxdigit (i) ? "YES" : "NO");
printf ("isxdigit (%c) %s\n", i, p);
}
return 0;
}
- OUTPUT
$ gcc -Wall isxdigit.c $ ./a.out isxdigit (e) YES isxdigit (f) YES isxdigit (g) NO isxdigit (h) NO
tolower
- NAME
-
tolower - convert a character to its lower-case pendant.
- SYNOPSIS
#include <ctype.h>
int tolower (int c);
- DESCRIPTION
-
The
tolower
function convertsc
to a lowercase character. Ifc
is not an alphabetic letter, thetolower
function has no effect. - RETURN VALUE
-
The
tolower
function returns the lowercase equivalent ofc
. - SEE ALSO
-
toupper
The details of what constitutes an uppercase or lowercase letter depend on the current locale. For example, the default "C" locale does not know about "umlauts", so no conversion is done for them. In some non - English locales, there are lowercase letters with no corresponding uppercase equivalent; the German "sharp s" is one example. |
- EXAMPLE
#include <ctype.h>
#include <stdio.h>
int main (void)
{
unsigned char i;
for (i = 'A'; i < 'D'; i++) {
printf ("tolower(%c) = %c\n", i, tolower(i));
}
return 0;
}
- OUTPUT
$ gcc -Wall tolower.c $ ./a.out tolower(A) = a tolower(B) = b tolower(C) = c
VARIANT _tolower
#define _tolower(c) ((c) - 'A' + 'a')
- DESCRIPTION
-
The above
_tolower
macro is a simpler version oftolower
that can be used whenc
is known to be an uppercase character. - RETURN VALUE
-
The
_tolower
macro returns a lowercase character. - EXAMPLE
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char k = 'A';
putchar(k);
if (isupper (k))
k = _tolower (k);
putchar(k);
putchar('\n');
return EXIT_SUCCESS;
}
- OUTPUT
$ gcc -Wall tolower2.c $ ./a.out Aa
toupper
- NAME
-
tolower - convert a character to its upper-case pendant.
- SYNOPSIS
#include <ctype.h>
int toupper (int c);
- DESCRIPTION
-
The
toupper
function convertsc
to an uppercase character. Ifc
is not an alphabetic letter, thetoupper
function has no effect. - RETURN VALUE
-
The
toupper
function returns the uppercase equivalent ofc
. - SEE ALSO
-
tolower
The details of what constitutes an uppercase or lowercase letter depend on the current locale. For example, the default "C" locale does not know about "umlauts", so no conversion is done for them. In some non - English locales, there are lowercase letters with no corresponding uppercase equivalent; the German "sharp s" is one example. |
- EXAMPLE
#include <ctype.h>
#include <stdio.h>
int main (void)
{
unsigned char i;
for (i = 95; i < 99; i++) {
printf ("toupper(%c) = %c\n", i, toupper(i));
}
return 0;
}
- OUTPUT
$ gcc -Wall toupper.c $ ./a.out toupper(_) = _ toupper(`) = ` toupper(a) = A toupper(b) = B
VARIANT _toupper
#define _toupper(c) ((c) - 'a' + 'A')
- DESCRIPTION
-
The above
_toupper
macro is a simpler version oftoupper
that can be used when c is known to be a lowercase character. - RETURN VALUE
-
The
_toupper
macro returns an uppercase character. - EXAMPLE
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char k = 'a';
putchar(k);
if (islower (k))
k = _toupper(k);
putchar(k);
putchar('\n');
return EXIT_SUCCESS;
}
- OUTPUT
$ gcc -Wall toupper2.c $ ./a.out aA
errno.h
errno
- NAME
-
errno - number of last error
- SYNOPSIS
#include <errno.h>
extern int errno;
- DESCRIPTION
-
The integer
errno
is set by system calls (and some library functions) to indicate what went wrong. Its value is significant only when the call returned an error (usually -1), and a library function that does succeed is allowed to changeerrno
.
Sometimes, when -1 is also a legal return value one has to zero
errno
before the call in order to detect possible errors.
errno
is defined by the ISO C standard to be a modifiable lvalue of
type int, and must not be explicitly declared; errno
may be a
macro. errno
is thread-local; setting it in one thread does not
affect its value in any other thread.
Valid error numbers are all non-zero; errno
is never set to zero by
any library function. All the error names specified by POSIX.1 must
have distinct values.
POSIX.1 (1996 edition) lists the following symbolic error names. Of these, EDOM and ERANGE are in the ISO C standard. ISO C Amendment 1 defines the additional error number EILSEQ for coding errors in multi- byte or wide characters.
E2BIG - Arg list too long EACCES - Permission denied EAGAIN - Resource temporarily unavailable EBADF - Bad file descriptor EBADMSG - Bad message EBUSY - Resource busy ECANCELED - Operation canceled ECHILD - No child processes EDEADLK - Resource deadlock avoided EDOM - Domain error EEXIST - File exists EFAULT - Bad address EFBIG - File too large EINPROGRESS - Operation in progress EINTR - Interrupted function call EINVAL - Invalid argument EIO - Input/output error EISDIR - Is a directory EMFILE - Too many open files EMLINK - Too many links EMSGSIZE - Inappropriate message buffer length ENAMETOOLONG - Filename too long ENFILE - Too many open files in system ENODEV - No such device ENOENT - No such file or directory ENOEXEC - Exec format error ENOLCK - No locks available ENOMEM - Not enough space ENOSPC - No space left on device ENOSYS - Function not implemented ENOTDIR - Not a directory ENOTEMPTY - Directory not empty ENOTSUP - Not supported ENOTTY - Inappropriate I/O control operation ENXIO - No such device or address EPERM - Operation not permitted EPIPE - Broken pipe ERANGE - Result too large EROFS - Read-only file system ESPIPE - Invalid seek ESRCH - No such process ETIMEDOUT - Operation timed out EXDEV - Improper link
- SEE ALSO
-
perror
,strerror
- EXAMPLE
#include <stdio.h>
#include <string.h>
void print_errs(void);
int main(void)
{
print_errs();
return 0;
}
void print_errs(void)
{
int i;
for( i = 0; i < sys_nerr; i++ ) {
printf( "Error #%3d: %s\n", i, strerror(i) );
}
}
- OUTPUT
$ gcc -Wall errno.c $ ./a.out Error # 0: Success Error # 1: Operation not permitted Error # 2: No such file or directory Error # 3: No such process Error # 4: Interrupted system call Error # 5: Input/output error Error # 6: No such device or address Error # 7: Argument list too long Error # 8: Exec format error Error # 9: Bad file descriptor Error # 10: No child processes Error # 11: Resource temporarily unavailable ...
floats.h
float.h
Include the standard header float.h
to determine various properties of floating-point type representations.
Some target environments can change the rounding and error-reporting properties of floating-point type representations while the program is running.
Where the prefix "FLT" pertains to type float, "DBL" to type double, and "LDBL" to type long double:
FLT_RADIX - radix of floating-point representations FLT_ROUNDS - floating-point rounding mode FLT_DIG DBL_DIG LDBL_DIG - precision (in decimal digits) FLT_EPSILON DBL_EPSILON LDBL_EPSILON - smallest number x such that 1.0 + x != 1.0 FLT_MANT_DIG DBL_MANT_DIG LDBL_MANT_DIG - number of digits, base FLT_RADIX, in mantissa FLT_MAX DBL_MAX LDBL_MAX - maximum number FLT_MAX_EXP DBL_MAX_EXP LDBL_MAX_EXP - largest positive integer exponent to which FLT_RADIX can be raised and remain representable FLT_MIN DBL_MIN LDBL_MIN - minimum normalised number FLT_MIN_EXP DBL_MIN_EXP LDBL_MIN_EXP - smallest negative integer exponent to which FLT_RADIX can be raised and remain representable
limits.h
limits
- DESCRIPTION
-
Include the standard header
limits.h
to determine various properties of the integer type representations, e.g.:
CHAR_BIT - number of bits in a char CHAR_MAX - maximum value of type char CHAR_MIN - minimum value of type char SCHAR_MAX - maximum value of type signed char SCHAR_MIN - minimum value of type signed char UCHAR_MAX - maximum value of type unsigned char SHRT_MAX - maximum value of type short SHRT_MIN - minimum value of type short USHRT_MAX - maximum value of type unsigned short INT_MAX - maximum value of type int INT_MIN - minimum value of type int UINT_MAX - maximum value of type unsigned int LONG_MAX - maximum value of type long LONG_MIN - minimum value of type long ULONG_MAX - maximum value of type unsigned long
locale.h
setlocale
- NAME
-
setlocale - set the current locale.
- SYNOPSIS
#include <locale.h>
char *setlocale(int category, const char * locale);
- DESCRIPTION
-
The
setlocale()
function is used to set or query the program’s current locale. If locale is "C" or "POSIX", the current locale is set to the portable locale.
If locale is "", the locale is set to the default locale which is selected from the environment variable LANG.
On startup of the main program, the portable "C" locale is selected as default.
The argument category determines which functions are influenced by the new locale:-
LC_ALL - for all of the locale.
-
LC_COLLATE - for the functions
strcoll()
andstrxfrm()
. -
LC_CTYPE - for the character classification and conversion routines.
-
LC_MONETARY - for
localeconv()
. -
LC_NUMERIC - for the decimal character.
-
LC_TIME - for
strftime()
. -
NULL if the request cannot not be honored. This string may be allocated in static storage.
-
A program may be made portable to all locales by calling setlocale(LC_ALL, "" )
after program
initialization, by using the values returned from a localeconv()
call for locale - dependent information and by using strcoll()
or strxfrm()
functions to compare strings.
- EXAMPLE
-
A code snippet similar to the following one can be used to change the locale or a portion thereof for a limited duration:
#include <stdio.h>
#include <time.h>
#include <locale.h>
int main (void)
{
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
struct lconv * lc;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
int twice=0;
do {
printf ("Locale is: %s\n", setlocale(LC_ALL,NULL) );
strftime (buffer,80,"%c",timeinfo);
printf ("Date is: %s\n",buffer);
lc = localeconv ();
printf ("Currency symbol is: %s\n-\n",lc->currency_symbol);
setlocale (LC_ALL,"");
} while (!twice++);
return 0;
}
- OUTPUT
$ gcc -Wall setlocale.c $ ./a.out Locale is: C Date is: Sun Sep 9 20:06:35 2012 Currency symbol is: - Locale is: en_US.utf8 Date is: Sun 09 Sep 2012 08:06:35 PM CEST Currency symbol is: $ -
math.h
acos
- NAME
-
acos - arc cosine function.
- SYNOPSIS
#include <math.h>
double acos(double x);
- DESCRIPTION
-
The
acos()
function calculates the arc cosine of x; that is the value whose cosine is x. If x falls outside the range -1 to 1, acos() fails and errno is set.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
The
acos()
function returns the arc cosine in radians and the value is mathematically defined to be between 0 and PI (inclusive). - ERRORS
-
EDOM
- x is out of range [-1, 1]. - SEE ALSO
-
asin
,atan
,atan2
,cos
,sin
,tan
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
float x;
float y;
for (x = -1.0; x <= 1.0; x = x + 0.1) {
y = acos(x);
printf ("ACOS(%f) = %f\n", x, y);
}
return 0;
}
- OUTPUT
$ gcc -Wall -lm acos.c $ ./a.out ACOS(-1.000000) = 3.141593 ACOS(-0.900000) = 2.690566 ACOS(-0.800000) = 2.498091 ACOS(-0.700000) = 2.346194 ACOS(-0.600000) = 2.214297 ACOS(-0.500000) = 2.094395 ACOS(-0.400000) = 1.982313 ACOS(-0.300000) = 1.875489 ACOS(-0.200000) = 1.772154 ACOS(-0.100000) = 1.670964 ACOS(0.000000) = 1.570796 ACOS(0.100000) = 1.470629 ACOS(0.200000) = 1.369438 ACOS(0.300000) = 1.266104 ACOS(0.400000) = 1.159279 ACOS(0.500000) = 1.047197 ACOS(0.600000) = 0.927295 ACOS(0.700000) = 0.795399 ACOS(0.800000) = 0.643501 ACOS(0.900000) = 0.451026
asin
- NAME
-
asin - arc sine function.
- SYNOPSIS
#include <math.h>
double asin(double x);
- DESCRIPTION
-
The
asin()
function calculates the arc sine ofx
; that is the value whose sine is x. If x falls outside the range -1 to 1,asin()
fails and errno is set.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
The
asin()
function returns the arc sine in radians and the value is mathematically defined to be between -PI/2 and PI/2 (inclusive). - ERRORS
-
EDOM - x is out of range [-1, 1].
- SEE ALSO
-
acos
,atan
,atan2
,cos
,sin
,tan
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
float x;
float y;
for (x = -1.0; x <= 1.0; x = x + 0.1) {
y = asin(x);
printf ("ASIN(%f) = %f\n", x, y);
}
return 0;
}
- OUTPUT
$ gcc -Wall -lm asin.c $ ./a.out ASIN(-1.000000) = -1.570796 ASIN(-0.900000) = -1.119769 ASIN(-0.800000) = -0.927295 ASIN(-0.700000) = -0.775397 ASIN(-0.600000) = -0.643501 ASIN(-0.500000) = -0.523599 ASIN(-0.400000) = -0.411517 ASIN(-0.300000) = -0.304693 ASIN(-0.200000) = -0.201358 ASIN(-0.100000) = -0.100167 ASIN(0.000000) = 0.000000 ASIN(0.100000) = 0.100167 ASIN(0.200000) = 0.201358 ASIN(0.300000) = 0.304693 ASIN(0.400000) = 0.411517 ASIN(0.500000) = 0.523599 ASIN(0.600000) = 0.643501 ASIN(0.700000) = 0.775398 ASIN(0.800000) = 0.927295 ASIN(0.900000) = 1.119770
atan
- NAME
-
atan - arc tangent function.
- SYNOPSIS
#include <math.h>
double atan(double x);
- DESCRIPTION
-
The
atan()
function calculates the arc tangent ofx
; that is the value whose tangent isx
.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
The
atan()
function returns the arc tangent in radians and the value is mathematically defined to be between -PI/2 and PI/2 (inclusive). - SEE ALSO
-
acos
,asin
,atan2
,cos
,sin
,tan
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
float x;
float y;
for (x = -10.0; x <= 10.0; x = x + 1) {
y = atan(x);
printf ("ATAN(%f) = %f\n", x, y);
}
return 0;
}
- OUTPUT
$ gcc -Wall -lm atan.c $ ./a.out ATAN(-10.000000) = -1.471128 ATAN(-9.000000) = -1.460139 ATAN(-8.000000) = -1.446441 ATAN(-7.000000) = -1.428899 ATAN(-6.000000) = -1.405648 ATAN(-5.000000) = -1.373401 ATAN(-4.000000) = -1.325818 ATAN(-3.000000) = -1.249046 ATAN(-2.000000) = -1.107149 ATAN(-1.000000) = -0.785398 ATAN(0.000000) = 0.000000 ATAN(1.000000) = 0.785398 ATAN(2.000000) = 1.107149 ATAN(3.000000) = 1.249046 ATAN(4.000000) = 1.325818 ATAN(5.000000) = 1.373401 ATAN(6.000000) = 1.405648 ATAN(7.000000) = 1.428899 ATAN(8.000000) = 1.446441 ATAN(9.000000) = 1.460139 ATAN(10.000000) = 1.471128
atan2
- NAME
-
atan2 - arc tangent function of two variables.
- SYNOPSIS
#include <math.h>
double atan2(double y, double x);
- DESCRIPTION
-
The
atan2()
function calculates the arc tangent of the two variablesx
andy
. It is similar to calculating the arc tangent ofy / x
, except that the signs of both arguments are used to determine the quadrant of the result. The floating-point value returned byatan2
will be a number in the range [-PI, PI].
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
The
atan2()
function returns the result in radians, which is between -PI and PI (inclusive). - SEE ALSO
-
acos
,asin
,atan
,cos
,sin
,tan
- EXAMPLE
/* z approaches -pi as y goes from -10 to 0 */
/* z approaches +pi as y goes from +10 to 0 */
#include <math.h>
#include <stdio.h>
int main (void)
{
float x;
float y;
float z;
x = -1.0;
for (y = -10.0; y < 10.0; y = y + 1) {
z = atan2(y,x);
printf ("ATAN2(%f/%f) = %f\n", y, x, z);
}
return 0;
}
- OUTPUT
$ gcc -Wall -lm atan2.c $ ./a.out ATAN2(-10.000000/-1.000000) = -1.670465 ATAN2(-9.000000/-1.000000) = -1.681454 ATAN2(-8.000000/-1.000000) = -1.695151 ATAN2(-7.000000/-1.000000) = -1.712693 ATAN2(-6.000000/-1.000000) = -1.735945 ATAN2(-5.000000/-1.000000) = -1.768192 ATAN2(-4.000000/-1.000000) = -1.815775 ATAN2(-3.000000/-1.000000) = -1.892547 ATAN2(-2.000000/-1.000000) = -2.034444 ATAN2(-1.000000/-1.000000) = -2.356194 ATAN2(0.000000/-1.000000) = 3.141593 ATAN2(1.000000/-1.000000) = 2.356194 ATAN2(2.000000/-1.000000) = 2.034444 ATAN2(3.000000/-1.000000) = 1.892547 ATAN2(4.000000/-1.000000) = 1.815775 ATAN2(5.000000/-1.000000) = 1.768192 ATAN2(6.000000/-1.000000) = 1.735945 ATAN2(7.000000/-1.000000) = 1.712693 ATAN2(8.000000/-1.000000) = 1.695151 ATAN2(9.000000/-1.000000) = 1.681454
ceil
- NAME
-
ceil - smallest integral value not less than
x
. - SYNOPSIS
#include <math.h>
double ceil(double x);
- DESCRIPTION
-
The
ceil()
function roundsx
upwards to the nearest integer, returning that value as a double.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
The
ceil
function returns a double that contains the smallest integer value that is not less than val. - SEE ALSO
-
floor
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double x;
double y;
printf("Enter a floating point value > ");
scanf("%lf", &x);
y = ceil(x);
printf("CEIL(%f) = %f\n", x, y);
return 0;
}
- OUTPUT
$ gcc -Wall -lm ceil.c $ ./a.out Enter a floating point value > 45.98934 CEIL(45.989340) = 46.000000
cos
- NAME
-
cos - cosine function.
- SYNOPSIS
#include <math.h>
double cos(double x);
- DESCRIPTION
-
The
cos()
function returns the cosine ofx
, wherex
is given in radians.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
The
cos()
function returns a value between [-1, 1]. - SEE ALSO
-
sin
,tan
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
float x;
float y;
for (x = 0; x < (2 * M_PI); x = x + 1) {
y = cos(x);
printf("cos(%f) = %f\n", x, y);
}
return 0;
}
- OUTPUT
$ gcc -Wall -lm cos.c $ ./a.out cos(0.000000) = 1.000000 cos(1.000000) = 0.540302 cos(2.000000) = -0.416147 cos(3.000000) = -0.989992 cos(4.000000) = -0.653644 cos(5.000000) = 0.283662 cos(6.000000) = 0.960170
cosh
- NAME
-
cosh - hyperbolic cosine function.
- SYNOPSIS
#include <math.h>
double cosh(double x);
- DESCRIPTION
-
The
cosh()
function returns the hyperbolic cosine ofx
, which is defined mathematically as exp(x) + exp(-x) / 2.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- SEE ALSO
-
sinh
,tanh
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
float x;
float y;
for (x = 0; x < (2 * M_PI); x = x + 1) {
y = cosh(x);
printf("cosh(%f) = %f\n", x, y);
}
return 0;
}
- OUTPUT
$ gcc -Wall -lm cosh.c $ ./a.out cosh(0.000000) = 1.000000 cosh(1.000000) = 1.543081 cosh(2.000000) = 3.762196 cosh(3.000000) = 10.067662 cosh(4.000000) = 27.308233 cosh(5.000000) = 74.209946 cosh(6.000000) = 201.715637
exp
- NAME
-
exp - exponential function.
- SYNOPSIS
#include <math.h>
double exp(double x);
- DESCRIPTION
-
The
exp()
function returns the value ofe
(the base of natural logarithms) raised to the power of x.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
On success, these functions return the exponential value of
x
. - SEE ALSO
-
log
,log10
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double x;
double y;
x = 4.605170186;
y = exp(x);
printf("EXP(%f) = %f\n", x, y);
return 0;
}
- OUTPUT
$ gcc -Wall -lm exp.c $ ./a.out EXP(4.605170) = 100.000000
fabs
- NAME
-
fabs - absolute value of floating-point number.
- SYNOPSIS
#include <math.h>
double fabs(double x);
- DESCRIPTION
-
The fabs function determines the absolute value of the floating-point number
val
.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
The
fabs
function returns the absolute value ofval
. - SEE ALSO
-
abs
,cabs
,labs
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
float x;
float y;
x = 10.2;
y = fabs(x);
printf("fabs(%f) = %f\n", x, y);
x = -3.6;
y = fabs(x);
printf("fabs(%f) = %f\n", x, y);
return 0;
}
- OUTPUT
$ gcc -Wall -lm fabs.c $ ./a.out fabs(10.200000) = 10.200000 fabs(-3.600000) = 3.600000
floor
- NAME
-
floor - largest integer value not greater than x.
- SYNOPSIS
#include <math.h>
double floor(double x);
- DESCRIPTION
-
These function returns the largest integral value that is not greater than
x
. For example,floor(0.5)
is0.0
, andfloor(-0.5)
is-1.0
.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
The floor function returns a floating point number that contains the largest integer value that is not greater than
x
. - SEE ALSO
-
ceil
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double x;
double y;
printf("Enter a floating point number > ");
scanf("%lf", &x);
y = floor(x);
printf("FLOOR(%lf) = %lf\n", x, y);
return 0;
}
- OUTPUT
$ gcc -Wall -lm floor.c $ ./a.out Enter a floating point number > 45.98 FLOOR(45.980000) = 45.000000 $ ./a.out Enter a floating point number > -45.98 FLOOR(-45.980000) = -46.000000
fmod
- NAME
-
fmod - floating-point remainder function.
- SYNOPSIS
#include <math.h>
double fmod(double x, double y);
- DESCRIPTION
-
The
fmod()
function computes the remainder of dividingx
byy
. The return value isx - n * y
, wheren
is the quotient ofx / y
, rounded towards zero to an integer.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
The
fmod()
function returns the remainder, unlessy
is zero --- in this case the function fails anderrno
is set. - ERRORS
-
EDOM - The denominator
y
is zero. - SEE ALSO
-
ceil
,fabs
,floor
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double x;
double y;
double z;
printf("Enter two floating point numbers separated by a space > ");
scanf("%lf %lf", &x, &y);
z = fmod(x,y);
printf("FMOD(%f/%f) = %f\n", x, y, z);
return 0;
}
- OUTPUT
$ gcc -Wall -lm fmod.c $ ./a.out Enter two floating point numbers separated by a space > 12.0 -3.45 FMOD(12.000000/-3.450000) = 1.650000
frexp
- NAME
-
frexp - convert floating-point number to fractional and integral components.
- SYNOPSIS
#include <math.h>
double frexp(double x, int *exp);
- DESCRIPTION
-
The function
frexp()
is used to decomposenum
into two parts: a mantissa between 0.5 and 1 (returned by the function) and an exponent returned asexp
. Scientific notation works like this:num = mantissa * (2 ^ exp)
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
The
frexp()
function returns the normalized fraction. If the argumentx
is not zero, the normalized fraction isx
times a power of two, and is always in the range 1/2 (inclusive) to 1 (exclusive). Ifx
is zero, then the normalized fraction is zero and zero is stored inexp
. - SEE ALSO
-
ldexp
,modf
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double param, result;
int n;
param = 15.2;
result = frexp(param , &n);
printf ("%f * 2^%d = %f\n", result, n, param);
return 0;
}
- OUTPUT
$ gcc -Wall -lm frexp.c $ ./a.out 0.950000 * 2^4 = 15.200000
ldexp
- NAME
-
ldexp - multiply floating-point number by integral power of 2.
- SYNOPSIS
#include <math.h>
double ldexp(double x, int exp);
- DESCRIPTION
-
Calculates the floating point value corresponding to the given mantissa and exponent, such that:
x * 2^exp
where thex
parameter represents the mantissa and the exp parameter the exponent.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
The
ldexp()
function returns the result of multiplying the floating-point numberx
by 2 raised to the powerexp
. - SEE ALSO
-
frexp
,modf
,exp
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double param, result;
int n;
param = 0.95;
n = 4;
result = ldexp(param , n);
printf ("%f * 2^%d = %f\n", param, n, result);
return 0;
}
- OUTPUT
$ gcc -Wall -lm ldexp.c $ ./a.out 0.950000 * 2^4 = 15.200000
log
- NAME
-
log - Returns the natural logarithm of parameter
x
. - SYNOPSIS
#include <math.h>
double log(double x);
- DESCRIPTION
-
The
log()
function returns the natural logarithm ofx
.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
Logarithm naturalis of
x
. - ERRORS
-
-
EDOM - The argument
x
is negative. -
ERANGE - The argument
x
is zero. The log of zero is not defined.
-
- SEE ALSO
-
log10
,exp
,pow
,sqrt
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double param, result;
param = 5.5;
result = log(param);
printf ("ln(%lf) = %lf\n", param, result );
return 0;
}
- OUTPUT
$ gcc -Wall -lm log.c $ ./a.out ln(5.500000) = 1.704748
log10
- NAME
-
log10 - The
log10()
function returns the "base 10" logarithm ofx
. - SYNOPSIS
#include <math.h>
double log10(double x);
- DESCRIPTION
-
The
log10()
function returns the natural logarithm ofx
.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
Returns the logarithm "base 10" of parameter
x
. - ERRORS
-
-
EDOM - The argument
x
is negative. -
ERANGE - The argument
x
is zero. The log of zero is not defined.
-
- SEE ALSO
-
log
,exp
,pow
,sqrt
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double param;
double result;
param = 1000.0;
result = log10(param);
printf ("log10(%lf) = %lf\n", param, result );
return 0;
}
- OUTPUT
$ gcc -Wall -lm log10.c $ ./a.out log10(1000.000000) = 3.000000
modf
- NAME
-
modf - extract signed integral and fractional values from floating-point number.
- SYNOPSIS
#include <math.h>
double modf(double x, double *iptr);
- DESCRIPTION
-
The
modf()
function breaks the argumentx
into an integral part and a fractional part, each of which has the same sign asx
. The integral part is stored iniptr
.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
The
modf()
function returns the fractional part ofx
. - SEE ALSO
-
ldexp
,frexp
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double param, fractpart, intpart;
param = M_PI;
fractpart = modf(param , &intpart);
printf ("%lf = %lf + %lf \n", param, intpart, fractpart);
return 0;
}
- OUTPUT
$ gcc -Wall -lm modf.c $ ./a.out 3.141593 = 3.000000 + 0.141593
pow
- NAME
-
pow - The
pow()
function returns the value ofx
raised to the power ofy
. - SYNOPSIS
#include <math.h>
double pow(double x, double y);
- DESCRIPTION
-
Returns
x
raised to the power ofy
:x^y
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
x
raised to the power ofy
. - ERRORS
-
-
EDOM - The argument
x
is negative andy
is not an integral value. This would result in a complex number. -
ERANGE - When
x
is zero andy
is nagetive a divide, by zero exception is raised. This error is also raised when the result overflows or underflows.
-
- SEE ALSO
-
exp
,log
,sqrt
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
printf ("7 ^ 3 = %lf\n", pow(7,3));
printf ("4.73 ^ 12 = %lf\n", pow(4.73,12));
printf ("32.01 ^ 1.54 = %lf\n", pow(32.01,1.54));
return 0;
}
- OUTPUT
$ gcc -Wall pow.c $ ./a.out 7 ^ 3 = 343.000000 4.73 ^ 12 = 125410439.217423 32.01 ^ 1.54 = 208.036691
sin
- NAME
-
sin - sine function.
- SYNOPSIS
#include <math.h>
double sin(double x);
- DESCRIPTION
-
The
sin()
function returns the sine ofx
, wherex
is given in radians.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
The
sin()
function returns a value between -1 and 1. - SEE ALSO
-
cos
,tan
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double param, result;
param = 45;
result = sin(param*M_PI/180);
printf ("Sine of %lf degrees is %lf\n", param, result );
return 0;
}
- OUTPUT
$ gcc -Wall -lm sin.c $ ./a.out Sine of 45.000000 degrees is 0.707107
sinh
- NAME
-
sinh - hyperbolic cosine function.
- SYNOPSIS
#include <math.h>
double sinh(double x);
- DESCRIPTION
-
The
sinh()
function returns the hyperbolic sine ofx
, which is defined mathematically asexp(x) - exp(-x) / 2
.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- SEE ALSO
-
cosh
,tanh
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double param, result;
param = 45;
result = sinh(param*M_PI/180);
printf ("Hyperbolic sine of %lf degrees is %lf\n", param, result );
return 0;
}
- OUTPUT
$ gcc -Wall -lm sinh.c $ ./a.out Hyperbolic sine of 45.000000 degrees is 0.868671
sqrt
- NAME
-
sqrt - square root function.
- SYNOPSIS
#include <math.h>
double sqrt(double x);
- DESCRIPTION
-
The
sqrt()
function returns the non-negative square root ofx
. It fails and sets errno toEDOM
, ifx
is negative.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
Square root of
x
. - ERRORS
-
-
EDOM -
x
is negative.
-
- SEE ALSO
-
exp
,log
,log10
,pow
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double param, result;
param = 1024.0;
result = sqrt(param);
printf ("sqrt(%lf) = %lf\n", param, result );
return 0;
}
- OUTPUT
$ gcc -Wall -lm sqrt.c $ ./a.out sqrt(1024.000000) = 32.000000
tan
- NAME
-
tan - tangent function.
- SYNOPSIS
#include <math.h>
double tan(double x);
- DESCRIPTION
-
The
tan()
function returns the tangent ofx
, wherex
is given in radians.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- RETURN VALUE
-
Tangent of
x
. - SEE ALSO
-
cos
,sin
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double param, result;
param = 60;
result = tan(param*M_PI/180);
printf ("Tangent of %lf degrees is %lf\n", param, result );
return 0;
}
- OUTPUT
$ gcc -Wall -lm tan.c $ ./a.out Tangent of 60.000000 degrees is 1.732051
tanh
- NAME
-
tanh - hyperbolic tangent function.
- SYNOPSIS
#include <math.h>
double tanh(double x);
- DESCRIPTION
-
The
tanh()
function returns the hyperbolic tangent ofx
, which is defined mathematically assinh(x) / cosh(x)
.
You’ll also need to link the program against the math library (see example below) using the -lm compile/link option.
|
- SEE ALSO
-
cosh
,sinh
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double param, result;
param = 60;
result = tan(param*M_PI/180);
printf ("Tangent of %lf degrees is %lf\n", param, result );
return 0;
}
- OUTPUT
$ gcc -Wall -lm tanh.c $ ./a.out Hyperbolic tangent of 45.000000 degrees is 0.655794
setjmp.h
longjmp
- NAME
-
longjmp - non-local jump to a saved stack context.
- SYNOPSIS
#include <setjmp.h>
void longjmp(jmp_buf env, int val);
- DESCRIPTION
-
longjmp()
andsetjmp()
are useful for dealing with errors and interrupts encountered in a low-level subroutine of a program.longjmp()
restores the environment saved by the last call ofsetjmp()
with the corresponding env argument. Afterlongjmp()
is completed, program execution continues as if the corresponding call ofsetjmp()
had just returned the value val.longjmp()
cannot cause 0 to be returned. Iflongjmp
is invoked with a second argument of 0, 1 will be returned instead. - RETURN VALUE
-
This function never returns.
- SEE ALSO
-
setjmp
- EXAMPLE
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
void some_function(jmp_buf);
int main(void)
{
int value;
jmp_buf environment_buffer;
value=setjmp(environment_buffer);
if(value!=0) {
printf("Reached this point from a longjmp with value=%d.\n",value);
exit(0);
}
printf("Calling function.\n");
some_function(environment_buffer);
return 0;
}
void some_function(jmp_buf env_buf)
{
longjmp(env_buf,5);
}
- OUTPUT
$ gcc -Wall longjmp.c $ ./a.out Calling function. Reached this point from a longjmp with value=5.
setjmp
- NAME
-
setjmp - save stack context for non-local goto.
- SYNOPSIS
#include <setjmp.h>
int setjmp(jmp_buf envbuf);
- DESCRIPTION
-
setjmp()
andlongjmp()
are useful for dealing with errors and interrupts encountered in a low-level subroutine of a program.setjmp()
saves the stack context/environment inenv
for later use bylongjmp()
. The stack context will be invalidated if the function which calledsetjmp()
returns. - RETURN VALUE
-
It returns the value 0 if returning directly and non-zero when returning from
longjmp()
using the saved context. - SEE ALSO
-
longjmp
- EXAMPLE
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
void some_function(jmp_buf);
int main(void)
{
int value;
jmp_buf environment_buffer;
value=setjmp(environment_buffer);
if(value!=0) {
printf("Reached this point from a longjmp with value=%d.\n",value);
exit(0);
}
printf("Calling function.\n");
some_function(environment_buffer);
return 0;
}
void some_function(jmp_buf env_buf)
{
longjmp(env_buf,5);
}
- OUTPUT
$ gcc -Wall setjmp.c $ ./a.out Calling function. Reached this point from a longjmp with value=5.
signal.h
signal
- NAME
-
signal - ANSI C signal handling.
- SYNOPSIS
#include <signal.h>
void (*signal(int signum, void (*handler)(int)))(int);
- DESCRIPTION
-
The signal system call installs a new signal handler for signal
signum
. The signal handler is set to handler which may be a user specified function, or one of the following:-
SIG_IGN - Ignore the signal.
-
SIG_DFL - Reset the signal to its default behavior.
-
SIG_IGN - Signal ignore.
-
Some basic signals that you can attach a signal handler too are:
-
SIGABRT - Abnormal termination (generated by the abort function).
-
SIGFPE - Floating-point error (error caused by division by zero, invalid operation, etc.).
-
SIGILL - Illegal operation (instruction).
-
SIGSEGV - Invalid access to storage (segment violation, memory violation).
-
SIGTERM - Generic stop signal that can be caught.
-
SIGINT - Interrupt program, normally ctrl-c.
-
SIGQUIT - Interrupt program, similar to SIGINT.
-
SIGKILL - Stops the program. Cannot be caught.
-
SIGHUP - Reports a disconnected terminal.
In the example below CTRL+C is pressed two times during the 5 seconds wait built into the program in order to emit an interrupt signal. |
- RETURN VALUE
-
signal
returns the previous value of the signal handler, orSIG_ERR
on error. - SEE ALSO
-
raise
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double param, result;
param = 5.5;
result = log(param);
printf ("ln(%lf) = %lf\n", param, result );
return 0;
}
- OUTPUT
$ gcc -Wall signal.c $ ./a.out Raising the interactive attention signal. Interactive attention signal caught. ^CInteractive attention signal caught. ^CInteractive attention signal caught. Exiting.
raise
- NAME
-
raise - send a signal.
- SYNOPSIS
#include <signal.h>
int raise (int sig);
- DESCRIPTION
-
raise()
sends a signal to the current process. It is equivalent tokill(getpid(),sig)
. - RETURN VALUE
-
Zero for success, nonzero for failure.
- SEE ALSO
-
signal
- EXAMPLE
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void catch_function(int);
void wait(int seconds);
int main(void)
{
if(signal(SIGINT, catch_function)==SIG_ERR) {
printf("An error occured while setting a signal handler.\n");
exit(EXIT_SUCCESS);
}
printf("Raising the interactive attention signal.\n");
if(raise(SIGINT)!=0) {
printf("Error raising the signal.\n");
exit(EXIT_SUCCESS);
}
wait(60);
printf("Exiting.\n");
return 0;
}
void catch_function(int signal)
{
printf("Interactive attention signal caught.\n");
}
void wait(int seconds)
{
int t;
t=0;
while (t < seconds)
t = clock()/CLOCKS_PER_SEC;
}
The above example uses a wait()
function to delay for approximately 60 seconds. During this time — whenever a CTRL+C signal is caught — the respective signal handler catch_function
gets invoked.
- OUTPUT
$ gcc -Wall raise.c $ ./a.out Raising the interactive attention signal. Interactive attention signal caught. ^CInteractive attention signal caught. ^CInteractive attention signal caught. ^CInteractive attention signal caught. Exiting.
stdarg.h
stdarg
- NAME
-
stdarg - variable argument lists.
- SYNOPSIS
#include <stdarg.h>
void va_start( va_list ap, last);type va_arg( va_list ap, type);void va_end( va_list ap);
- DESCRIPTION
-
A function may be called with a varying number of arguments of varying types. The include file
stdarg.h
declares a typeva_list
and defines three macros for stepping through a list of arguments whose number and types are not known to the called function.
The called function must declare an object of type va_list
which is
used by the macros va_start
, va_arg
, and va_end
.
The va_start
macro initializes ap
for subsequent use by va_arg
and
va_end
, and must be called first.
The parameter last is the name of the last parameter before the variable argument list, i.e., the last parameter of which the calling function knows the type.
Because the address of this parameter is used in the va_start
macro, it should not be declared as a register variable, or as a
function or an array type.
The va_arg
macro expands to an expression that has the type and
value of the next argument in the call. The parameter ap
is the
va_list
ap
initialized by va_start
. Each call to va_arg
modifies ap
so that the next call returns the next argument. The parameter type
is a type name specified so that the type of a pointer to an object
that has the specified type can be obtained simply by adding a *
to
type.
If there is no next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), random errors will occur.
The first use of the va_arg
macro after that of the va_start
macro
returns the argument after last. Successive invocations return the
values of the remaining arguments.
The va_end
macro handles a normal return from the function whose
variable argument list was initialized by va_start
.
- RETURN VALUE
-
Neither the
va_start
macro nor theva_end
macro return a value. - EXAMPLE
#include <stdarg.h>
#include <stdio.h>
void sum(char *, int, ...);
int main(void)
{
sum("The sum of 10+15+13 is %d.\n",3,10,15,13);
return 0;
}
void sum(char *string, int num_args, ...)
{
int sum=0;
va_list ap;
int loop;
va_start(ap,num_args);
for(loop=0; loop<num_args; loop++)
sum+=va_arg(ap,int);
printf(string,sum);
va_end(ap);
}
- OUTPUT
$ gcc -Wall stdarg.c $ ./a.out The sum of 10+15+13 is 38.
- EXAMPLE
-
The function foo takes a string of format characters and prints out the argument associated with each format character based on the type.
void foo(char *fmt, ...)
{
va_list ap;
int d;
char c, *p, *s;
va_start(ap, fmt);
while (*fmt) {
switch(*fmt++) {
case 's': /* string */
s = va_arg(ap, char *);
printf("string %s\n", s);
break;
case 'd': /* int */
d = va_arg(ap, int);
printf("int %d\n", d);
break;
case 'c': /* char */
c = va_arg(ap, char);
printf("char %c\n", c);
break;
}
}
va_end(ap);
}
- EXAMPLE
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
int set(char *item, int num, ...);
int main(void)
{
char *item="pear";
int ret;
ret = set (item,4, "apple", "pear", "banana", "grape");
if (ret) {
printf ("%s found\n", item);
} else {
printf("%s not found\n", item);
}
return EXIT_SUCCESS;
}
int set(char *item, int num, ...)
{
va_list ap;
int ret=0;
int inc=0;
va_start(ap, num);
do {
if ( item == va_arg(ap, char *)) {
ret = 1;
}
} while ( (ret==0) && (++inc < num));
va_end(ap);
return (ret);
}
- OUTPUT
$ gcc -Wall stdarg3.c $ ./a.out pear found
stddef.h
stddef
- SYNOPSIS
#include <stddef.h>
- DESCRIPTION
-
The
stddef
header defines several standard definitions. Many of these definitions also appear in other headers:-
ptrdiff_t - is the result of subtracting two pointers.
-
size_t - is the unsigned integer result of the sizeof keyword.
-
wchar_t - is an integer type of the size of a wide character constant.
-
NULL - is the value of a null pointer constant.
-
offsetof(type, member-designator) - This results in a constant integer of type size_t which is the offset in bytes of a structure member from the beginning of the structure. The member is given by member-designator, and the name of the structure is given in type.
-
- EXAMPLE
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
struct user {
char name[50];
char alias[50];
int level;
};
printf("level is at %d byte.\n",offsetof(struct user, level));
return EXIT_SUCCESS;
}
- OUTPUT
$ gcc -Wall stddef.c $ ./a.out level is at 100 byte.
stdio.h
Stdio Summary
STREAMS
Streams are an abstraction used in C and C++ for input
and output operations through I/O devices based on characters, like
files, a keyboard, printer, screen and I/O ports. A stdio
stream is represented by a pointer to a FILE
structure that
contains internal info about properties and indicators of a file.
Normally data contained in these structures are not referred
directly. When using stdio.h functions, pointer to FILE
structures are only used to be passed as parameters to I/O
functions.
PROPERTIES
A stream has some properties that define which
functions can be used with it or how the functions will treat the
stream. Most of them are defined in the mode parameter when the
fopen
function is called.
-
Access - Specifies if the operations performed with the stream will have read and/or write access to the file.
-
Text / Binary - Text files are those where lines are delimited by the special character
EOL
(End Of Line), and some translations occur when this special character is read or written for that these file can be directly output to a console. The End of a text file is defined by the first occurrence of theEOF
character.
A binary file is a file where each byte is read or written as a character, no translations occur, and the End of a binary file matches with the physical End of the File. -
Buffer - A buffer is a block of memory where data is accumulated before being physically read or written to the file. Buffered stream causes I/O operations with the stream to be faster because normally buffers are faster than physical devices like disks or ports. A stream can be unbuffered so the data is directly read or written to the device. The use of stream buffers can be specified using functions
setbuf
andsetvbuf
.
INDICATORS
A stream has some indicators that specify the current state of it. These are internally modified and affect the behavior of Input/Output functions:
-
Error Indicator - This indicator is set when an error has occurred in an operation related with the stream. This indicator can be checked using
ferror
, and can be reset by a call toclearerr
or by any repositioning function (rewind
,fseek
, andfsetpos
). -
End-Of-File Indicator - When this indicator is set, the last reading or writing operation performed has reached the End of the file associated with the stream. This can be checked with the
feof
function, and can be reset by calling toclearerr
or by any repositioning function (rewind
,fseek
, andfsetpos
). -
Position Indicator (File pointer) - This indicator is an internal pointer that points to the next character within the stream that has to be read or written by the next I/O operation. This value can be obtained by the
ftell
andfgetpos
functions, and can be changed calling torewind
,fseek
, andfsetpos
functions.
STANDARD STREAMS
When a program that includes stdio
begin its execution, three predefined streams are opened:
-
stdin - This is the standard input stream. By default
stdin
corresponds to the keyboard, but this can be redirected by the operating system. -
stdout - This is the standard output stream. By default
stdout
is directed to the screen, but the operating system can redirect it to a file or any other output device. -
stderr - The standard error stream. This is an output stream specifically intended to receive error messages. By default is directed to the standard output (like
stdout
), but it can be redirected to a log file or any other output device.
clearerr
- NAME
-
clearerr - Reset error indicators.
- SYNOPSIS
#include <stdio.h>
void clearerr( FILE *stream );
- DESCRIPTION
-
The function
clearerr
clears the end-of-file (EOF) and error indicators for the stream pointed to by stream. - RETURN VALUE
-
None.
- SEE ALSO
-
feof
,ferror
,fwrite
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[])
{
FILE * pFile;
pFile = fopen(argv[1],"r");
if (pFile==NULL)
perror ("Error opening file");
else {
fputc ('x',pFile);
if (ferror (pFile)) {
printf ("Error Writing to %s.\n", argv[1]);
clearerr (pFile);
}
fgetc (pFile);
if (!ferror (pFile))
printf ("No errors reading %s.\n", argv[1]);
fclose (pFile);
}
return 0;
}
This program opens a existing file in read-only mode thus causing an I/O error. That error is cleared using clearerr
so a second error checking returns false.
- OUTPUT
$ gcc -Wall clearerr.c $ ./a.out test Error opening file: No such file or directory $ touch test $ ./a.out test Error Writing to test. No errors reading test.
fclose
- NAME
-
fclose - Close a stream.
- SYNOPSIS
#include <stdio.h>
int fclose(FILE *stream);
- DESCRIPTION
-
Close the file associated with the specified stream after flushing all buffers associated with it.
- RETURN VALUE
-
If the stream is successfully closed 0 is returned. In case of an error
EOF
is returned. - SEE ALSO
-
fopen
,freopen
,fflush
- EXAMPLE
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
FILE * pFile;
pFile = fopen (argv[1],"wt");
if (pFile==NULL) {
printf("Error opening file.\n");
exit(EXIT_FAILURE);
}
fprintf (pFile, "fclose example");
fclose (pFile);
return 0;
}
- OUTPUT
$ gcc -Wall fclose.c $ ./a.out hello $ more hello fclose example
- EXAMPLE
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int c;
FILE *pFile;
pFile = fopen(argv[1],"r");
if (pFile==NULL) {
printf("Error opening file.\n");
exit(EXIT_FAILURE);
}
while ((c = fgetc(pFile)) != EOF) {
printf("%c",c);
}
fclose(pFile);
return 0;
}
- OUTPUT
$ gcc -Wall fclose2.c $ ./a.out fclose2.c #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int c; FILE *pFile; pFile = fopen(argv[1],"r"); if (pFile==NULL) { printf("Error opening file.\n"); exit(EXIT_FAILURE); } while ((c = fgetc(pFile)) != EOF) { printf("%c",c); } fclose(pFile); return 0; }
feof
- NAME
-
feof - Check if End Of File has been reached.
- SYNOPSIS
#include <stdio.h>
int feof(FILE *stream);
- DESCRIPTION
-
Tests if the position indicator of a given stream has reached the End of File.
Once End Of File has been reached, further reading operations on
the same stream return EOF
until rewind()
or fseek()
are called
changing the position indicator to a valid position. Because the
EOF
value returned by many input functions may indicate either the
End-Of-File or an error, this function should be called to ensure
the End Of File has been reached.
- RETURN VALUE
-
A non-zero value is returned in the case that the position indicator reached the End Of File in the last input operation with the specified stream, otherwise
0
is returned. - SEE ALSO
-
clearerr
,ferror
,fwrite
- EXAMPLE
#include <stdio.h>
int main (int argc, char*argv[])
{
FILE * pFile;
long n;
n = 0;
pFile = fopen (argv[1],"rb");
if (pFile==NULL) {
perror ("Error opening file");
} else {
while (!feof(pFile)) {
fgetc (pFile);
n++;
}
fclose (pFile);
printf ("Total number of bytes: %ld\n",n);
}
return 0;
}
- OUTPUT
$ gcc -Wall feof.c $ ./a.out Error opening file: Bad address $ ./a.out feof.c Total number of bytes: 342
- EXAMPLE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char data[80];
FILE *ptr;
int i;
i=0;
ptr = fopen(argv[1],"r");
if (ptr == 0) {
printf("%s open failure.\n", argv[1]);
exit(1);
}
while (1) {
fgets(data, 80, ptr);
if (feof(ptr) != 0)
break;
i = i + 1;
}
printf("The file contains %d lines.\n",i);
fclose(ptr);
return 0;
}
- OUTPUT
$ gcc -Wall feof2.c $ ./a.out feof2.c The file contains 26 lines.
ferror
- NAME
-
ferror - Check for errors.
- SYNOPSIS
#include <stdio.h>
int ferror(FILE *stream);
- DESCRIPTION
-
Tests if a error has occurred in the last reading or writing operation with the given stream, returning a non-zero value in case of error. If indeed there has been an error the error indicator will not be modified by a call to this function. You should call
clearerr
or rewind to reset it. - RETURN VALUE
-
If there were no errors a 0 value is returned. Otherwise a non-zero value is returned and the error indicator of the stream will remain set.
- SEE ALSO
-
feof
,clearerr
,perror
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[])
{
FILE * pFile;
pFile=fopen(argv[1],"r");
if (pFile==NULL) {
perror ("Error opening file");
} else {
fputc ('x',pFile);
if (ferror(pFile))
printf ("Error Writing to %s.\n", argv[1]);
fclose (pFile);
}
return 0;
}
The above program opens an existing file whose file name is provided as command-line argument in read-only mode. The program, however, tries to write a character to it, generating an error that is caught by ferror
.
- OUTPUT
$ gcc -Wall ferror.c $ ./a.out Error opening file: Bad address $ ./a.out ferror.c Error Writing to ferror.c.
fflush
- NAME
-
fflush - Flush a stream.
- SYNOPSIS
#include <stdio.h>
int fflush(FILE *stream);
- DESCRIPTION
-
If the given stream has been opened for writing operations the output buffer is physically written to the file. If the stream was open for reading operations the content of the input buffer is cleared. The stream remains open after this call. When a file is closed all the buffers associated with it are automatically flushed. If the program terminates, every buffer is automatically flushed.
- RETURN VALUE
-
A
0
value indicates success. If errors occurEOF
is returned. - ERRORS
-
EBADF - Stream is not an open stream, or, in the case of
fflush
, not a stream open for writing.
The function fflush
may also fail and set errno
for any of the
errors specified for the routine write()
.
- SEE ALSO
-
fclose
,fopen
,fread
,fwrite
- EXAMPLE
-
Consider the following program. It opens a file stream and writes ‘something’ to the file. Next, it reads a few characters and then tries to write ‘something’ a second time. Finally the program becomes busy --- in this case simulated by an endless loop --- before the program can eventually close the stream. We use a text pattern written to a
test.txt
file to investigate the behavior.
#include <stdio.h>
int main(int argc, char *argv[])
{
char buffer[100];
FILE *pFile;
// open file for both reading and writing
pFile = fopen(argv[1], "rt+");
if (pFile!=NULL) {
fprintf(pFile, "something");
fgets(buffer, 10, pFile);
printf("Read %s from file.\n", buffer);
fprintf(pFile, "something");
while(1)
;
fclose(pFile);
}
return 0;
}
- OUTPUT
$ gcc -Wall fflush.c $ cat test.txt abcdefghi123456789abcdefghi123456789 abcdefghi123456789abcdefghi123456789 $ ./a.out test.txt Read 123456789 from file. ^C $ cat test.txt something123456789abcdefghi123456789 abcdefghi123456789abcdefghi123456789
Following compilation the above listing first shows the content of the test files test.txt
Next the program is invoked and after a few seconds interrupted by pressing CTRL+C (Strg+C). Finally, test.txt
is investigated a second time. From the output we can see that the first fprintf()
and fgets()
were successful, the second fprintf()
, however, doesn’t show up.
The next listing adds a fflush()
after the second fprintf()
; now, since the output gets flushed the second fprintf()
output is also present in the test file.
#include <stdio.h>
int main(int argc, char *argv[])
{
char buffer[100];
FILE *pFile;
// open file for both reading and writing
pFile = fopen(argv[1], "rt+");
if (pFile!=NULL) {
fprintf(pFile, "something");
fgets(buffer, 10, pFile);
printf("Read %s from file.\n", buffer);
fprintf(pFile, "something");
fflush(pFile);
while(1)
;
fclose(pFile);
}
return 0;
}
- OUTPUT
$ gcc -Wall fflush.c $ cat test.txt abcdefghi123456789abcdefghi123456789 abcdefghi123456789abcdefghi123456789 $ ./a.out test.txt Read 123456789 from file. ^C $ cat test.txt something123456789something123456789 abcdefghi123456789abcdefghi123456789
fgetc
- NAME
-
fgetc - Get the next character from a stream.
- SYNOPSIS
#include <stdio.h>
int fgetc(FILE *stream);
- DESCRIPTION
-
Returns the next character of the stream and increases the file pointer to point to the following one.
- RETURN VALUE
-
The character read is returned as an
int
value. If the End Of File has been reached or there has been an error reading, the function returnsEOF
. You can useferror()
orfeof()
to determine whether an error happened or the End-Of-File was reached. - SEE ALSO
-
fputc
,fread
,fwrite
- EXAMPLE
#include <stdio.h>
int main (int argc, char * argv[])
{
FILE * pFile;
char c;
int n;
n=0;
pFile=fopen (argv[1],"r");
if (pFile==NULL) {
perror ("Error opening file");
} else {
do {
c = fgetc (pFile);
if (c == 'a')
n++;
} while (c != EOF);
fclose (pFile);
printf ("File contains %d 'a' characters.\n",n);
}
return 0;
}
The above program reads a file whose file name is provided as command-line argument
character by character and uses the variable n
to count how many
a characters are found.
- OUTPUT
$ gcc -Wall fgetc.c $ ./a.out fgetc.c File contains 11 'a' characters.
- EXAMPLE
#include <stdio.h>
int main(int argc, char *argv[1])
{
int c;
FILE *ptr;
ptr = fopen(argv[1],"r");
while ((c = fgetc(ptr)) != EOF) {
printf("%c",c);
}
fclose(ptr);
return 0;
}
This example simply reads character after character from a file and prints it to the screen.
- OUTPUT
$ gcc -Wall fgetc2.c $ ./a.out fgetc2.c #include <stdio.h> int main(int argc, char *argv[1]) { int c; FILE *ptr; ptr = fopen(argv[1],"r"); while ((c = fgetc(ptr)) != EOF) { printf("%c",c); } fclose(ptr); return 0; }
fgetpos
- NAME
-
fgetpos - Get position in a stream.
- SYNOPSIS
#include <stdio.h>
int fgetpos (FILE * stream , fpos_t * position);
- DESCRIPTION
-
Gets the value of the position indicator of the given stream and stores it in the location pointed by position in a format that is only intended for use as a parameter in further calls to
fsetpos
. If you want to get the current position of a stream for any other use than as a parameter forfsetpos
you should call toftell
function. - RETURN VALUE
-
0 value indicates success. non-zero value indicates error.
- SEE ALSO
-
fsetpos
,ftell
,fseek
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[])
{
FILE * pFile;
char c;
int n;
fpos_t pos;
pFile = fopen (argv[1],"r");
if (pFile==NULL) {
perror ("Error opening file");
} else {
c = fgetc (pFile);
printf ("1st character is %c\n",c);
fgetpos (pFile,&pos);
for (n=0; n < 3; n++) {
fsetpos (pFile,&pos);
c = fgetc (pFile);
printf ("2nd character is %c\n",c);
}
fclose (pFile);
}
return 0;
}
This example opens a file and reads the first character once and then it reads 3 times the same second character.
- OUTPUT
$ gcc -Wall fgetpos.c $ ./a.out file.txt 1st character is h 2nd character is e 2nd character is e 2nd character is e
fgets
- NAME
-
fgets - Get a string from a stream.
- SYNOPSIS
#include <stdio.h>
char *fgets (char *string , int num , FILE *stream);
- DESCRIPTION
-
Reads characters from stream and stores them in string until (
num - 1
) characters have been read or anewline
orEOF
character is reached, whichever comes first. A newline character ends reading but is considered a valid character and included in the new string. A null character is always appended at the end of the resulting string. - RETURN VALUE
-
On success, the string read is returned. On end-of-file or error, null pointer is returned. Use
ferror
orfeof
to check what happend. - SEE ALSO
-
fputc
,fread
,fwrite
- EXAMPLE
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE * pFile;
char string [100];
pFile = fopen (argv[1] , "r");
if (pFile == NULL) {
perror ("Error opening file");
} else {
fgets (string , 100 , pFile);
puts (string);
fclose (pFile);
}
return 0;
}
This example reads the first line or the first 100 characters (whichever come first) of a given file and print it to the screen.
- OUTPUT
$ gcc -Wall fgets.c $ ./a.out Error opening file: Bad address $ ./a.out test.txt abcdefghi123456789abcdefghi123456789
- EXAMPLE
#include <stdio.h>
#define LINE_LENGTH 80
int main(int argc, char *argv[])
{
FILE* fp;
char line[LINE_LENGTH];
int count;
count = 0;
fp=fopen(argv[1],"r");
while ( fgets(line, LINE_LENGTH, fp) != NULL) {
count++;
}
printf("File contains %d lines.\n", count);
fclose(fp);
return 0;
}
The above program counts the number of lines in a file.
- OUTPUT
$ gcc -Wall fgets2.c $ ./a.out test.txt File contains 2 lines.
- EXAMPLE
#include <stdio.h>
#include <string.h>
int main(void)
{
char buff[80];
printf("Enter text > ");
fgets(buff, sizeof(buff), stdin);
buff[strlen(buff)-1] = '\0';
printf("Stripped (minus \\n) length is %d -%s-\n", strlen(buff), buff);
return 0;
}
This programs reads a string and outputs the length of the string minus the newline character.
- OUTPUT
$ gcc -Wall fgets3.c $ ./a.out Enter text > hello world Length is 11 -hello world-
fopen
- NAME
-
fopen - Open a file.
- SYNOPSIS
#include <stdio.h>
FILE *fopen (const char *filename, const char *mode);
- DESCRIPTION
-
Opens the file which name is stored in the
filename
string and returns a pointer to the file (stream). Operations allowed to the file returned are defined by the mode parameter:
"r" |
Open a file for reading. The file must exist. |
"w" |
Create an empty file for writing. If a file with the same name already exists its content is erased. |
"a" |
Append to a file. Writing operations append data at the end of the file. The file is created if it doesn’t exist. |
"r+" |
Open a file for reading and writing. The file must exist. |
"w+" |
Create an empty file for reading and writing. If a file with the same name already exists its content is erased before it is opened. |
"a+" |
Open a file for reading and appending. All writing operations are done at the end of the file protecting the previous content to be overwritten. You can reposition ( |
The mode parameter serves also to specify whether we want to open the file as text or binary, adding
t
or b
characters to this access mode string.
t |
Text mode. In text mode the end of file is assumed to be at first Ctrl-Z character. Some conversions can occur reading and writing with End Of Line / Feedback characters depending on your compiler and your Operating System. |
b |
Binary mode. End of file is reached at last byte of the file. No conversions. |
This additional t
or b
characters can be appended to the read/write
mode at the end of the string (like "rb", "wt", "r+t", "w+b" …)
or can be inserted between the letter and the "" character (like "rt
", "wb+").
If t
nor b
are given, the default method is used (commonly t
). Most compilers use the default method specified by the global variable _fmode
defined in stdio.h
.
- RETURN VALUE
-
If the file has been successfully opened the function will return a pointer to the file. Otherwise a NULL pointer is returned.
- SEE ALSO
-
fclose
,fputc
,fgetc
,fread
,fwrite
- EXAMPLE
#include <stdio.h>
int main (int argc, char * argv[])
{
FILE * pFile;
pFile = fopen (argv[1],"wt");
if (pFile!=NULL) {
fputs ("fopen example\n",pFile);
fclose (pFile);
}
return 0;
}
- OUTPUT
$ gcc -Wall fopen.c $ ./a.out test.txt $ cat test.txt fopen example
- EXAMPLE
#include <stdio.h>
int main(int argc, char *argv[])
{
int c;
FILE *ptr;
ptr = fopen(argv[1],"r");
while ((c = fgetc(ptr)) != EOF) {
printf("%c",c);
}
fclose(ptr);
return 0;
}
- OUTPUT
$ gcc -Wall fopen2.c $ ./a.out test.txt fopen example
fprintf
- NAME
-
fprintf - Print formatted data to a stream..
- SYNOPSIS
#include <stdio.h>
int fprintf (FILE *stream , const char *format [ , argument , ...] );
- DESCRIPTION
-
Prints to the specified stream a sequence of arguments formatted as the format argument specifies.
- PARAMETERS
-
-
stream - Pointer to an open file.
-
format - String that contains the text to be printed. Optionally it can contain format tags that are substituted by the values specified in subsequent argument(s) and formatted as requested. The number of format tags must correspond with the number of additional arguments that follows.
-
The format tags follow this prototype:
%[flags][width][.precision][modifiers]type
where type
is the most significant and defines how the value will be printed:
type | Output | Example |
---|---|---|
c |
Character |
a |
d or i |
Signed decimal integer |
392 |
e |
Scientific notation (mantise/exponent) using e character |
3.9265e2 |
E |
Scientific notation (mantise/exponent) using E character |
3.9265E2 |
f |
Decimal floating point |
392.650000 |
g |
Use shorter %e or %f |
392.65 |
G |
Use shorter %E or %f |
392.65 |
o |
Signed octal |
610 |
s |
String of characters |
"sample" |
u |
Unsigned decimal integer |
7235 |
x |
Unsigned hexadecimal integer |
7fa |
X |
Unsigned hexadecimal integer (capital letters) |
7FA |
p |
Address pointed by the argument |
B800:0000 |
n |
Nothing printed. The argument must be a pointer to integer where the number of characters written so far will be stored. |
The other parameters flags
, width
, precision
and modifiers
are optional and follow these specifications:
flags | meaning |
---|---|
- |
Left align within the given width. (right align is the default). |
+ |
Forces to prepend the result with a sign (+ or -) if signed type. (by default only - (minus) is printed). |
blank |
If the argument is a positive signed value, a blank is inserted before the number. |
# |
Used with |
width | meaning |
---|---|
number |
Minimum number of characters to be printed. If the value to be printed is shorter than this number the result is padded with blanks. The value is never truncated even if the result is larger. |
0number |
Same as above but filled with 0s instead of blanks. |
* |
The width is not specified in the format string, it is specified by an integer value preceding the argument has has to be formatted. |
.precision | meaning |
---|---|
.number |
for |
modifier | meaning (influences on how arguments are interpreted by the function) |
---|---|
h |
argument is interpreted as short |
l |
argument is interpreted as |
L |
argument is interpreted as |
argument(s) - Optional parameter(s) that contain the data to be inserted instead of % tags specified in format parameter. There must be the same number of these parameter than the number of format tags.
- RETURN VALUE
-
On success, the total number of characters printed is returned. On error, a negative number is returned.
- SEE ALSO
-
printf
,fscanf
- EXAMPLE
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[])
{
FILE * pFile;
int n;
char name[100];
pFile = fopen (argv[1],"w");
for (n=0 ; n<3 ; n++) {
printf("Enter a name> ");
fgets(name, sizeof(name), stdin);
name[strlen(name)-1] = '\0';
fprintf (pFile, "Name %d [%-10.10s]\n",n,name);
}
fclose (pFile);
return 0;
}
This example prompts 3 times the user for a
name and then writes them to given file each one in a line with a fixed
length (a total of 19 characters + newline). Two format tags are used: %d
(Signed decimal integer) and %-10.10s
(left aligned -
, minimum of 10 characters 10
, maximum of 10 characters .10
, String s
).
- OUTPUT
$ gcc -Wall fprintf.c $ ./a.out test.txt Enter a name> Jonas Enter a name> Bernhard Enter a name> Thomas $ cat test.txt Name 0 [Jonas ] Name 1 [Bernhard ] Name 2 [Thomas ]
- EXAMPLE
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *ptr;
char line[256];
ptr = fopen(argv[1], "w");
if (ptr==NULL)
perror("fopen error");
while(1) {
fgets(line, sizeof(line),stdin);
if (line[0] == '\n')
break;
line[strlen(line)-1] = '\0';
fprintf(ptr, "%s\n", line);
}
fclose(ptr);
return 0;
}
- OUTPUT
$ gcc -Wall fprintf2.c $ ./a.out test.txt This string goes to the file ... $ cat test.txt This string goes to the file ...
fputc
- NAME
-
fputc - Write character to stream.
- SYNOPSIS
#include <stdio.h>
int fputc(int character, FILE *stream);
- DESCRIPTION
-
Writes character to the current position in the specified stream and increases the file position pointer to the next character.
- PARAMETERS
-
-
character - Character to be written. Although it is declared as
int
, the function converts it tounsigned char
before writing it. -
stream - pointer to an open file.
-
- RETURN VALUE
-
If there are no errors the written character is returned. If an error occurs, EOF is returned.
- SEE ALSO
-
fgetc
,fread
,fwrite
,fopen
,putc
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[])
{
FILE *pFile;
char c;
pFile = fopen (argv[1],"w");
if (pFile!=NULL) {
for (c = 'A' ; c <= 'Z' ; c++) {
fputc (c , pFile);
}
fputc('\n', pFile);
fclose (pFile);
}
return 0;
}
- OUTPUT
$ gcc -Wall fputc.c $ ./a.out test.txt $ cat test.txt ABCDEFGHIJKLMNOPQRSTUVWXYZ
- EXAMPLE
#include <stdio.h>
int main(int argc, char *argv[])
{
int c;
FILE *iFile;
FILE *oFile;
iFile = fopen(argv[1],"r");
oFile = fopen(argv[2],"w");
while ((c = fgetc(iFile)) != EOF) {
fputc(c, oFile);
}
fclose(iFile);
fclose(oFile);
return 0;
}
This program can be used to copy a file (e.g. similar to the Unix cp command, although without parameters).
- OUTPUT
$ gcc -Wall fputc2.c $ echo 'Hello World!' > src.txt $ cat src.txt Hello World! $ ./a.out src.txt dest.txt $ cat dest.txt Hello World!
fputchar
- NAME
-
fputchar - Write character to stdout.
- SYNOPSIS
#include <stdio.h>
int fputchar (int character);
- DESCRIPTION
-
Writes character to standard output. It is equivalent to
fputchar(character,stdout)
. - PARAMETERS
-
-
character - Character to be written. Although it is declared as
int
, the function converts it tounsigned char
before writing it.
-
- RETURN VALUE
-
The value returned is the written character. If an error occurs, EOF is returned.
Not defined in ANSI-C, however, supported by most compilers. |
- SEE ALSO
-
fputc
,fgetc
,putchar
- EXAMPLE
-
This program writes ABCDEFGHIJKLMNOPQRSTUVWXYZ to the standard output (screen).
fputs
- NAME
-
fputs - Write string to a stream.
- SYNOPSIS
#include <stdio.h>
int fputs (const char *string , FILE *stream);
- DESCRIPTION
-
Writes string to the current position of the given stream. The function begins copying from the address specified (string) until it reaches a null character (
\0
) that ends the string. The final null-character is not copied to the stream. - PARAMETERS
-
-
string - Null-terminated string to be written.
-
stream - pointer to an open file.
-
- RETURN VALUE
-
On success, a non-negative value is returned. On error the function returns EOF.
- SEE ALSO
-
fgets
,gets
,puts
,fprintf
,fscanf
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[])
{
FILE *pFile;
char sentence [256];
printf ("Enter sentence to append> ");
fgets (sentence,255,stdin);
pFile = fopen (argv[1],"at");
if (pFile==NULL)
perror("fopen error");
fputs(sentence,pFile);
fclose (pFile);
return 0;
}
This program allows to append a line to a given file each time you run it.
- OUTPUT
$ gcc -Wall fputs.c $ cat src.txt Hello World! $ ./a.out src.txt Enter sentence to append> !dlroW olleH $ cat src.txt Hello World! !dlroW olleH
fread
- NAME
-
fread - Read a block of data from a stream.
- SYNOPSIS
#include <stdio.h>
int fread (void *buffer, size_t size, size_t count, FILE *stream);
- DESCRIPTION
-
Read count number of items each one with a size of size bytes from the stream and stores it in the specified buffer. Stream’s position indicator is increased by the number of bytes read. Total amount of bytes read is (size * count).
- PARAMETERS
-
-
buffer - Pointer to the destination structure with a minimum size of (
size*count
) bytes. -
size - Size in bytes of each item to be read.
-
count - Number of items, each one with a size of size bytes.
-
stream - pointer to an open file.
-
- RETURN VALUE
-
The total number of items read is returned. If this number differs from the requested amount (count parameter) an error has occurred or End Of File has been reached. To determine what happened call
feof
orferror
. - SEE ALSO
-
fgetc
,fread
,fwrite
,fopen
- EXAMPLE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char * argv[])
{
FILE * pFile;
long lSize;
char *buffer;
int i;
pFile = fopen (argv[1] , "rb" );
if (pFile==NULL)
perror("fopen error");
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
buffer = (char*) malloc (lSize);
if (buffer==NULL)
perror("malloc error");
fread (buffer,1,lSize,pFile);
buffer[strlen(buffer)-1] = '\0';
for (i=strlen(buffer); i>=0; i--)
printf("%c", buffer[i]);
printf("\n");
fclose (pFile);
free (buffer);
return 0;
}
This code loads the contents of a file into a buffer, outputs the read text in reverse order and finally terminates.
- OUTPUT
$ gcc -Wall fread.c $ cat test.txt 0123456789 abcdefghijklmnopqrstuvwxyz $ ./a.out test.txt zyxwvutsrqponmlkjihgfedcba 9876543210
freopen
- NAME
-
freopen - Reopen a stream with a different file and mode.
- SYNOPSIS
#include <stdio.h>
FILE *freopen (const char *filename , const char *mode , FILE *stream);
- DESCRIPTION
-
freopen
first tries to close any file already open associated with the given stream. Then, whether the stream was closed or not,freopen
opens the file which name is pointed byfilename
string and associates it with the specified stream. - PARAMETERS
-
-
filename - name of the file to be opened. This parameter must follow operating system’s specifications and can include a path if the system supports it.
-
stream - pointer to open file that has to be reopened.
-
mode - type of access requested. It can be:
-
"r" |
Open a file for reading. The file must exist. |
"w" |
Create an empty file for writing. If a file with the same name already exists its content is erased. |
"a" |
Append to a file. Writing operations append data at the end of the file. The file is created if it doesn’t exist. |
"r+" |
Open a file for reading and writing. The file must exist. |
"w+" |
Create an empty file for reading and writing. If a file with the same name already exists its content is erased before it is opened. |
"a+" |
Open a file for reading and appending. All writing operations are done at the end of the file protecting the previous content to be overwritten. You can reposition ( |
The mode parameter serves also to specify whether we want to open the file as text or binary, adding t
or b
characters to this access mode string.
t |
Text mode. In text mode the end of file is assumed to be at first |
b |
Binary mode. End of file is reached at last byte of the file. No conversions. |
This additional t
or b
characters can be appended to the read/write mode at the end of the string (like "rb"
, "wt"
, "r+t"
, "w+b"
…) or can be inserted between the letter and the +
character (like "rt+"
, "wb+"
). If t
nor b
are given the default method (commonly t
) is used. In most compilers this default method is specified by the global variable _fmode
defined in stdio.h
.
- RETURN VALUE
-
If the file has been successfully reopened the function returns a pointer to the file. Otherwise a NULL pointer is returned.
- SEE ALSO
-
fopen
,fclose
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[])
{
freopen (argv[1],"w",stdout);
printf ("This sentence is redirected to a file.\n");
fclose (stdout);
return 0;
}
This sample code redirects the output that normally would go to standard output to a file, that after
this program is executed contains: This sentence is redirected to a file.
- OUTPUT
$ gcc -Wall freopen.c $ ./a.out test.txt $ cat test.txt This sentence is redirected to a file.
fscanf
- NAME
-
fscanf - Read formatted data from a stream.
- SYNOPSIS
#include <stdio.h>
int fscanf( FILE *stream , const char *format [ , argument , ...] );
- DESCRIPTION
-
Reads data from the current position of stream and stores it into the locations given by argument(s). Locations pointed by each argument are filled with their corresponding type of value requested in the format string. There must be the same number of type specifiers in format string than arguments passed.
- PARAMETERS
-
-
stream - Pointer to an open file.
-
format - String that can contain one or more of these items:
-
- Whitespace characters
-
the function will read and ignore any whitespace characters (this includes blank, newline and tab characters) encountered before the next non-whitespace character. This includes any quantity of whitespace characters (including none).
- Non-whitespace characters
-
(any character not including blank, newline, tab, or any format specifier beginning with
%
character): this cause that the function read and discard any character that match the given non-whitespace character. If this character is not found the function ends returning error. - Format specifiers
-
A sequence of characters begining with
%
indicates that next data has to be read and stored at the location pointed by its corresponding argument with a given format that is specified following this prototype:%[*][width][modifiers]type
where:
* |
Data is read but ignored. It is not assigned to the corresponding argument. |
width |
Specifies the maximum number of characters to be read. |
modifiers |
Specifies a different size for the data pointed by argument:
|
type |
Character specifying the type of data that is expected and how it has to be read. See next table. |
type | qualifying input | required argument |
---|---|---|
c |
Single character: Reads the next character (whitespace characters included). |
char * |
d |
Decimal integer: Number optionally prepended with a sign. |
int * |
e,E,f,g,G |
Floating point: Decimal number containing a decimal point, optionally prepended by a sign and optionally followed by the |
float * |
o |
Octal integer. |
int * |
s |
String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are blank, newline and tab). |
char *(string) |
u |
Unsigned decimal integer. |
unsigned int * |
x |
Hexadecimal integer. |
int * |
argument(s) - pointer to objects or structures to be filled with data read as specified by format
string. There must be the same number of these parameters than the number of format tags. NOTE: These arguments must be pointers: if you want to store the result of a scanf
operation on a standard variable you should precede it with the reference operator, i.e. an ampersand sign: &
- RETURN VALUE
-
The number of items successfully read. This count doesn’t include any ignored fields. If EOF is returned an error has occurred before the first assignation could be done.
- SEE ALSO
-
scanf
,fprintf
,fopen
,fclose
- EXAMPLE
#include <stdio.h>
#include <math.h>
int main (int argc, char *argv[])
{
char str [80];
float f;
FILE * pFile;
pFile = fopen (argv[1],"w+");
if (pFile==NULL)
perror("fopen error");
fprintf (pFile, "%f %s\n", M_PI, "PI");
rewind (pFile);
fscanf (pFile, "%f", &f);
fscanf (pFile, "%s", str);
fclose (pFile);
printf ("I have read: %f and %s \n",f,str);
return 0;
}
This sample code creates a file using the given command-line argument as file name and (1) stores a float number and a string, then, (2) the stream is rewinded and both values are read with fscanf
. Finally (3) the program prints respective information to stdout.
- OUTPUT
$ gcc -Wall -lm fscanf.c $ ./a.out test.txt I have read: 3.141593 and PI $ cat test.txt 3.141593 PI
fseek
- NAME
-
fseek - Reposition stream’s position indicator.
- SYNOPSIS
#include <stdio.h>
int fseek( FILE *stream , long offset , int origin );
- DESCRIPTION
-
Sets the position indicator associated with the stream to a new position defined by an offset from the location given by the origin parameter. The End-Of-File indicator of this stream is cleared after a call to
fseek
.
When using fseek
on files opened in text mode consider that you can
only be sure of the results if an offset of 0 or an offset equal to
a value returned from ftell
is specified, any other offset value
makes result unpredictable because of carriage-return translations
under this mode.
The next operation with the stream after a call to fseek
can be
either for input or output.
- PARAMETERS
-
-
stream - Pointer to an open file.
-
offset - Number of bytes from origin.
-
origin - Initial position from where offset is applied. It can be any of these constants defined in
stdio.h
:-
SEEK_SET (0) Beginning of file.
-
SEEK_CUR (1) Current position of the file pointer.
-
SEEK_END (2) End of file.
-
-
- RETURN VALUE
-
If successful the function returns 0. Otherwise it returns nonzero.
- SEE ALSO
-
fopen
,fsetpos
,ftell
,rewind
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[])
{
FILE * pFile;
pFile = fopen (argv[1],"w");
fputs ("This is an apple.\n",pFile);
fseek (pFile,9,SEEK_SET);
fputs (" sam",pFile);
fclose (pFile);
return 0;
}
The above example first writes This is an apple.
to a file. Next, the file pointer is re-positioned and part of the text gets overwritten.
- OUTPUT
$ gcc -Wall fseek.c $ ./a.out test.txt $ cat test.txt This is a sample.
fsetpos
- NAME
-
fsetpos - Reposition file pointer to a saved location.
- SYNOPSIS
#include <stdio.h>
int fsetpos ( FILE *stream , const fpos_t *position );
- DESCRIPTION
-
Sets the file pointer associated with stream to a new position. The position parameter is a value previously obtained by a call to
fgetpos
. After a call to this function, the End-Of-File indicator of the stream is cleared and any effect of a previous call toungetc
is undone. The next operation with the stream after a call tofsetpos
can be either for input or output. - PARAMETERS
-
-
stream - Pointer to an open file.
-
position - Position value obtained from a previous call to
fgetpos
that indicates the position of the file pointer at that moment.
-
- RETURN VALUE
-
If successful the function returns 0. Otherwise it returns nonzero and sets the global variable errno to a non-zero value.
- SEE ALSO
-
fopen
,fgetpos
,fseek
,ftell
,frewind
- EXAMPLE
#include <stdio.h>
int main (int argc, char * argv[])
{
FILE * pFile;
fpos_t position;
pFile = fopen (argv[1],"w");
fgetpos (pFile, &position);
fputs ("That is a sample.\n",pFile);
fsetpos (pFile, &position);
fputs ("This",pFile);
fclose (pFile);
return 0;
}
The above example first obtains the actual position of the file pointer. Next, it writes That is a sample.
to the file. Than the file pointer is re-positioned using fsetpos
and parts of the text get overwritten.
- OUTPUT
$ gcc -Wall fsetpos.c $ ./a.out test.txt $ cat test.txt This is a sample.
ftell
- NAME
-
ftell - Return the current position in a stream.
- SYNOPSIS
#include <stdio.h>
long ftell ( FILE *stream );
- DESCRIPTION
-
Returns the current position pointed by the position indicator of the stream. When a file has been opened in binary mode the value obtained corresponds to the number of bytes from the beginning of the file. In files opened in text-mode this is not granted because of carriage-return translations under that mode. The value returned is valid for further calls to
fseek
. - PARAMETERS
-
-
stream - Pointer to an open file.
-
- RETURN VALUE
-
On success, the current file pointer position is returned. If an error occurs -1 is returned and the global variable errno is set to a positive value. If the stream is unable to perform seeking operations the return value is undefined.
- SEE ALSO
-
fopen
,fseek
,fgetpos
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[])
{
FILE * pFile;
long size;
pFile = fopen (argv[1],"rb");
if (pFile==NULL) {
perror ("Error opening file");
} else {
fseek (pFile, 0, SEEK_END);
size=ftell(pFile);
fclose (pFile);
printf ("Size of %s: %ld bytes.\n",argv[1], size);
}
return 0;
}
This program opens a file for reading and calculates its size by simply positioning the file-pointer to the end.
- OUTPUT
$ gcc -Wall ftell.c $ ./a.out test.txt Size of test.txt: 18 bytes.
fwrite
- NAME
-
fwrite - Write a block of data to a stream.
- SYNOPSIS
#include <stdio.h>
size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );
- DESCRIPTION
-
Writes count number of items, each one with a size of size bytes, from the memory block pointed by buffer to the current position in the stream. Stream’s position indicator is increased by the number of bytes written. On files opened in text mode some translations may occur with carriage-return and line-feed characters. The total number of bytes to be written is (size x count). Normally the parameter size should contain the size of each item (
char
,int
,long
, structures …) to be written and count the number of these items. But this is not absolute, you can specify any combination of numbers which result of (size x count
) match the size in bytes of the block to be written. - PARAMETERS
-
-
buffer - Pointer to data to be written.
-
size - Size in bytes of each item that has to be written.
-
count - Number of items, each one with a size of size bytes.
-
stream - Pointer to an open file with writing access.
-
- RETURN VALUE
-
Number of full items (not bytes) successfully written. This may be less than the specified in count parameter if an error occurred.
- SEE ALSO
-
fread
,fscanf
,getc
,fgetc
- EXAMPLE
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[])
{
FILE * pFile;
char buffer[] = "This buffer contains some characters.\n";
pFile = fopen (argv[1] , "w");
fwrite (buffer , 1 , strlen(buffer) , pFile);
fclose (pFile);
return 0;
}
- OUTPUT
$ gcc -Wall fwrite.c $ ./a.out test.txt $ cat test.txt This buffer contains some characters.
getc
- NAME
-
getc - Get the next character.
- SYNOPSIS
#include <stdio.h>
int getc(FILE *stream);
- DESCRIPTION
-
Returns the next character of the stream and increases the file pointer to point to the next character. This routine is normally implemented as a macro with the same result as
fgetc()
. - PARAMETERS
-
-
stream - Pointer to an open file.
-
- RETURN VALUE
-
The character read is returned as an
int
value. If the End Of File has been reached or there has been an error reading, the function returns EOF. You can useferror()
orfeof()
to determine whether an error happened or the End-Of-File was reached. - SEE ALSO
-
fputc
,fread
,fwrite
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[])
{
FILE * pFile;
char c;
int n = 0;
pFile = fopen(argv[1],"r");
if (pFile==NULL) {
perror ("Error opening file");
} else {
do {
c = getc (pFile);
if (c == 'a')
n++;
} while (c != EOF);
fclose (pFile);
printf ("File contains %d 'a' characters.\n",n);
}
return 0;
}
- OUTPUT
$ gcc -Wall getc.c $ cat test.txt This buffer contains some characters. $ ./a.out test.txt File contains 3 'a' characters.
getchar
- NAME
-
getchar - Get the next character from STDIN.
- SYNOPSIS
#include <stdio.h>
int getchar( void );
- DESCRIPTION
-
Returns the next character from the standard input (stdin). It corresponds to:
getc(stdin)
- RETURN VALUE
-
The character read is returned as int. If the End-of-File is reached or there has been an error reading, the function returns
EOF
.EOF
can indicate either the End-of-File or an error while reading. You can useferror()
andfeof()
to determine which happened. - SEE ALSO
-
getc
,putchar
,fgetc
,fopen
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[])
{
FILE * pFile;
char c;
int n = 0;
pFile = fopen(argv[1],"r");
if (pFile==NULL) {
perror ("Error opening file");
} else {
do {
c = getc (pFile);
if (c == 'a')
n++;
} while (c != EOF);
fclose (pFile);
printf ("File contains %d 'a' characters.\n",n);
}
return 0;
}
- OUTPUT
$ gcc -Wall getchar.c $ ./a.out Enter some text ... hello hello
perror
- NAME
-
perror - Print error message.
- SYNOPSIS
#include <stdio.h>
void perror(const char *string);
- DESCRIPTION
-
Transcribes the the value of the global variable
errno
into a string and prints that string tostderr
(standard error output, generally the screen).errno
describes the last error produced by a call to a library routine. It is an index for the global variablesys_errlist
that contains an array of strings describing library routine errors. These error strings do not include the ending newline character (\n
). The number of entries is defined by the global variablesys_nerr
. If the parameter string is not NULL, string is printed followed by a colon (:) and the error description. After the error description a newline character (\n
) is appended. The standard convention is to pass the program name as the string parameter.perror
should be called right after a library routine returns an error or it can be overwritten by further calls. - PARAMETERS
-
-
string - Message to be printed before the error message.
-
- RETURN VALUE
-
None
- SEE ALSO
-
clearerr
,ferror
,feof
- EXAMPLE
#include <stdio.h>
int main (int arghc, char *argv[])
{
FILE * pFile;
pFile = fopen (argv[1],"rb");
if (pFile==NULL) {
perror ("fopen error");
} else {
fclose (pFile);
}
return 0;
}
- OUTPUT
$ gcc -Wall perror.c $ ./a.out nonexist.txt fopen error: No such file or directory $ ./a.out perror.c
printf
- NAME
-
printf - Print formatted data to STDOUT.
- SYNOPSIS
#include <stdio.h>
int printf( const char *format [ , argument , ...] );
- DESCRIPTION
-
Prints to standard output (stdout) a sequence of arguments formatted as the format argument specifies.
- PARAMETERS
-
-
format - String that contains the text to be printed.
-
Optionally it can contain format tags that are substituted by the
values specified in subsequent argument(s) and formatted as
requested. The number of format tags must correspond to the number
of additional arguments that follows. The format tags follow this
prototype: %[flags][width][.precision][modifiers]type
where
type
is the most significant and defines how the value will be
printed:
-
format - String that contains the text to be printed. Optionally it can contain format tags that are substituted by the values specified in subsequent argument(s) and formatted as requested. The number of format tags must correspond with the number of additional arguments that follows.
The format tags follow this prototype:
%[flags][width][.precision][modifiers]type
where type
is the most significant and defines how the value will be printed:
type | Output | Example |
---|---|---|
c |
Character |
a |
d or i |
Signed decimal integer |
392 |
e |
Scientific notation (mantise/exponent) using e character |
3.9265e2 |
E |
Scientific notation (mantise/exponent) using E character |
3.9265E2 |
f |
Decimal floating point |
392.650000 |
g |
Use shorter %e or %f |
392.65 |
G |
Use shorter %E or %f |
392.65 |
o |
Signed octal |
610 |
s |
String of characters |
"sample" |
u |
Unsigned decimal integer |
7235 |
x |
Unsigned hexadecimal integer |
7fa |
X |
Unsigned hexadecimal integer (capital letters) |
7FA |
p |
Address pointed by the argument |
B800:0000 |
n |
Nothing printed. The argument must be a pointer to integer where the number of characters written so far will be stored. |
The other parameters flags
, width
, precision
and modifiers
are optional and follow these specifications:
flags | meaning |
---|---|
- |
Left align within the given width. (right align is the default). |
+ |
Forces to prepend the result with a sign (+ or -) if signed type. (by default only - (minus) is printed). |
blank |
If the argument is a positive signed value, a blank is inserted before the number. |
# |
Used with |
width | meaning |
---|---|
number |
Minimum number of characters to be printed. If the value to be printed is shorter than this number the result is padded with blanks. The value is never truncated even if the result is larger. |
0number |
Same as above but filled with 0s instead of blanks. |
* |
The width is not specified in the format string, it is specified by an integer value preceding the argument has has to be formatted. |
.precision | meaning |
---|---|
.number |
for |
modifier | meaning (influences on how arguments are interpreted by the function) |
---|---|
h |
argument is interpreted as short |
l |
argument is interpreted as |
L |
argument is interpreted as |
argument(s) - Optional parameter(s) that contain the data to be inserted instead of % tags specified in format parameter. There must be the same number of these parameter than the number of format tags.
- RETURN VALUE
-
On success, the total number of characters printed is returned. On error, a negative number is returned.
- SEE ALSO
-
fprintf
,scanf
- EXAMPLE
#include <stdio.h> int main (void) { printf ("Characters: %c %c \n", 'a', 65); printf ("Decimals: %d %ld\n", 1977, 6500000L); printf ("Preceding with blanks: %10d \n", 1977); printf ("Preceding with zeros: %010d \n", 1977); printf ("Some different radices: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100); printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416); printf ("Width trick: %*d \n", 5, 10); printf ("%s \n", "A string"); return 0; }
- OUTPUT
$ gcc -Wall printf.c $ ./a.out Characters: a A Decimals: 1977 6500000 Preceding with blanks: 1977 Preceding with zeros: 0000001977 Some different radices: 100 64 144 0x64 0144 floats: 3.14 +3e+00 3.141600E+00 Width trick: 10 A string
putc
- NAME
-
putc - Write character to stream.
- SYNOPSIS
#include <stdio.h>
int putc (int character, FILE *stream);
- DESCRIPTION
-
Writes character to the current position in the specified stream and increase the file pointer to point to next character. This routine is normally implemented as a macro with the same result as
fputc
. - PARAMETERS
-
-
character - Character to be written. The function casts the
int
parameter to anunsigned char
equivalent before writing it. -
stream - Pointer to an open file.
-
- RETURN VALUE
-
In case there are no errors the written character is returned. If an error occurs, EOF is returned.
- SEE ALSO
-
fgetc
,fputc
,fwrite
,getchar
,putchar
- EXAMPLE
#include <stdio.h>
int main (int argc, char*argv[])
{
FILE * pFile;
char c;
pFile=fopen(argv[1],"wt");
if (pFile==NULL)
perror("fopen error");
for (c = 'A' ; c <= 'Z' ; c++) {
putc (c , pFile);
}
putc('\n',pFile);
fclose (pFile);
return 0;
}
- OUTPUT
$ gcc -Wall putc.c $ ./a.out test.txt $ cat test.txt ABCDEFGHIJKLMNOPQRSTUVWXYZ
putchar
- NAME
-
putchar - Write character to STDOUT.
- SYNOPSIS
#include <stdio.h>
int putchar(int c);
- DESCRIPTION
-
Writes character to the current position in the standard output (stdout) and increases the file pointer to point to next character. This routine corresponds to:
putc(character,stdout)
. - PARAMETERS
-
-
character - Character to be written. Although it is declared as
int
, the function converts it tounsigned char
before it writes it.
-
- RETURN VALUE
-
The value returned is the written character. If an error occurs, EOF is returned. Note that when you work with binary files EOF is a valid character and you must use
ferror()
function to check if it has been an error. - SEE ALSO
-
putc
,fputc
,getchar
- EXAMPLE
#include <stdio.h>
int main (void)
{
char c;
for (c = 'A' ; c <= 'Z' ; c++) {
putchar(c);
}
putchar('\n');
return 0;
}
- OUTPUT
$ gcc -Wall putchar.c $ ./a.out ABCDEFGHIJKLMNOPQRSTUVWXYZ
puts
- NAME
-
puts - Output a string to stdout.
- SYNOPSIS
#include <stdio.h>
int puts (const char * string );
- DESCRIPTION
-
Copies the string to standard output stream (stdout) and appends a new line character (
\n
). - PARAMETERS
-
-
string - Null-terminated string to be outputed.
-
- RETURN VALUE
-
On success, a non-negative value is returned. On error EOF value is returned.
- SEE ALSO
-
putc
,gets
,printf
- EXAMPLE
#include <stdio.h>
int main (void)
{
char string [] = "Hello world!";
puts(string);
return 0;
}
- OUTPUT
$ gcc -Wall puts.c $ ./a.out Hello world!
remove
- NAME
-
remove - Delete a file.
- SYNOPSIS
#include <stdio.h>
int remove( const char *filename );
- DESCRIPTION
-
Deletes the file specified by filename. It is compiled as a call to the system function for deleting files (unlink, erase or del).
- PARAMETERS
-
-
filename - Path and name of the file to be removed.
-
- RETURN VALUE
-
If the file is successfully deleted a 0 value is returned. On error a non-zero value is returned and the errno variable is set with the corresponding error code that that can be printed with a call to perror.
- SEE ALSO
-
rename
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[])
{
if( remove(argv[1]) == -1 )
perror( "Error deleting file" );
else
puts( "File successfully deleted" );
return 0;
}
- OUTPUT
$ gcc -Wall remove.c $ ls src.txt src.txt $ ./a.out src.txt File successfully deleted $ ls src.txt ls: cannot access src.txt: No such file or directory
rename
- NAME
-
rename - Rename a file or directory.
- SYNOPSIS
#include <stdio.h>
int rename(const char *oldname , const char *newname);
- DESCRIPTION
-
Renames the file or directory specified by
oldname
tonewname
. Ifoldname
andnewname
specify different paths the file is moved. - PARAMETERS
-
-
oldname - Path and name of the file to be renamed or moved. This file must exist and we must have write access to it.
-
newname - New path and name for the file. This filename must not be the same of an existing one.
-
- RETURN VALUE
-
If the file is successfully renamed/moved a 0 value is returned. On error a non-zero value is returned and the
errno
variable is set to the corresponding error code that can be printed usingperror
. - SEE ALSO
-
remove
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[1])
{
int result;
result = rename( argv[1] , argv[2] );
if (result != 0)
perror( "Error renaming file" );
return 0;
}
- OUTPUT
$ ./a.out old.txt new.txt $ cat new.txt Hello World! $ cat old.txt cat: old.txt: No such file or directory
If the file old.txt
exists before execution and we meet the permission requirements to call this function the file will be renamed to new.txt
, otherwise a message similar to STDERR: Error renaming file: Permission denied
will be output.
rewind
- NAME
-
rewind - Repositions the file pointer to the beginning of a stream.
- SYNOPSIS
#include <stdio.h>
void rewind ( FILE *stream );
- DESCRIPTION
-
Sets the file pointer associated with the stream to the beginning of the file. A call to
rewind
is equivalent to:fseek(stream , 0L , SEEK_SET);
except that unlikefseek
, usingrewind
the error indicator is cleared. The next operation with the stream after a call tofseek
can be either for input or output. This function is also useful for clearing the keyboard buffer (normally associated with stdin). - PARAMETERS
-
-
stream - Pointer to an open file.
-
- RETURN VALUE
-
None.
- SEE ALSO
-
fseek
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[])
{
int n;
FILE * pFile;
char buffer [27];
pFile = fopen (argv[1],"w+");
for ( n='A' ; n<='Z' ; n++)
fputc (n, pFile);
fputc('\n', pFile);
rewind(pFile);
fread (buffer,1,26,pFile);
fclose (pFile);
buffer[26]='\0';
puts (buffer);
return 0;
}
A file is created for reading and writing and filled with the alphabet. The file is rewinded, read and its content is stored in a buffer. Finally, the read content is written to the standard output (screen).
- OUTPUT
$ gcc -Wall rewind.c $ ./a.out file.txt ABCDEFGHIJKLMNOPQRSTUVWXYZ $ cat file.txt ABCDEFGHIJKLMNOPQRSTUVWXYZ
scanf
- NAME
-
scanf - Read formatted data from STDIN.
- SYNOPSIS
#include <stdio.h>
int scanf(const char *format [ , argument , ...]);
- DESCRIPTION
-
Reads data from the standard input (stdin) and stores it into the locations given by argument(s). Locations pointed by each argument are filled with their corresponding type of value requested in the format string. There must be the same number of type specifiers in format string than arguments passed.
- PARAMETERS
-
-
format - String that can contain one or more of these items:
-
Whitespace characters: the function will read and ignore any whitespace characters (this includes blank, newline and tab characters) encountered before the next non-whitespace character. This includes any quantity of whitespace characters (including none).
-
Non-whitespace characters (any character not including blank, newline, tab, or any format specifier beginning with % character): this cause that the function read and discard any character that match the given non-whitespace character. If this character is not found the function ends returning error.
-
Format specifiers: A sequence of characters beginning with
'%'
indicates that next data has to be read and stored at the location pointed by its corresponding argument with a given format that is specified following this prototype:%[*][width][modifiers]type where:
-
-
* |
Data is read but ignored. It is not assigned to the corresponding argument. |
width |
Specifies the maximum number of characters to be read. |
modifiers |
Specifies a different size for the data pointed by argument: - h: short int - l: long int (if integer) or double (if floating point). - L: long double |
type |
Character specifying the type of data that is expected and how it has to be read. See next table. |
type | Qualifying Input | required argument |
---|---|---|
c |
Single character: Reads the next character (whitespace characters included). |
char * |
d |
Decimal integer: Number optionally preceded with a sign. |
int * |
e,E,f,g,G |
Floating point: Decimal number containing a decimal point, optionally preceded by a sign and optionally followed by the |
float * |
o |
Octal integer. |
int * |
s |
String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are blank, newline and tab). |
char *(string) |
u |
Unsigned decimal integer. |
unsigned int * |
x |
Hexadecimal integer. |
int * |
argument(s) - pointer to objects or structures to be filled with data read as specified by format
string. There must be the same number of these parameters than the number of format tags. NOTE: These arguments must be pointers: if you want to store the result of a scanf
operation on a standard variable you should precede it with the reference operator, i.e. an ampersand sign (&
), like in: scanf ("%d",&n);
- RETURN VALUE
-
The number of items successfully read. This count doesn’t include any ignored fields with asterisks (
*
). If EOF is returned an error has occurred before the first assignation could be done. - SEE ALSO
-
fscanf
,printf
,fopen
,fclose
- EXAMPLE
#include <stdio.h>
int main (void)
{
char str [80];
int i;
printf ("Enter your surname: ");
scanf ("%s",str);
printf ("Enter your age: ");
scanf ("%d",&i);
printf ("Mr. %s, %d years old.\n",str,i);
printf ("Enter a hexadecimal number: ");
scanf ("%x",&i);
printf ("You have entered %#x (%d).\n",i,i);
return 0;
}
- OUTPUT
$ gcc -Wall scanf.c $ ./a.out Enter your surname: Mayer Enter your age: 110 Mr. Mayer, 110 years old. Enter a hexadecimal number: AF You have entered 0xaf (175).
setbuf
- NAME
-
setbuf - Change stream buffering.
- SYNOPSIS
#include <stdio.h>
void setbuf ( FILE *stream , char *buffer );
- DESCRIPTION
-
Changes the buffer used for I/O operations with the specified stream, or, if the specified buffer is NULL it disables buffering with the stream. This function should be called once the file associated with the stream has been opened but before any input or output operation has been done. The buffer must point to an array BUFSIZ bytes long (BUFSIZ is defined in stdio.h). With buffered streams writing operations do not write directly to the device associated with them; the data is accumulated in the buffer and written to the device as a block. This can be forced flushing the stream by calling
fflush
or by closing the file (fclose
). All buffers are also flushed when program terminates. With unbuffered streams, data is directly written to the physical device on each writing operation. Normally, files are opened with a default allocated buffer, where this function can be used to define a user-allocated buffer or to disable buffering for the file. System standard streams likestdout
andstderr
are unbuffered by default if they are not redirected. - PARAMETERS
-
-
stream - Pointer to an open file.
-
buffer - User allocated buffer. Must have a length of BUFSIZ bytes.
-
- RETURN VALUE
-
None.
- SEE ALSO
-
fopen
,fflush
,setvbuf
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[])
{
char buffer[BUFSIZ];
FILE *pFile1, *pFile2;
pFile1=fopen (argv[1],"w");
if (pFile1==NULL)
perror("fopen error");
pFile2=fopen (argv[2],"a");
if (pFile2==NULL)
perror("fopen error");
setbuf(pFile1 , buffer );
fputs("This is sent to a buffered stream.\n",pFile1);
fflush(pFile1);
setbuf( pFile2 , NULL );
fputs("This is sent to an unbuffered stream.\n",pFile2);
fclose(pFile1);
fclose(pFile2);
return 0;
}
- OUTPUT
$ gcc -Wall setbuf.c $ ./a.out file1.txt file2.txt $ cat file1.txt This is sent to a buffered stream. $ cat file2.txt This is sent to an unbuffered stream.
Two files are opened with writing access. The stream associated with the file1.txt is set to a user allocated buffer; a writing operation to it is done; the data is logically part of the stream now and a reading operation to it can get this data, but it has not been physically written to the device until the fflush
has been called. The second buffer in the example, associated with the file2.txt, is set to unbuffered, so the subsequent output operation is directly written to the device.
setvbuf
- NAME
-
setvbuf - Change stream buffering.
- SYNOPSIS
#include <stdio.h>
int setvbuf(FILE *stream, char *buffer, int mode, size_t size);
- DESCRIPTION
-
Changes the buffer to be used for I/O operations with the specified stream. Size and mode for the buffer can be specified. This function should be called once the file associated with the stream has been opened but before any input or output operation has been done. The size of the buffer is specified by the size parameter, and can be any value between 2 and 32767 in bytes, this value may be rounded down by some system due to specific alignment. buffer can be NULL. In that case system dynamically allocates the amount of memory requested by size and uses it as buffer for the stream. The type parameter is used to specify if the buffer has to be fully buffered, line buffered or if the stream has to be unbuffered (see below). With buffered streams, writing operations do not write directly to the physical device associated with them; instead the data is accumulated in the buffer and written to the device as a block. This can be forced flushing the stream by calling
fflush
or by closing the file (fclose
). All buffers are also flushed when program terminates. With unbuffered streams, data is directly written to the device on each writing operation. Normally, files are opened with a default allocated buffer, where this function can be used to define a user-allocated buffer or to disable buffering for the file. System standard streams likestdout
andstderr
are unbuffered by default if they are not redirected. - PARAMETERS
-
-
stream - Pointer to an open file.
-
buffer - User allocated buffer. Must have at least a size of size bytes.
-
mode - Specifies a mode for file buffering.
-
size - Buffer size in bytes, must be more than 0 and less than 32768, this value may be rounded down by some systems due to specific alignment, in which case the minimum value should be 2.
-
mode | description |
---|---|
_IOFBF |
Full buffering: On output the data is written to the file once the buffer is full. On input the buffer is filled when an input operation is requested and buffer is empty. |
_IOLBF |
Line buffering: On output the data will be written to the file when a newline character is written to the stream or when the buffer is full, whatever happens first. On Input the buffer is filled when an input operation is requested and buffer is empty. |
_IONBF |
No buffering: No buffer is used. Each I/O operation is directly carried out to the file without buffering. buffer and size parameters are ignored. |
- RETURN VALUE
-
If the buffer is correctly assigned to the file a 0 value is returned. On error, a non-zero value is returned. This can be because an invalid type or size has been specified or because an error allocating memory (if NULL buffer was specified).
- SEE ALSO
-
fopen
,fflush
,setbuf
- EXAMPLE
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void wait(int seconds);
int main(void)
{
char buf[4] = "123";
if(setvbuf(stdout, buf, _IOFBF, sizeof(buf))!=0) {
perror("failed to change the buffer of stdout");
return EXIT_FAILURE;
}
putc(buf[0],stdout);
/* The buffer contains 1; nothing is written yet to stdout */
wait(3);
fflush(stdout); /* 1 is actually written to stdout */
if(setvbuf(stdout, NULL, _IONBF, 0)!=0) {
perror("failed to change the buffer of stdout");
return EXIT_FAILURE;
}
putc('2',stdout); /* 2 is written immediately */
wait(6);
if(setvbuf(stdout, buf, _IOLBF, sizeof(buf))!=0) {
perror("failed to change the buffer of stdout");
return EXIT_FAILURE;
}
putc('3',stdout); /* 3 is _not_ written here */
wait(9);
puts("..."); /* 3 is written here along with the \n */
return EXIT_SUCCESS;
}
void wait(int seconds)
{
int t;
t=0;
while (t < seconds)
t = clock()/CLOCKS_PER_SEC;
}
- OUTPUT
$ gcc -Wall setvbuf.c $ ./a.out 123...
The above example write 1
after approximately 3 seconds when the fflush()
is executed. 2
is written almost at the same time since the buffer is now in unbuffered mode.Finally, the buffer is set to line-buffered mode; thus 3
is written when puts()
outputs a terminating '\n'
. When puts()
would be missing, it would take up to the next '\n'
or (in this case) until the program terminates untzil the 3
would be output.
sprintf
- NAME
-
sprintf - Print formatted data to a string.
- SYNOPSIS
#include <stdio.h>
int sprintf ( char *buffer, const char *format [ , argument , ...] );
- DESCRIPTION
-
Writes a sequence of arguments to the given buffer formatted as the format argument specifies.
- PARAMETERS
-
-
buffer - Buffer where to store the resulting formatted string.
-
format - String that contains the text to be printed. Optionally it can contain format tags that are substituted by the values specified in subsequent argument(s) and formatted as requested. The number of format tags must correspond to the number of additional arguments that follows. The format tags follow this prototype:
%[flags][width][.precision][modifiers]type
where type is the most significant and defines how the value will be printed:
-
type | Output | Example |
---|---|---|
c |
Character |
a |
d or i |
Signed decimal integer |
392 |
e |
Scientific notation (mantise/exponent) using e character |
3.9265e2 |
E |
Scientific notation (mantise/exponent) using E character |
3.9265E2 |
f |
Decimal floating point |
392.650000 |
g |
Use shorter %e or %f |
392.65 |
G |
Use shorter %E or %f |
392.65 |
o |
Signed octal |
610 |
s |
String of characters |
"sample" |
u |
Unsigned decimal integer |
7235 |
x |
Unsigned hexadecimal integer |
7fa |
X |
Unsigned hexadecimal integer (capital letters) |
7FA |
p |
Address pointed by the argument |
B800:0000 |
n |
Nothing printed. The argument must be a pointer to integer where the number of characters written so far will be stored. |
The other parameters flags
, width
, precision
and modifiers
are optional and follow these specifications:
flags | meaning |
---|---|
- |
Left align within the given width. (right align is the default). |
+ |
Forces to prepend the result with a sign (+ or -) if signed type. (by default only - (minus) is printed). |
blank |
If the argument is a positive signed value, a blank is inserted before the number. |
# |
Used with |
width | meaning |
---|---|
number |
Minimum number of characters to be printed. If the value to be printed is shorter than this number the result is padded with blanks. The value is never truncated even if the result is larger. |
0number |
Same as above but filled with 0s instead of blanks. |
* |
The width is not specified in the format string, it is specified by an integer value preceding the argument has has to be formatted. |
.precision | meaning |
---|---|
.number |
for |
modifier | meaning (influences on how arguments are interpreted by the function) |
---|---|
h |
argument is interpreted as short |
l |
argument is interpreted as |
L |
argument is interpreted as |
argument(s) - Optional parameter(s) that contain the data to be inserted instead of % tags specified in format parameter. There must be the same number of these parameter than the number of format tags.
- RETURN VALUE
-
On success, the total number of characters printed is returned. On error, a negative number is returned.
- SEE ALSO
-
printf
,sscanf
- EXAMPLE
#include <stdio.h>
int main (void)
{
char buffer [50];
int n;
int a;
int b;
a = 5;
b = 3;
n = sprintf (buffer, "%d plus %d is %d", a, b, a+b);
printf ("[%s] is a %d chars string\n",buffer,n);
return 0;
}
- OUTPUT
[5 plus 3 is 8] is a 13 chars string
snprintf
- NAME
-
snprintf - Print formatted data to an array.
- SYNOPSIS
#include <stdio.h>
int snprintf(char * restrict s, size_t n, const char * restrict format, ...);
- DESCRIPTION
-
The
snprintf
function is equivalent tofprintf
, except that the output is written into an array (specified by arguments
) rather than to a stream. Ifn
is zero, nothing is written, ands
may be a NULL pointer. Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a NULL character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined. - PARAMETERS
-
-
buffer - Buffer where to store the resulting formatted string.
-
format - String that contains the text to be printed. Optionally it can contain format tags that are substituted by the values specified in subsequent argument(s) and formatted as requested. The number of format tags must correspond to the number of additional arguments that follows. The format tags follow this prototype:
%[flags][width][.precision][modifiers]type
where type is the most significant and defines how the value will be printed:
-
type | Output | Example |
---|---|---|
c |
Character |
a |
d or i |
Signed decimal integer |
392 |
e |
Scientific notation (mantise/exponent) using e character |
3.9265e2 |
E |
Scientific notation (mantise/exponent) using E character |
3.9265E2 |
f |
Decimal floating point |
392.650000 |
g |
Use shorter %e or %f |
392.65 |
G |
Use shorter %E or %f |
392.65 |
o |
Signed octal |
610 |
s |
String of characters |
"sample" |
u |
Unsigned decimal integer |
7235 |
x |
Unsigned hexadecimal integer |
7fa |
X |
Unsigned hexadecimal integer (capital letters) |
7FA |
p |
Address pointed by the argument |
B800:0000 |
n |
Nothing printed. The argument must be a pointer to integer where the number of characters written so far will be stored. |
The other parameters flags
, width
, precision
and modifiers
are optional and follow these specifications:
flags | meaning |
---|---|
- |
Left align within the given width. (right align is the default). |
+ |
Forces to prepend the result with a sign (+ or -) if signed type. (by default only - (minus) is printed). |
blank |
If the argument is a positive signed value, a blank is inserted before the number. |
# |
Used with |
width | meaning |
---|---|
number |
Minimum number of characters to be printed. If the value to be printed is shorter than this number the result is padded with blanks. The value is never truncated even if the result is larger. |
0number |
Same as above but filled with 0s instead of blanks. |
* |
The width is not specified in the format string, it is specified by an integer value preceding the argument has has to be formatted. |
.precision | meaning |
---|---|
.number |
for |
modifier | meaning (influences on how arguments are interpreted by the function) |
---|---|
h |
argument is interpreted as short |
l |
argument is interpreted as |
L |
argument is interpreted as |
argument(s) - Optional parameter(s) that contain the data to be inserted instead of % tags specified in format parameter. There must be the same number of these parameter than the number of format tags.
- RETURN VALUE
-
The
snprintf
function returns the number of characters that would have been written hadn
been sufficiently large, not counting the terminating NULL character, or a negative value if an encoding error occurred. Thus, the null-terminated output has been completely written if and only if the returned value is non-negative and less thann
. - SEE ALSO
-
fprintf
- EXAMPLE
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[16];
int len;
len = snprintf(str, 16, "%s %d", "hello world", 1000);
printf("%s\n", str);
if (len >= 16)
printf("length truncated (from %d)\n", len);
return EXIT_SUCCESS;
}
- OUTPUT
$ gcc -Wall snprintf.c $ ./a.out hello world 100 length truncated (from 16)
sscanf
- NAME
-
sscanf - Read formatted data to a string.
- SYNOPSIS
#include <stdio.h>
int sscanf ( char *buffer, const char *format [ , argument , ...] );
- DESCRIPTION
-
Reads data from the buffer specified and stores it into the locations given by argument(s). Locations pointed by each argument are filled with their corresponding type of value requested in the format string. There must be the same number of type specifiers in format string than arguments passed.
- PARAMETERS
-
-
buffer - Buffer containing the string to be parsed for data.
-
format - String that can contain one or more of these items:
-
Whitespace characters: the function will read and ignore any whitespace characters (this includes blank, newline and tab characters) encountered before the next non-whitespace character. This includes any quantity of whitespace characters (including none).
-
Non-whitespace characters (any character not including blank, newline, tab, or any format specifier beginning with % character): this cause that the function read and discard any character that match the given non-whitespace character. If this character is not found the function ends returning error.
-
Format specifiers: A sequence of characters beginning with
'%'
indicates that next data has to be read and stored at the location pointed by its corresponding argument with a given format that is specified following this prototype:%[*][width][modifiers]type where:
-
-
* |
Data is read but ignored. It is not assigned to the corresponding argument. |
width |
Specifies the maximum number of characters to be read. |
modifiers |
Specifies a different size for the data pointed by argument: - h: short int - l: long int (if integer) or double (if floating point). - L: long double |
type |
Character specifying the type of data that is expected and how it has to be read. See next table. |
type | Qualifying Input | required argument |
---|---|---|
c |
Single character: Reads the next character (whitespace characters included). |
char * |
d |
Decimal integer: Number optionally preceded with a sign. |
int * |
e,E,f,g,G |
Floating point: Decimal number containing a decimal point, optionally preceded by a sign and optionally followed by the |
float * |
o |
Octal integer. |
int * |
s |
String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are blank, newline and tab). |
char *(string) |
u |
Unsigned decimal integer. |
unsigned int * |
x |
Hexadecimal integer. |
int * |
argument(s) - pointer to objects or structures to be filled with data read as specified by format
string. There must be the same number of these parameters than the number of format tags. NOTE: These arguments must be pointers: if you want to store the result of a scanf
operation on a standard variable you should precede it with the reference operator, i.e. an ampersand sign (&
), like in: sscanf (buffer,"%d",&n);
- RETURN VALUE
-
The number of items successfully read. This count doesn’t include any ignored fields. If EOF is returned an error has occurred before the first assignation could be done.
- SEE ALSO
-
scanf
,printf
- EXAMPLE
#include <stdio.h>
int main (void)
{
char sentence []="Benny is 29 years old";
char str [20];
int i;
sscanf (sentence,"%s %*s %d",str,&i);
printf ("%s -> %d\n",str,i);
return 0;
}
- OUTPUT
$ gcc -Wall sscanf.c $ ./a.out Benny -> 29
tmpfile
- NAME
-
tmpfile - Open a temporary file.
- SYNOPSIS
#include <stdio.h>
FILE *tmpfile(void);
- DESCRIPTION
-
Creates a temporary binary file for update (
w+b
mode — seefopen
for details). The filename is unique to avoid any conflict with existing files. The temporary file created is automatically deleted when it is closed (fclose
) or when the program terminates normally. - PARAMETERS
-
None.
- RETURN VALUE
-
If successful, the function returns a file pointer (stream) to the temporary file created. If the file can not be created a NULL pointer is returned.
- SEE ALSO
-
fopen
,tmpnam
- EXAMPLE
#include <stdio.h>
int main (void)
{
FILE * pFile;
int i;
pFile = tmpfile ();
if (pFile==NULL)
perror("fopen error");
/* perform some operations involving the tmpfile */
fclose (pFile);
return 0;
}
This code creates a temporary file and deletes it when closing the stream.
tmpnam
- NAME
-
tmpnam - Generate a unique temporary filename.
- SYNOPSIS
#include <stdio.h>
char *tmpnam ( char *buffer );
- DESCRIPTION
-
A string containing a unique filename is generated. This string can be used to create a temporary file without overwriting any existing one. If the buffer parameter is NULL, the resulting string is stored in an internal static array that can be accessed by the return value. The content of this string is stored until a further call to this function erases it. If the buffer parameter is not NULL, it must point to an array of at least
L_tmpnam
bytes that will be filled with the proposed tempname.L_tmpnam
is a constant defined instdio
. - PARAMETERS
-
buffer - Pointer to an array of
L_tmpnam
(defined instdio
) bytes, where the proposed tempname will be stored. You can also specify a NULL pointer. In this case the string will be stored in an internal static array. - RETURN VALUE
-
A pointer to the string containing the proposed name for a temporary file. If NULL was specified as the buffer this points to an internal buffer that will be overwritten the next time this function is called, otherwise it returns the buffer parameter. If an error occurs this function returns NULL.
- SEE ALSO
-
fopen
,tmpfile
- EXAMPLE
#include <stdio.h>
int main (void)
{
char buffer [L_tmpnam];
char *pointer;
tmpnam (buffer);
printf ("Tempname #1: %s\n",buffer);
pointer = tmpnam (NULL);
printf ("Tempname #2: %s\n",pointer);
return 0;
}
This program will generate two different names for temporary files. Each one has been created by one of the two methods how tmpnam
can be used.
- OUTPUT
$ gcc -Wall tmpnam.c $ ./a.out Tempname #1: /tmp/filexTTLhK Tempname #2: /tmp/fileDhJI1b
ungetc
- NAME
-
ungetc - Push a character back into stream.
- SYNOPSIS
#include <stdio.h>
int ungetc(int character , FILE *stream);
- DESCRIPTION
-
A character is pushed into an input stream where last character was read and the file pointer is reset to that previous position. This character will be returned by the next call to getc or fread for the same stream. If the End-Of-File indicator was set is cleared after a call to this function. A call to fflush, fseek, fsetpos or rewind for this stream will undo the effects of any previous call to ungetc. This function do not affect the file associated with the stream, which will remain unchanged by any call to this function.
- PARAMETERS
-
-
character - Character to be pushed.
-
stream - Pointer to an open file.
-
- RETURN VALUE
-
If successful, the character put is returned. Otherwise EOF is returned and the stream remains unchanged.
- SEE ALSO
-
getc
,fgetc
,putc
- EXAMPLE
#include <stdio.h>
int main (int argc, char *argv[])
{
FILE * pFile;
char c;
char buffer [256];
pFile = fopen (argv[1],"rt");
if (pFile==NULL)
perror ("Error opening file");
else {
c = fgetc(pFile); // read the first character
printf("%c\n",c); // output c
ungetc(c, pFile); // push the character back
fgets (buffer,255,pFile); // read the first
printf ("[%c] %s",c,buffer);
}
return 0;
}
This example opens an existing file and reads the first character, then pushes back this character into the stream and gets the whole line into buffer.
- OUTPUT
$ gcc -Wall ungetc.c $ ./a.out file.txt H [H] Hello
vfprintf
- NAME
-
vfprintf - Sends formatted output to a stream using an argument list.
- SYNOPSIS
#include <stdio.h>
int vfprintf(FILE *stream, const char *fmtstr, va_list arg);
- DESCRIPTION
-
The
vfprintf
function formats a series of strings and numeric values and builds a string to write to the output stream using thefputc
function. The function is similar to the counterpartfprintf
, but it accepts a pointer to a list of arguments instead of an argument list.
The fmtstr
argument is a pointer to a format string and has the
same form and function as the fmtstr
argument for the printf
function. Refer to fprintf
for a description of the format string.
The va_list
points to a list of arguments that are converted and
output according to the corresponding format specifications in the
format.
- PARAMETERS
-
-
stream - Pointer to an open file.
-
format - String that contains the text to be printed. Optionally it can contain format tags that are substituted by the values specified in subsequent argument(s) and formatted as requested. The number of format tags must correspond with the number of additional arguments that follows.
-
The format tags follow this prototype:
%[flags][width][.precision][modifiers]type
where type
is the most significant and defines how the value will be printed:
type | Output | Example |
---|---|---|
c |
Character |
a |
d or i |
Signed decimal integer |
392 |
e |
Scientific notation (mantise/exponent) using e character |
3.9265e2 |
E |
Scientific notation (mantise/exponent) using E character |
3.9265E2 |
f |
Decimal floating point |
392.650000 |
g |
Use shorter %e or %f |
392.65 |
G |
Use shorter %E or %f |
392.65 |
o |
Signed octal |
610 |
s |
String of characters |
"sample" |
u |
Unsigned decimal integer |
7235 |
x |
Unsigned hexadecimal integer |
7fa |
X |
Unsigned hexadecimal integer (capital letters) |
7FA |
p |
Address pointed by the argument |
B800:0000 |
n |
Nothing printed. The argument must be a pointer to integer where the number of characters written so far will be stored. |
The other parameters flags
, width
, precision
and modifiers
are optional and follow these specifications:
flags | meaning |
---|---|
- |
Left align within the given width. (right align is the default). |
+ |
Forces to prepend the result with a sign (+ or -) if signed type. (by default only - (minus) is printed). |
blank |
If the argument is a positive signed value, a blank is inserted before the number. |
# |
Used with |
width | meaning |
---|---|
number |
Minimum number of characters to be printed. If the value to be printed is shorter than this number the result is padded with blanks. The value is never truncated even if the result is larger. |
0number |
Same as above but filled with 0s instead of blanks. |
* |
The width is not specified in the format string, it is specified by an integer value preceding the argument has has to be formatted. |
.precision | meaning |
---|---|
.number |
for |
modifier | meaning (influences on how arguments are interpreted by the function) |
---|---|
h |
argument is interpreted as short |
l |
argument is interpreted as |
L |
argument is interpreted as |
argument(s) - Optional parameter(s) that contain the data to be inserted instead of % tags specified in format parameter. There must be the same number of these parameter than the number of format tags.
- RETURN VALUE
-
The
vfprintf
function returns the number of characters actually written to the output stream. - SEE ALSO
-
printf
,vprintf
,vsprintf
- EXAMPLE
#include <stdio.h>
#include <stdarg.h>
void echo_err_printf(char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
vfprintf(stderr, format, arg_ptr);
va_end(arg_ptr);
va_start(arg_ptr, format);
vprintf(format, arg_ptr);
va_end(arg_ptr);
}
int main(void)
{
echo_err_printf("Error: %d\n", 12);
return 0;
}
- OUTPUT
$ gcc -Wall vfprintf.c $ ./a.out Error: 12 Error: 12
vprintf
- NAME
-
vprintf - Sends formatted output to
stdout
using an argument list. - SYNOPSIS
#include <stdio.h>
int vprintf(const char *fmtstr, va_list arg);
- DESCRIPTION
-
The
vprintf
function formats a series of strings and numeric values and builds a string to write to the output stream using theputchar
function. The function is similar to the counterpartprintf
, but it accepts a pointer to a list of arguments instead of an argument list.
Thefmtstr
argument is a pointer to a format string and has the same form and function as thefmtstr
argument for theprintf
function. Refer toprintf
for a description of the format string. Theva_list
points to a list of arguments that are converted and output according to the corresponding format specifications in the format. - PARAMETERS
-
See printf for a description of the allowable parameters and arguments.
- RETURN VALUE
-
The
vprintf
function returns the number of characters actually written to the output stream. - SEE ALSO
-
printf
,vfprintf
,vsprintf
- EXAMPLE
#include <stdio.h>
#include <stdarg.h>
void error (char *fmt, ...);
void test_vprintf (void);
int main (void)
{
test_vprintf();
return 0;
}
void error (char *fmt, ...)
{
va_list arg_ptr;
va_start (arg_ptr, fmt);
vprintf (fmt, arg_ptr);
va_end (arg_ptr);
}
void test_vprintf (void)
{
int i;
i = 1000;
error ("Error: '%d' number too large\n", i);
error ("Syntax Error\n");
}
The above example demonstrates how vprintf()
can be used to write an error routine.
- OUTPUT
$ gcc -Wall vprintf.c $ ./a.out Error: '1000' number too large Syntax Error
vsnprintf
- NAME
-
vscanf - Sends formatted output to a string using an argument list.
- SYNOPSIS
#include <stdio.h>
int vsprintf(char *restrict s, size_t n, const char *restrict format, va_list arg);
- DESCRIPTION
-
The
vsnprintf
function is equivalent tosnprintf
, with the variable argument list replaced byarg
, which shall have been initialized by theva_start
macro (and possibly subsequentva_arg
calls). Thevsnprintf
function does not invoke theva_end macro
.) If copying takes place between objects that overlap, the behavior is undefined. - PARAMETERS
-
-
buffer - Buffer where to store the resulting formatted string.
-
format - String that contains the text to be printed. Optionally it can contain format tags that are substituted by the values specified in subsequent argument(s) and formatted as requested. The number of format tags must correspond to the number of additional arguments that follows. The format tags follow this prototype:
%[flags][width][.precision][modifiers]type
where type is the most significant and defines how the value will be printed:
-
type | Output | Example |
---|---|---|
c |
Character |
a |
d or i |
Signed decimal integer |
392 |
e |
Scientific notation (mantise/exponent) using e character |
3.9265e2 |
E |
Scientific notation (mantise/exponent) using E character |
3.9265E2 |
f |
Decimal floating point |
392.650000 |
g |
Use shorter %e or %f |
392.65 |
G |
Use shorter %E or %f |
392.65 |
o |
Signed octal |
610 |
s |
String of characters |
"sample" |
u |
Unsigned decimal integer |
7235 |
x |
Unsigned hexadecimal integer |
7fa |
X |
Unsigned hexadecimal integer (capital letters) |
7FA |
p |
Address pointed by the argument |
B800:0000 |
n |
Nothing printed. The argument must be a pointer to integer where the number of characters written so far will be stored. |
The other parameters flags
, width
, precision
and modifiers
are optional and follow these specifications:
flags | meaning |
---|---|
- |
Left align within the given width. (right align is the default). |
+ |
Forces to prepend the result with a sign (+ or -) if signed type. (by default only - (minus) is printed). |
blank |
If the argument is a positive signed value, a blank is inserted before the number. |
# |
Used with |
width | meaning |
---|---|
number |
Minimum number of characters to be printed. If the value to be printed is shorter than this number the result is padded with blanks. The value is never truncated even if the result is larger. |
0number |
Same as above but filled with 0s instead of blanks. |
* |
The width is not specified in the format string, it is specified by an integer value preceding the argument has has to be formatted. |
.precision | meaning |
---|---|
.number |
for |
modifier | meaning (influences on how arguments are interpreted by the function) |
---|---|
h |
argument is interpreted as short |
l |
argument is interpreted as |
L |
argument is interpreted as |
argument(s) - Optional parameter(s) that contain the data to be inserted instead of % tags specified in format parameter. There must be the same number of these parameter than the number of format tags.
- RETURN VALUE
-
The
vsnprintf
function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. Thus, the null-terminated output has been completely written if and only if the returned value is non-negative and less thann
. - SEE ALSO
-
snprintf
- EXAMPLE
#include <stdarg.h>
#include <stdio.h>
void vout(char *string, char *fmt, ...);
char fmt1 [] = "%s %s %s\n";
int main(void)
{
char string[100];
vout(string, fmt1, "Sat", "Sun", "Mon");
printf("The string is: %s\n", string);
return 0;
}
void vout(char *string, char *fmt, ...)
{
va_list arg_ptr;
va_start(arg_ptr, fmt);
vsnprintf(string, 8, fmt, arg_ptr);
va_end(arg_ptr);
}
- OUTPUT
$ gcc -Wall vsnprintf.c $ ./a.out The string is: Sat Su
vsprintf
- NAME
-
vsprintf - Sends formatted output to a string using an argument list.
- SYNOPSIS
#include <stdio.h>
int vsprintf(char *buffer, const char *fmtstr, va_list arg);
- DESCRIPTION
-
The
vsprintf
function formats a series of strings and numeric values and stores the string in buffer. The function is similar to the counterpartsprintf
, but it accepts a pointer to a list of arguments instead of an argument list.
Thefmtstr
argument is a pointer to a format string and has the same form and function as thefmtstr
argument for theprintf
function. Refer tosprintf
for a description of the format string. Theva_list
points to a list of arguments that are converted and output according to the corresponding format specifications in the format. - PARAMETERS
-
-
buffer - Buffer where to store the resulting formatted string.
-
format - String that contains the text to be printed. Optionally it can contain format tags that are substituted by the values specified in subsequent argument(s) and formatted as requested. The number of format tags must correspond to the number of additional arguments that follows. The format tags follow this prototype:
%[flags][width][.precision][modifiers]type
where type is the most significant and defines how the value will be printed:
-
type | Output | Example |
---|---|---|
c |
Character |
a |
d or i |
Signed decimal integer |
392 |
e |
Scientific notation (mantise/exponent) using e character |
3.9265e2 |
E |
Scientific notation (mantise/exponent) using E character |
3.9265E2 |
f |
Decimal floating point |
392.650000 |
g |
Use shorter %e or %f |
392.65 |
G |
Use shorter %E or %f |
392.65 |
o |
Signed octal |
610 |
s |
String of characters |
"sample" |
u |
Unsigned decimal integer |
7235 |
x |
Unsigned hexadecimal integer |
7fa |
X |
Unsigned hexadecimal integer (capital letters) |
7FA |
p |
Address pointed by the argument |
B800:0000 |
n |
Nothing printed. The argument must be a pointer to integer where the number of characters written so far will be stored. |
The other parameters flags
, width
, precision
and modifiers
are optional and follow these specifications:
flags | meaning |
---|---|
- |
Left align within the given width. (right align is the default). |
+ |
Forces to prepend the result with a sign (+ or -) if signed type. (by default only - (minus) is printed). |
blank |
If the argument is a positive signed value, a blank is inserted before the number. |
# |
Used with |
width | meaning |
---|---|
number |
Minimum number of characters to be printed. If the value to be printed is shorter than this number the result is padded with blanks. The value is never truncated even if the result is larger. |
0number |
Same as above but filled with 0s instead of blanks. |
* |
The width is not specified in the format string, it is specified by an integer value preceding the argument has has to be formatted. |
.precision | meaning |
---|---|
.number |
for |
modifier | meaning (influences on how arguments are interpreted by the function) |
---|---|
h |
argument is interpreted as short |
l |
argument is interpreted as |
L |
argument is interpreted as |
argument(s) - Optional parameter(s) that contain the data to be inserted instead of % tags specified in format parameter. There must be the same number of these parameter than the number of format tags. RETURN VALUE::
The vsprintf
function returns the number of characters actually written to the output stream.
- SEE ALSO
-
printf
,vprintf
,vfprintf
- EXAMPLE
#include <stdio.h>
#include <stdarg.h>
char etxt[30];
void error (char *fmt, ...)
{
va_list arg_ptr;
va_start (arg_ptr, fmt);
vsprintf (etxt, fmt, arg_ptr);
va_end (arg_ptr);
}
int main (void)
{
int i;
i = 1000;
error("Error: '%d' number too large\n", i);
printf(">>>> %s", etxt);
error("Syntax Error\n");
printf(">>>> %s", etxt);
return 0;
}
The above example prints to the string etxt.
- OUTPUT
$ gcc -Wall vsprintf.c $ ./a.out >>>> Error: '1000' number too large >>>> Syntax Error
vfscanf
- NAME
-
vfscanf - Format input of a stdarg argument list.
- SYNOPSIS
#include <stdio.h>
int vfscanf(FILE *restrict stream, const char *restrict format, va_list arg);
- DESCRIPTION
-
The
vfscanf
function is equivalent to thefscanf
function except that instead of being called with a variable number of arguments, it is called with an argument list as defined in thestdarg
header. This function shall not invoke theva_end
macro. As this function invokes theva_arg
macro, the value ofap
after the return is unspecified. - PARAMETERS
-
-
stream - Pointer to an open file.
-
format - String that can contain one or more of these items:
-
- Whitespace characters
-
the function will read and ignore any whitespace characters (this includes blank, newline and tab characters) encountered before the next non-whitespace character. This includes any quantity of whitespace characters (including none).
- Non-whitespace characters
-
(any character not including blank, newline, tab, or any format specifier beginning with
%
character): this cause that the function read and discard any character that match the given non-whitespace character. If this character is not found the function ends returning error. - Format specifiers
-
A sequence of characters begining with
%
indicates that next data has to be read and stored at the location pointed by its corresponding argument with a given format that is specified following this prototype:%[*][width][modifiers]type
where:
* |
Data is read but ignored. It is not assigned to the corresponding argument. |
width |
Specifies the maximum number of characters to be read. |
modifiers |
Specifies a different size for the data pointed by argument:
|
type |
Character specifying the type of data that is expected and how it has to be read. See next table. |
type | qualifying input | required argument |
---|---|---|
c |
Single character: Reads the next character (whitespace characters included). |
char * |
d |
Decimal integer: Number optionally prepended with a sign. |
int * |
e,E,f,g,G |
Floating point: Decimal number containing a decimal point, optionally prepended by a sign and optionally followed by the |
float * |
o |
Octal integer. |
int * |
s |
String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are blank, newline and tab). |
char *(string) |
u |
Unsigned decimal integer. |
unsigned int * |
x |
Hexadecimal integer. |
int * |
argument(s) - pointer to objects or structures to be filled with data read as specified by format
string. There must be the same number of these parameters than the number of format tags. NOTE: These arguments must be pointers: if you want to store the result of a scanf
operation on a standard variable you should precede it with the reference operator, i.e. an ampersand sign: &
- RETURN VALUE
-
The
vfscanf
function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, thevfscanf
function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure. - SEE ALSO
-
fscanf
- EXAMPLE
#include <stdio.h>
#include <stdarg.h>
#define MAX_LEN 80
int vread(FILE *stream, char *fmt, ...);
int main(int argc, char *argv[])
{
FILE *stream;
long l;
float fp;
char s[MAX_LEN + 1];
char c;
stream = fopen(argv[1], "r");
vread(stream, "%s", &s[0]);
vread(stream, "%ld", &l);
vread(stream, "%c", &c);
vread(stream, "%f", &fp);
printf("string = %s\n", s);
printf("long double = %ld\n", l);
printf("char = %c\n", c);
printf("float = %f\n", fp);
return 0;
}
int vread(FILE *stream, char *fmt, ...)
{
int rc;
va_list arg_ptr;
va_start(arg_ptr, fmt);
rc = vfscanf(stream, fmt, arg_ptr);
va_end(arg_ptr);
return(rc);
}
- OUTPUT
$ gcc -Wall vfscanf.c $ cat file.txt Hello 42w123.456789 $ ./a.out file.txt string = Hello long double = 42 char = w float = 123.456787
vscanf
- NAME
-
vscanf - Format input of a stdarg argument list.
- SYNOPSIS
#include <stdio.h>
int vscanf(const char *restrict format, va_list arg);
- DESCRIPTION
-
The
vscanf
function is equivalent toscanf
, with the variable argument list replaced byarg
, which shall have been initialized by theva_start
macro (and possibly subsequentva_arg
calls). Thevscanf
function does not invoke theva_end
macro. - PARAMETERS
-
-
format - String that can contain one or more of these items:
-
Whitespace characters: the function will read and ignore any whitespace characters (this includes blank, newline and tab characters) encountered before the next non-whitespace character. This includes any quantity of whitespace characters (including none).
-
Non-whitespace characters (any character not including blank, newline, tab, or any format specifier beginning with % character): this cause that the function read and discard any character that match the given non-whitespace character. If this character is not found the function ends returning error.
-
Format specifiers: A sequence of characters beginning with
'%'
indicates that next data has to be read and stored at the location pointed by its corresponding argument with a given format that is specified following this prototype:%[*][width][modifiers]type where:
-
-
* |
Data is read but ignored. It is not assigned to the corresponding argument. |
width |
Specifies the maximum number of characters to be read. |
modifiers |
Specifies a different size for the data pointed by argument: - h: short int - l: long int (if integer) or double (if floating point). - L: long double |
type |
Character specifying the type of data that is expected and how it has to be read. See next table. |
type | Qualifying Input | required argument |
---|---|---|
c |
Single character: Reads the next character (whitespace characters included). |
char * |
d |
Decimal integer: Number optionally preceded with a sign. |
int * |
e,E,f,g,G |
Floating point: Decimal number containing a decimal point, optionally preceded by a sign and optionally followed by the |
float * |
o |
Octal integer. |
int * |
s |
String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are blank, newline and tab). |
char *(string) |
u |
Unsigned decimal integer. |
unsigned int * |
x |
Hexadecimal integer. |
int * |
argument(s) - pointer to objects or structures to be filled with data read as specified by format
string. There must be the same number of these parameters than the number of format tags. NOTE: These arguments must be pointers: if you want to store the result of a scanf
operation on a standard variable you should precede it with the reference operator, i.e. an ampersand sign (&
), like in: scanf ("%d",&n);
- RETURN VALUE
-
The
vscanf
function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, thevscanf
function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure. - SEE ALSO
-
scanf
- EXAMPLE
#include <stdio.h>
#include <stdarg.h>
int vread(char *fmt, ...);
int main(void)
{
int i, rc;
float fp;
char c, s[81];
printf("Enter an integer, a real number, a character "
"and a string: \n");
rc = vread("%d %f %c %s", &i, &fp, &c, s);
if (rc != 4)
printf("Not all fields are assigned\n");
else {
printf("integer = %d\n", i);
printf("real number = %f\n", fp);
printf("character = %c\n", c);
printf("string = %s\n",s);
}
return 0;
}
int vread(char *fmt, ...)
{
int rc;
va_list arg_ptr;
va_start(arg_ptr, fmt);
rc = vscanf(fmt, arg_ptr);
va_end(arg_ptr);
return(rc);
}
- OUTPUT
$ gcc -Wall vscanf.c $ ./a.out Enter an integer, a real number, a character and a string : 42 123.456 a hello integer = 42 real number = 123.456001 character = a string = hello
vsscanf
- NAME
-
vsscanf - Format input of a stdarg argument list.
- SYNOPSIS
#include <stdio.h>
int vsscanf(const char *restrict s, const char *restrict format, va_list arg);
- DESCRIPTION
-
The
vsscanf
function is equivalent tosscanf
, with the variable argument list replaced byarg
, which shall have been initialized by theva_start
macro (and possibly subsequentva_arg
calls). The vsscanf function does not invoke theva_end
macro. - PARAMETERS
-
-
buffer - Buffer where to store the resulting formatted string.
-
format - String that contains the text to be printed. Optionally it can contain format tags that are substituted by the values specified in subsequent argument(s) and formatted as requested. The number of format tags must correspond to the number of additional arguments that follows. The format tags follow this prototype:
%[flags][width][.precision][modifiers]type
where type is the most significant and defines how the value will be printed:
-
type | Output | Example |
---|---|---|
c |
Character |
a |
d or i |
Signed decimal integer |
392 |
e |
Scientific notation (mantise/exponent) using e character |
3.9265e2 |
E |
Scientific notation (mantise/exponent) using E character |
3.9265E2 |
f |
Decimal floating point |
392.650000 |
g |
Use shorter %e or %f |
392.65 |
G |
Use shorter %E or %f |
392.65 |
o |
Signed octal |
610 |
s |
String of characters |
"sample" |
u |
Unsigned decimal integer |
7235 |
x |
Unsigned hexadecimal integer |
7fa |
X |
Unsigned hexadecimal integer (capital letters) |
7FA |
p |
Address pointed by the argument |
B800:0000 |
n |
Nothing printed. The argument must be a pointer to integer where the number of characters written so far will be stored. |
The other parameters flags
, width
, precision
and modifiers
are optional and follow these specifications:
flags | meaning |
---|---|
- |
Left align within the given width. (right align is the default). |
+ |
Forces to prepend the result with a sign (+ or -) if signed type. (by default only - (minus) is printed). |
blank |
If the argument is a positive signed value, a blank is inserted before the number. |
# |
Used with |
width | meaning |
---|---|
number |
Minimum number of characters to be printed. If the value to be printed is shorter than this number the result is padded with blanks. The value is never truncated even if the result is larger. |
0number |
Same as above but filled with 0s instead of blanks. |
* |
The width is not specified in the format string, it is specified by an integer value preceding the argument has has to be formatted. |
.precision | meaning |
---|---|
.number |
for |
modifier | meaning (influences on how arguments are interpreted by the function) |
---|---|
h |
argument is interpreted as short |
l |
argument is interpreted as |
L |
argument is interpreted as |
argument(s) - Optional parameter(s) that contain the data to be inserted instead of % tags specified in format parameter. There must be the same number of these parameter than the number of format tags.
- RETURN VALUE
-
The
vsscanf
function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, thevscanf
function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure. - SEE ALSO
-
sscanf
- EXAMPLE
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
void sfind( char* string, char* format, ... );
int main( void )
{
int day, year;
char weekday[10], month[12];
sfind( "Monday June 28 1999",
"%s %s %d %d",
weekday, month, &day, &year );
printf( "%s, %s %d, %d\n",
weekday, month, day, year );
return EXIT_SUCCESS;
}
void sfind( char* string, char* format, ... )
{
va_list arglist;
va_start( arglist, format );
vsscanf( string, format, arglist );
va_end( arglist );
}
- OUTPUT
$ gcc -Wall vsscanf.c $ ./a.out Monday, June 28, 1999
stdlib.h
Stdlib Summary
C stdlib
library functions can be divided in these groups depending on their utility:
-
conversion
-
atof, atoi, atol, mblen, mbstowcs, mbtowc, strtod, strtol, strtoul, wctomb, wcstombs
-
-
dynamic memory allocation/deallocation
-
calloc, free, malloc, realloc
-
-
process control and environment variables
-
abort, atexit, exit, getenv, system
-
-
sorting and searching
-
bsearch, lfind, lsearch, qsort
-
-
mathematical operations
-
abs, div, labs, ldiv, rand, srand, etc.
-
NOTES
-
NULL - NULL is a defined constant used to express null pointers, that is, an unassigned pointer or a pointer that points nowhere. It is defined as:
#define NULL 0
-
size_t - Defined type used as arguments for some functions that require sizes or counts specifications. This represents an unsigned value generally defined in header files as unsigned int:
typedef unsigned int size_t;
abort
- NAME
-
abort - cause abnormal process termination
- SYNOPSIS
#include <stdlib.h>
void abort(void);
- DESCRIPTION
-
If the
abort()
function causes process termination, all open streams are closed and flushed. - RETURN VALUE
-
None. The calling process does not receive back control.
- SEE ALSO
-
exit
,atexit
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char *argv[])
{
FILE * pFile;
pFile= fopen (argv[1],"r");
if (pFile == NULL) {
printf ("Error opening file \"%s\".\n",argv[1]);
abort();
}
fclose (pFile);
return 0;
}
If the file name provided as argument doesn’t exist a message is
printed, abort
is called and an errorlevel is returned. Otherwise
the file is normally closed and the errorlevel returned is 0
(return 0). In a Unix bash
shell the return value can be read via echo $?
immediately after termination.
abs
- NAME
-
abs - computes the absolute value of an integer.
- SYNOPSIS
#include <math.h>
int abs(int j);
- DESCRIPTION
-
The
abs()
function computes the absolute value of the integer argumentj
. - SEE ALSO
-
fabs
,labs
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
int main (int argc, char *argv[])
{
int j,k;
if (argc!=2) {
printf("A single number as argument is required.\n");
abort();
}
j = atoi(argv[1]);
if ( j <= INT_MIN || j >= INT_MAX ) {
printf("Number out of range.\n");
exit(EXIT_FAILURE);
}
k = abs(j);
printf ("The number you entered %d.\n",j);
printf ("The absolute value is %d.\n",k);
return 0;
}
- OUTPUT
$ gcc -Wall abs.c $ ./a.out 2147483647 Number out of range. $ ./a.out 2147483646 The number you entered 2147483646. The absolute value is 2147483646. $ ./a.out -2147483647 The number you entered -2147483647. The absolute value is 2147483647. $ ./a.out -2147483648 Number out of range.
atexit
- NAME
-
atexit - Specifies a function to be executed at exit.
- SYNOPSIS
#include <stdlib.h>
int atexit ( void (* function) (void) );
- DESCRIPTION
-
The function pointed by function parameter is called when the program terminates normally. If more than one
atexit
function is specified calling this, they are all executed in reverse order, that is, the last function specified is the first to be executed at exit. ANSI standard specifies that up to 32 functions can be prefixed for a single process. These functions will not receive any parameter when called. - PARAMETERS
-
function - Function to be called.
- RETURN VALUE
-
0 is returned if successful, or a non-zero value if an error occurs.
- SEE ALSO
-
abort
,exit
- EXAMPLE
#include <stdio.h>
#include <stdlib.h>
void fn_exit1 (void)
{
printf ("Exit function 1.\n");
}
void fn_exit2 (void)
{
printf ("Exit function 2.\n");
}
int main (void)
{
atexit (fn_exit1);
atexit (fn_exit2);
printf ("Main function.\n");
return 0;
}
- OUTPUT
$ gcc -Wall atexit.c $ ./a.out Main function. Exit function 2. Exit function 1.
atof
- NAME
-
atof - convert string to double.
- SYNOPSIS
#include <stdlib.h>
double atof(const char * string );
- DESCRIPTION
-
Parses string interpreting its content as a floating point number and returns a value of type double.
- PARAMETERS
-
string - String representing a floating point number. The number is considered until a non-numeric character is found (digits, signs, E and e are considered valid numeric characters for this parameter as specified in format). The format used is:
[white-spaces][+|-][nnnnn][.nnnnn][e|E[+|-]nnnn]
(where white-spaces are any tab or space character andnnnnn
may be any number of digits) - RETURN VALUE
-
The converted floating point value of the input string. On overflow the result is undefined. If an error occurs 0.0 is returned.
- SEE ALSO
-
atoi
,atol
,strtod
- EXAMPLE
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
double n,m;
char szInput [256];
printf ( "Enter degrees: " );
gets ( szInput );
n = atof ( szInput );
m = sin (n*M_PI/180);
printf ( "sine of %f degrees is %f\n" , n, m );
return 0;
}
- OUTPUT
$ gcc -Wall -lm atof.c $ ./a.out Enter degrees: 45 sine of 45.000000 degrees is 0.707107
atoi
- NAME
-
atoi - Convert string to integer.
- SYNOPSIS
#include <stdlib.h>
int atoi ( const char * string );
- DESCRIPTION
-
Parses string interpreting its content as a number and returns an
int
value. - PARAMETERS
-
string - String representing an integer number. The number is considered until a non-numeric character is found (digits, and signs are considered valid numeric characters for this parameter as specified in format). The format used is:
[white-spaces][+|-][nnnnn]
(where white-spaces are any tab or space character andnnnnn
may be any number of digits) - RETURN VALUE
-
The converted integer value of the input string. On overflow the result is undefined. If an error occurs 0 is returned.
- SEE ALSO
-
atol
,atof
,strtod
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
int i;
char szInput [256];
printf ("Enter a number: ");
gets ( szInput );
i = atoi (szInput);
printf ("Value entered is %d, and its double %d.\n",i,i*2);
return 0;
}
- OUTPUT
gcc -Wall atoi.c $ ./a.out Enter a number: a 123 Value entered is 0, and its double 0. $ ./a.out Enter a number: 123 2 Value entered is 123, and its double 246. $ ./a.out Enter a number: 123 Value entered is 123, and its double 246.
atol
- NAME
-
atol - Convert string to long.
- SYNOPSIS
#include <stdlib.h>
long atol ( const char * string );
- DESCRIPTION
-
Parses string interpreting its content as a number and returns a long value.
- PARAMETERS
-
string - String representing an integer number. The number is considered until a non-numeric character is found (digits, and signs are considered valid numeric characters for this parameter as specified in format). The format used is:
[white-spaces][+|-][nnnnn]
(where white-spaces are any tab or space character andnnnnn
may be any number of digits) - RETURN VALUE
-
The converted long integer value of the input string. On overflow the result is undefined. If an error occurs 0 is returned.
- SEE ALSO
-
atoi
,atof
,strtod
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
int i;
char szInput [256];
printf ("Enter a long number: ");
gets ( szInput );
i = atol (szInput);
printf ("Value entered is %d, and its double %d.\n",i,i*2);
return 0;
}
- OUTPUT
$ gcc -Wall atol.c $ ./a.out Enter a long number: 123456789 Value entered is 123456789, and its double 246913578. $ ./a.out Enter a long number: 1234567890 Value entered is 1234567890, and its double -1825831516.
bsearch
- NAME
-
bsearch - Binary search.
- SYNOPSIS
#include <stdlib.h>
void* bsearch ( const void * key, const void * base, size_t num, \
size_t width, int (*fncompare)(const void *, const void * ) );
- DESCRIPTION
-
Searches the given key in an array pointed by base and formed by num elements each of a size of width bytes, and returns the address of the first entry in the table that matches the search key. The comparison is performed by function
fncomparison
that is called back one or more times during the search. Because this function performs a binary search the values of the items in the array should be in ascending sorted order before the call. - PARAMETERS
-
-
key - Pointer to the object that serves as key for the search.
-
base - Pointer to the base of the array where the search is performed.
-
num - Number of elements in the array pointed by base.
-
width - Width of each element in the array.
-
fncompare - Function that compares two elements. This should be provided by the caller to this function and must follow or be cast to a declaration like:
-
int fncompare (const void * elem1, const void * elem2);
The function should receive two parameters (elem1
and elem2
) that
are pointers to elements, and should return an int value with the
result of comparing them:
return value | description |
---|---|
<0 |
*elem1 < *elem2 |
0 |
*elem1 == *elem2 |
>0 |
*elem1 > elem2 |
- RETURN VALUE
-
A pointer to an entry in the array that matches the search key. If key is not found, a NULL pointer is returned.
- SEE ALSO
-
lsearch
,qsort
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
/***************************************************** PROTOTYPES ***/
int compare (const void * a, const void * b);
/******************************************************** GLOBALS ***/
int values[] = { 10, 20, 25, 40, 90, 100 };
/****************************************************** FUNCTIONS ***/
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main (int argc, char *argv[])
{
int * pItem;
int key = 0;
printf("Enter an integer number in the range 0-100 > ");
scanf("%d", &key);
pItem = (int*) bsearch(&key, values, 6, sizeof (int), compare);
if (pItem!=NULL)
printf ("%d is in the array.\n",*pItem);
else
printf ("%d is not in the array.\n",key);
return 0;
}
In the example there is an array of sorted int values. There is also a function called compare that compares the values pointed by the two parameters as if they were pointers to int values (that indeed they are) and returns the result of the subtraction, giving 0 if they are equal, greater than 0 if a points to a greater int than b or less than 0 if b points to a greater int than a.
- OUTPUT
$ gcc -Wall bsearch.c $ ./a.out Enter an integer number in the range 0-100 > 20 20 is in the array. $ ./a.out Enter an integer number in the range 0-100 > 15 15 is not in the array.
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
#define NUM 11
/***************************************************** PROTOTYPES ***/
static int func (void *, void *);
/****************************************************** FUNCTIONS ***/
int main(void)
{
int numbers[NUM]= {3,4,7,9,11,13,15,17,19,21,23};
int key=0;
int *result;
printf("Enter an integer number in the range 0-30 > ");
scanf("%d", &key);
result = bsearch (&key, numbers, NUM, sizeof(numbers[0]), (void *)func);
printf("%d ", key);
(result) ? puts("found") : puts("not found");
return 0;
}
static int func (void *a, void *b)
{
printf("%d %d \n", *(int *)a, *(int *)b);
if (*(int *)a == *(int *)b)
return(0);
if (*(int *)a < *(int *)b)
return(-1);
return(1);
}
$ gcc -Wall bsearch2.c $ ./a.out Enter an integer number in the range 0-30 > 7 7 13 7 7 7 found $ ./a.out Enter an integer number in the range 0-30 > 30 30 13 30 19 30 23 30 not found
calloc
- NAME
-
calloc - Allocate array in memory.
- SYNOPSIS
#include <stdlib.h>
void * calloc ( size_t num, size_t size );
- DESCRIPTION
-
Dynamically allocates a block of memory for an array of
num
elements of size bytes each one. The block is initialized with zeros. The effective result is the allocation of an initialized memory block ofnum * size
bytes. - PARAMETERS
-
-
num - number of elements to be allocated.
-
size - size of elements.
-
- RETURN VALUE
-
A pointer to the allocated space. The type of this pointer is void*. A type cast to the desired type of data pointer should be performed on this returned pointer in order to be used as an ordinary array of a concrete type. If the system could not allocate the requested block of memory or if any of the parameters was 0 a NULL pointer is returned.
- SEE ALSO
-
free
,malloc
,realloc
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
struct data {
char item[20];
};
int main (void)
{
int i, n;
struct data *d;
/* How many items will be input? */
printf ("Enter number of items to be remembered: ");
scanf ("%d", &i);
/* Memory allocation */
d = (struct data *) calloc (i,sizeof(struct data));
if (d == NULL)
exit (EXIT_FAILURE);
/* Input */
for (n=0; n<i; n++) {
printf ("Enter item #%d: ",n);
scanf ("%s", (char *)d);
getchar();
d++;
}
/* Output */
d = d - n; // move the pointer to the first element
printf ("You have entered: ");
for (n=0; n<i; n++)
printf ("%s ",(char *)d++);
printf("\n");
/* Free the allocated memory */
d = d - n; // move the pointer to the first element
free (d);
return 0;
}
This program only stores strings and then prints them out. The number of items it can remember is not limited since the program allocates as much dynamic memory as needed to store the number of items the user wants to enter.
$ gcc -Wall calloc.c $ ./a.out Enter number of items to be remembered: 3 Enter item #0: hello Enter item #1: world Enter item #2: goodbye You have entered: hello world goodbye
div
- NAME
-
div - Divide two integer values.
- SYNOPSIS
#include <stdlib.h>
div_t div (int numerator, int denominator);
- DESCRIPTION
-
numerator
is divided bydenominator
. Quotient and remainder are returned in adiv_t
structure. - PARAMETERS
-
-
numerator - Numerator.
-
denominator - Denominator.
-
- RETURN VALUE
-
A
div_t
structure is returned:
typedef struct { int quot; int rem;} div_t;
The div_t
structure is defined in stdlib.h
and has two
members of type int quot
representing the quotient, and rem
representing the remainder.
- SEE ALSO
-
ldiv
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
int n, d;
div_t divresult;
printf("Enter two integers separated by a space > ");
scanf("%d %d", &n, &d);
divresult = div (n,d);
printf ("%d / %d = %d ( %d\n", n, d, divresult.quot, divresult.rem);
return 0;
}
- OUTPUT
$ gcc -Wall div.c $ ./a.out Enter two integers separated by a space > 38 5 38 / 5 = 7 ( 3
ldiv
- NAME
-
ldiv - Divide two long integer values.
- SYNOPSIS
#include <stdlib.h>
ldiv_t ldiv ( long int numer, long int denom );
- DESCRIPTION
-
numer
is divided bydenom
. Quotient and remainder are returned in aldiv_t
structure. - PARAMETERS
-
-
numer - Numerator.
-
denom - Denominator.
-
- RETURN VALUE
-
A
ldiv_t
structure is returned:
typedef struct { long int quot; long int rem;} ldiv_t;
The ldiv_t
structure is defined in stdlib.h
and has two
members of type long int
: quot
representing the quotient, and rem
representing the remainder.
- SEE ALSO
-
div
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
ldiv_t divresult;
divresult = ldiv (65537,179);
printf ("65537 / 179 = %ld ( %ld\n", divresult.quot, divresult.rem);
return 0;
}
- OUTPUT
$ gcc -Wall ldiv.c $ ./a.out 65537 / 179 = 366 ( 23
exit
- NAME
-
exit - Terminate calling process.
- SYNOPSIS
#include <stdlib.h>
void exit(int status);
- DESCRIPTION
-
The process performs standard cleanup and then terminates. Before the cleanup is done any function registered by
atexit
is called. The cleanup consists on flushing all buffers and close any open files. The status parameter is returned to the parent of the process (if any) or the operating system as if a return statement was specified in main function. Generally a return value of0
or constantEXIT_SUCCESS
indicates success and any other value or constantEXIT_FAILURE
is used to indicate an error or an abnormal program termination. - PARAMETERS
-
-
status - status value returned to parent process (if any) or operating system, generally:
-
status | value | description |
---|---|---|
EXIT_SUCCESS |
0 |
Normal termination |
EXIT_FAILURE |
1 |
Abnormal termination. Error in process. |
- RETURN VALUE
-
NONE.
- SEE ALSO
-
abort
,atexit
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char *argv[])
{
FILE * pFile;
pFile = fopen (argv[1],"r");
if (pFile==NULL) {
printf ("Error opening file.\n");
exit (EXIT_FAILURE);
} else {
printf("Operation successful.\n");
exit(EXIT_SUCCESS);
}
fclose(pFile);
return 0;
}
- OUTPUT
$ gcc -Wall exit.c $ ./a.out hello Error opening file. $ ./a.out exit.c Operation successful.
free
- NAME
-
free - Deallocate dynamically allocated memory.
- SYNOPSIS
#include <stdlib.h>
void free(void * memblock);
- DESCRIPTION
-
A block of memory previously allocated by a call to
malloc
,calloc
orrealloc
is freed. The memblock parameter must point to a previously allocated memory block. If an invalid pointer is passed to the function the behavior is undefined. This function only frees memory allocated from the specified functions. Memory obtained from other methods (like C++'s new operator) should not be freed with this function. - PARAMETERS
-
-
memblock - pointer to the memory block to be freed.
-
- RETURN VALUE
-
NONE.
- SEE ALSO
-
malloc
,calloc
,realloc
- EXAMPLE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char * argv[])
{
FILE * pFile;
long lSize;
char *buffer;
int i;
pFile = fopen (argv[1] , "rb" );
if (pFile==NULL)
perror("fopen error");
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
buffer = (char*) malloc (lSize);
if (buffer==NULL)
perror("malloc error");
fread (buffer,1,lSize,pFile);
buffer[strlen(buffer)-1] = '\0';
for (i=strlen(buffer); i>=0; i--)
printf("%c", buffer[i]);
printf("\n");
fclose (pFile);
free (buffer);
return 0;
}
The above program allocates dynamically 100 bytes to store up to 100 characters. Next, using fgets()
up to 100 characters are read from stdin. Afterwards, the terminating \n
is overwritten bei a \0
.
Next, the program uses a loop to output the contents of the buffer in reverse order. Finally , the buffer is freed and the respective pointer is set back to NULL.
- OUTPUT
$ gcc -Wall free.c $ ./a.out Enter some text> 1234567890 0987654321 $ ./a.out Enter some text> 1 2 3 4 5 6 7 8 9 0 0 9 8 7 6 5 4 3 2 1 $ ./a.out Enter some text> mana mana oh mana mana mana ma oh mana mana mananana oh ho mananah manananah nahnah hanhan hanananam hananam oh ho anananam anam anam ho am anam anam anam ho anam anam
getenv
- NAME
-
getenv - Get string from environment.
- SYNOPSIS
#include <stdlib.h>
char *getenv(const char * varname);
- DESCRIPTION
-
Gets a pointer to the null-terminated string containing the value of the environment variable which name is specified in
varname
. If the requested variable is not defined in the environment the function returns a NULL pointer. The returned pointer is not intended for modifying operations on the environment variable. Refer toputenv
or your platform’s manual for that. - PARAMETERS
-
-
varname - Null-terminated string containing the name of the requested variable.
-
- RETURN VALUE
-
A null-terminated string with the value of the requested environment variable or NULL if that environment variable does not exist. Do not use this returned pointer to modify directly the environment variable from your program.
- SEE ALSO
-
malloc
,calloc
,realloc
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
char * buffer;
buffer = getenv ("PATH");
if (buffer!=NULL)
printf ("Current path is: %s\n",buffer);
return 0;
}
- OUTPUT
$ gcc -Wall getenv.c $ ./a.out Current path is: /usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:.
labs
- NAME
-
labs - absolute value of long integer parameter.
- SYNOPSIS
#include <stdlib.h>
double labs(long n);
- DESCRIPTION
-
The absolute value corresponding to the
long int
parameter n is returned (|n|). - PARAMETERS
-
-
n - integer value.
-
- SEE ALSO
-
abs
,fabs
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
int n,m;
n = labs(65537);
m = labs(-100000);
printf ("n=%d\n",n);
printf ("m=%d\n",m);
return 0;
}
- OUTPUT
$ gcc -Wall labs.c $ ./a.out n=65537 m=100000
malloc
- NAME
-
malloc - Allocate memory block.
- SYNOPSIS
#include <stdlib.h>
void * malloc ( size_t size );
- DESCRIPTION
-
Requests the allocation of a block of size bytes of memory. A pointer to the new block of memory is returned if successful. The dynamic memory should be freed using free once it is no longer needed.
- PARAMETERS
-
-
size - size in bytes of the block of memory requested.
-
- RETURN VALUE
-
A pointer to the allocated space. The type of this pointer is
"void *"
. A type cast to the desired type of data pointer should be performed on this returned pointer in order to be used as an ordinary array of a concrete type. If the system could not allocate the requested block of memory or if the size requested was 0 a NULL pointer is returned. - SEE ALSO
-
free
,calloc
,realloc
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
int i;
int n;
char * buffer;
printf ("How long do you want the string? ");
scanf ("%d", &i);
buffer = (char*)malloc(i+1);
if (buffer==NULL)
exit (1);
for (n=0; n<i; n++) {
buffer[n]=rand()%26+'a';
}
buffer[i]='\0';
printf ("Random string: %s\n",buffer);
free(buffer);
buffer=NULL;
return 0;
}
This program generates a string of the length specified by the user and fills it with alphabetic characters. The possible length of this string is only limited by the amount of
memory available in the system that malloc
can allocate.
- OUTPUT
$ gcc -Wall malloc.c $ ./a.out How long do you want the string? 5 Random string: nwlrb
malloc (memory allocation) is used to dynamically allocate memory at run time. Possible uses for this function are:
|
-
Read records of an unknown length.
-
Read an unknown number of database records.
-
Linked lists.
The simplest way to reserve memory is to code something like:
#include <string.h>
int main(void)
{
char string[1000];
strcpy (string, "Some text");
/* ... */
return 0;
}
The example above, however, has the following problems:
-
If the data is less than 1000 bytes the program wasting memory.
-
If the data is greater than 1000 bytes the program is going to crash.
-
The 1000 bytes are reserved throughout the life of the program. If this was a long running program that rarely used the memory, it would again be wasteful.
malloc
, in contrast, allows us to allocate exactly the correct amount of memory and with the use of free only for the time it is required.
#include <stdlib.h>
int main(void)
{
char * str;
str = (char *) malloc(1000);
/* ... */
free(str);
str=NULL;
return 0;
}
Looking at the example snippet above, 1000 bytes are reserved and the pointer String points to the first byte. The 1000 bytes are not initialized by malloc
. If the memory is not available, a NULL pointer is returned. Please note, the cast is required to return a pointer of the correct type.
mblen
- NAME
-
mblen - Returns the length of a multibyte character.
- SYNOPSIS
#include <stdlib.h>
int mblen(const char *c, size_t num);
- DESCRIPTION
-
The function calculates the length of the multibyte character
c
. At most, the multibyte character may consist ofnum
bytes. - PARAMETERS
-
-
c - Pointer to the first byte of a multibyte character. Alternatively, the function may be called with a null pointer, in which case the function resets its internal shift state to the initial value and returns whether multibyte characters have state-dependent encodings or not.
-
num - Maximum number of bytes to be checked for character length. No more than MB_CUR_MAX characters are examined in any case.
-
- RETURN VALUE
-
If the argument passed as
c
is not a null pointer, the size in bytes of the character pointed byc
is returned when it forms a valid multibyte character and is not the terminating null character. If it is the terminating null character, the function returns zero, and in the case they do not form a valid multibyte character, -1 is returned.
If the argument passed asc
is a null pointer, the function returns a nonzero value if multibyte character encodings are state-dependent, and zero otherwise. - SEE ALSO
-
mbstowcs
,mbstowcs
,mbtowc
,wcstombs
,wctomb
- EXAMPLE
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int length;
char string [6] = "w";
wchar_t arr[6];
/* Initialize internal state variable */
length = mblen(NULL, MB_CUR_MAX);
/* Set string to point to a multibyte character */
length = mblen(string, MB_CUR_MAX);
mbtowc(arr,string,length);
arr[1] = L'\0';
printf("wide character string: %ls\n", arr);
return 0;
}
- OUTPUT
$ gcc -Wall mblen.c $ ./a.out wide character string: w
mbstowcs
- NAME
-
mbstowcs - Convert a multibyte string to a wide character string.
- SYNOPSIS
#include <stdlib.h>
size_t mbstowcs(wchar_t *wcstr, const char *mbstr, size_t count);
- DESCRIPTION
-
The
mbstowcs
function converts up to a maximum number of count multibyte characters pointed to bymbstr
to a string of corresponding wide characters that are determined by the current locale. It stores the resulting wide-character string at the address represented bywcstr
. The result is similar to a series of calls tombtowc
. Ifmbstowcs
encounters the single-byte null character (\0) either before or when count occurs, it converts the null character to a wide-character null character (L'\0') and stops. Thus the wide-character string atwcstr
is null-terminated only if a null character is encountered during conversion. If the sequences pointed to bywcstr
andmbstr
overlap, the behavior is undefined. If thewcstr
argument is NULL,mbstowcs
returns the required size of the destination string. - PARAMETERS
-
-
wcstr - The address of a sequence of wide characters.
-
mbstr - The address of a sequence of null terminated multibyte characters.
-
count - The maximum number of multibyte characters to convert.
-
- RETURN VALUE
-
The number of characters translated, not including the ending null-character. If an invalid multibyte character is encountered, a -1 value is returned.
- SEE ALSO
-
mblen
,mbtowc
,wcstombs
,wctomb
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
int i;
char *pmbhello = (char *)malloc( MB_CUR_MAX );
wchar_t *pwchello = L"Hi";
wchar_t *pwc;
pwc = (wchar_t *)malloc( sizeof( wchar_t ));
printf( "Convert to multibyte string:\n" );
i = wcstombs( pmbhello, pwchello, MB_CUR_MAX );
printf( " Characters converted: %u\n", i );
printf( " Hex value of first" );
printf( " multibyte character: %#.4x\n\n", pmbhello[0] );
printf( "Convert back to wide-character string:\n" );
i = mbstowcs( pwc, pmbhello, MB_CUR_MAX );
printf( " Characters converted: %u\n", i );
printf( " Hex value of first" );
printf( " wide character: %#.4x\n\n", pwc[0] );
return 0;
}
- OUTPUT
$ gcc mbstowcs.c $ ./a.out Convert to multibyte string: Characters converted: 1 Hex value of first multibyte character: 0x0048 Convert back to wide-character string: Characters converted: 1 Hex value of first wide character: 0x0048
mbtowc
- NAME
-
mbtowc - Convert a multibyte character to a wide character.
- SYNOPSIS
#include <stdlib.h>
int mbtowc(wchar_t *wchar, const char *mbchar, size_t count);
- DESCRIPTION
-
The
mbtowc
function convertscount
or fewer bytes pointed to bymbchar
, ifmbchar
is not NULL, to a corresponding wide character.mbtowc
stores the resulting wide character atwchar
, ifwchar
is not NULL.mbtowc
does not examine more thanMB_CUR_MAX
bytes. - PARAMETERS
-
-
wchar - Address of a wide character (type
wchar_t
). -
mbchar - Address of a sequence of bytes (a multibyte character).
-
count - Number of bytes to check.
-
- RETURN VALUE
-
If
mbchar
is not NULL and if the object thatmbchar
points to forms a valid multibyte character,mbtowc
returns the length in bytes of the multibyte character. Ifmbchar
is NULL or the object that it points to is a wide-character null character (L'\0'
), the function returns 0. If the object thatmbchar
points to does not form a valid multibyte character within the first count characters, it returns -1. - SEE ALSO
-
mblen
,mbstowcs
,wcstombs
,wctomb
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
int i;
char *pmbc = (char *)malloc( sizeof( char ) );
wchar_t wc = L'a';
wchar_t *pwcnull = NULL;
wchar_t *pwc;
pwc = (wchar_t *)malloc( sizeof( wchar_t ) );
printf( "Convert a wide character to multibyte character:\n" );
i = wctomb( pmbc, wc );
printf( " Characters converted: %u\n", i );
printf( " Multibyte character: %x\n\n", *pmbc );
printf( "Convert multibyte character back to a wide " "character:\n" );
i = mbtowc( pwc, pmbc, MB_CUR_MAX );
printf( " Bytes converted: %u\n", i );
printf( " Wide character: %x\n\n", *pwc );
printf( "Attempt to convert when target is NULL\n" );
printf( " returns the length of the multibyte character:\n" );
i = mbtowc( pwcnull, pmbc, MB_CUR_MAX );
printf( " Length of multibyte character: %u\n\n", i );
printf( "Attempt to convert a NULL pointer to a" );
printf( " wide character:\n" );
pmbc = NULL;
i = mbtowc( pwc, pmbc, MB_CUR_MAX );
printf( " Bytes converted: %u\n", i );
return 0;
}
- OUTPUT
$ gcc mbtowc.c $ ./a.out Convert a wide character to multibyte character: Characters converted: 1 Multibyte character: 61 Convert multibyte character back to a wide character: Bytes converted: 1 Wide character: 61 Attempt to convert when target is NULL returns the length of the multibyte character: Length of multibyte character: 1 Attempt to convert a NULL pointer to a wide character: Bytes converted: 0
qsort
- NAME
-
qsort - Sort using quicksort algorithm.
- SYNOPSIS
#include <stdlib.h>
void qsort ( void * base, size_t num, size_t width, \
int (*fncompare)(const void *, const void *) );
- DESCRIPTION
-
This function uses an implementation of the quicksort algorithm to sort the
num
elements of an array pointed by base, each element has the specified width in bytes. The method used to compare each pair of elements is provided by the caller to this function withfncompare
parameter, that is a function called one or more times during the sort process. - PARAMETERS
-
-
base - Pointer to the first element of the array where the sorting process has to be performed.
-
num - Number of elements in the array pointed by base.
-
width - Width of each element in the array.
-
fncompare - Function that compares two elements. This should be provided by the caller to this function and must follow or be cast to a declaration like:
int fncompare (const void * elem1, const void * elem2);
-
The function should receive two parameters (elem1
and elem2
) that
are pointers to elements, and should return an int value with the
result of comparing them:
return value | description |
---|---|
< 0 |
*elem1 goes before *elem2 |
0 |
*elem1 == *elem2 |
> 0 |
*elem1 goes after *elem2 |
- RETURN VALUE
-
None.
- SEE ALSO
-
bsearch
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int compare (const void * a, const void * b);
int main (void)
{
int n;
int values[] = { 40, 10, 100, 90, 20, 25 };
for (n=0; n<6; n++) {
printf ("%d ",values[n]);
}
putchar('\n');
qsort (values, 6, sizeof(int), compare);
for (n=0; n<6; n++) {
printf ("%d ",values[n]);
}
putchar('\n');
return 0;
}
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
- OUTPUT
$ gcc -Wall qsort.c $ ./a.out 40 10 100 90 20 25 10 20 25 40 90 100
rand
- NAME
-
rand - Generate a random number.
- SYNOPSIS
#include <stdlib.h>
int rand(void);
- DESCRIPTION
-
Returns a pseudo-random number in the range from
0
to theRAND_MAX
constant. This is generated by an algorithm that returns a series of non-related numbers each time is called. The algorithm should be initialized to different starting points using functionsrand
to generate more realistic random numbers.RAND_MAX
is a constant defined instdlib.h
. Its default value is implementation specific. - PARAMETERS
-
None.
- RETURN VALUE
-
An integer value between
0
andRAND_MAX
. - SEE ALSO
-
srand
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main (void)
{
srand(time(NULL));
printf ("A number between 0 and RAND_MAX (%d): %d\n", RAND_MAX, rand());
printf ("A number between 0 and 99: %d\n", rand()%100);
printf ("A number between 20 and 29: %d\n", rand()%10+20);
return 0;
}
- OUTPUT
$ gcc -Wall rand.c $ ./a.out + A number between 0 and RAND_MAX (2147483647): 108411866 A number between 0 and 99: 2 A number between 20 and 29: 25
A good way to generate almost-true random numbers is to initialize the random algorithm using srand
with the current time in seconds as parameter, as obtained from time function included in time.h
. Furthermore, in order to obtain an integer random number in between a range 0 to RAND_MAX
use the modulo (%) operation on a result provided by rand()
: thus rand()%25
would be a
random number between 0
and 24
, both included.
realloc
- NAME
-
realloc - Reallocate memory block.
- SYNOPSIS
#include <stdlib.h>
void * realloc(void * memblock, size_t size);
- DESCRIPTION
-
The size of the block pointed to by the
memblock
parameter is changed to thesize
in bytes specified, expanding or reducing the amount of memory accessible in that block. The block could be moved to a new location in some cases, in this case the pointer returned by the function will point to the location. The content of the block will remain unchanged even if the block is moved and will be accessible from the new pointer. In case thatmemblock
is NULL the function behaves exactly asmalloc
assigning a new block ofsize
bytes and returning a pointer to the beginning of it. In case thatsize
is0
the memory previously allocated inmemblock
is de-allocated and a NULL pointer is returned. Dynamic memory allocated withmalloc
,calloc
andrealloc
should be freed usingfree
once it is no longer needed. - PARAMETERS
-
-
memblock - Pointer to a previously allocated block of memory. If it is NULL a new block is allocated and a pointer to it is returned by the function.
-
size - size in bytes of the block of memory requested. If it is
0
andmemblock
points to an existing block of memory this is de-allocated and a NULL pointer is returned by the function.
-
- RETURN VALUE
-
A pointer to the allocated space. The type of this pointer is
"void *"
. A type cast to the desired type of data pointer should be performed on this returned pointer in order to be used as an ordinary array of a concrete type. If the system could not allocate the requested block of memory or if the size requested was0
a NULL pointer is returned. - SEE ALSO
-
free
,calloc
,malloc
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
int input,n;
int count=0;
int *pNum = NULL;
do {
printf ("Enter an integer value (0 to end): ");
scanf ("%d", &input);
count++;
pNum = (int*) realloc (pNum, count * sizeof(int));
if (pNum==NULL) {
puts ("Error (re)allocating memory");
exit (1);
}
pNum[count-1]=input;
} while (input!=0);
printf ("Numbers entered: ");
for (n=0; n<count; n++) {
printf ("%d ",pNum[n]);
}
putchar('\n');
free (pNum);
pNum = NULL;
return 0;
}
- OUTPUT
$ gcc -Wall realloc.c $ ./a.out Enter an integer value (0 to end): 9 Enter an integer value (0 to end): 8 Enter an integer value (0 to end): 77 Enter an integer value (0 to end): 98 Enter an integer value (0 to end): -13 Enter an integer value (0 to end): 98 Enter an integer value (0 to end): 0 Numbers entered: 9 8 77 98 -13 98 0
The program prompts the user for numbers until a 0 is
entered. Each time a new value is introduced the memory block
pointed by numbers is increased by the size of an int
.
srand
- NAME
-
srand - Initialize random number generator.
- SYNOPSIS
#include <stdlib.h>
int srand ( unsigned int seed );
- DESCRIPTION
-
Uses seed parameter to set a new starting point for generating random numbers with rand. If seed is set to 1 the generator is reinitialized to its initial value as before any call to rand or srand. In order to generate true random numbers it is suggested to use as seed a value that changes often, like the one returned by time function included in
time.h
(the number of seconds elapsed since newyear 1970). - PARAMETERS
-
-
seed - An integer value to be used as starting point with the pseudo-random number generator algorithm.
-
- RETURN VALUE
-
None.
- SEE ALSO
-
rand
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main (void)
{
srand ( time(NULL) );
printf ("A number between 0 and 100: %d\n", rand()%100);
printf ("A number between 20 and 30: %d\n", rand()%10+20);
return 0;
}
- OUTPUT
$ gcc -Wall srand.c $ ./a.out A number between 0 and 100: 22 A number between 20 and 30: 25 $ ./a.out A number between 0 and 100: 33 A number between 20 and 30: 28
- EXAMPLE
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int rolls=4;
srand((unsigned int)time((time_t *)NULL));
while(rolls--) {
printf("Dice value is %d\n", (rand()%6)+1);
}
return 0;
}
- OUTPUT
$ gcc -Wall srand2.c $ ./a.out Dice value is 5 Dice value is 1 Dice value is 3 Dice value is 4
strtod
- NAME
-
strtod - Convert string to double-precision floating-point value.
- SYNOPSIS
#include <stdlib.h>
double strtod ( const char * string, char** endptr );
- DESCRIPTION
-
Parses string interpreting its content as a floating-point value until a character that can not be interpreted is found, and returns a double precision value.
- PARAMETERS
-
-
string - String representing a floating point number. The number is considered until a non-numeric character is found (digits, signs, E and e are considered valid numeric characters for this parameter as specified in format). The format used is:
[whitespaces][+|-][nnnnn][.nnnnn][e|E[+|-]nnnn]
(where whitespaces are any tab or space character and nnnnn may be any number of digits) -
endptr - Address of a pointer. This is filled by the function with the address where scan has ended. Serves to determine where there is the first non-numerical character in the string.
-
- RETURN VALUE
-
The converted double value from the input string. If conversion would cause overflow the result is
+/- HUGE_VAL
. If an error occurs 0 is returned. - SEE ALSO
-
atof
,strtol
,strtoul
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
char szInput [256];
char * pEnd;
double dbl;
printf ("Enter a floating-point value> ");
gets (szInput);
dbl = strtod (szInput,&pEnd);
printf ("Value entered: %lf. Its square: %lf\n",dbl,dbl*dbl);
return 0;
}
- OUTPUT
$ gcc -Wall strtod.c $ ./a.out Enter a floating-point value> 3.14 Value entered: 3.140000. Its square: 9.859600
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
char *string, *stopstring;
double x;
long l;
int base;
unsigned long ul;
string = "3.1415926This stopped it";
x = strtod( string, &stopstring );
printf( "string = %s\n", string );
printf(" strtod = %f\n", x );
printf(" Stopped scan at: %s\n\n", stopstring );
string = "-10110134932This stopped it";
l = strtol( string, &stopstring, 10 );
printf( "string = %s\n", string );
printf(" strtol = %ld\n", l );
printf(" Stopped scan at: %s\n\n", stopstring );
string = "10110134932";
printf( "string = %s\n", string );
for( base = 2; base <= 8; base *= 2 ) {
ul = strtoul( string, &stopstring, base );
printf( " strtol = %ld (base %d)\n", ul, base );
printf( " Stopped scan at: %s\n", stopstring );
}
return 0;
}
- OUTPUT
$ gcc -Wall strtod2.c $ ./a.out string = 3.1415926This stopped it strtod = 3.141593 Stopped scan at: This stopped it string = -10110134932This stopped it strtol = -2147483648 Stopped scan at: This stopped it string = 10110134932 strtol = 45 (base 2) Stopped scan at: 34932 strtol = 4423 (base 4) Stopped scan at: 4932 strtol = 2134108 (base 8) Stopped scan at: 932
strtol
- NAME
-
strtol - Convert string to a long integer.
- SYNOPSIS
#include <stdlib.h>
long strtol(const char * string, char** endptr, int radix);
- DESCRIPTION
-
Parses string interpreting its content as an integer value until a character that can not be interpreted is found, and returns a long int value.
- PARAMETERS
-
-
string - String representing an integer number. The number is considered until a non-numeric character is found (only the digits from 0 to radix-1 are considered valid numeric characters, signs are considered valid numeric characters for this parameter). The format used is:
[whitespaces][+|-][0|0x][nnnnn]
(where whitespaces are any tab or space character andnnnnn
is a sequence of valid numbers following the specified radix) -
endptr - Address of a pointer. This is filled by the function with the address where scan has ended. Serves to determine where there is the first non-numerical character in the string.
-
radix - Numeral radix in which the number to be interpreted. Must be 0 or be between 2 and 36. If it is 0 the radix of the string is determined by the initial characters of the string:
-
initial chars | Interpreted by strol as |
---|---|
0x |
hexadecimal: radix 16 |
0 |
octal: radix 8 |
[1-9] |
decimal: radix 10 |
- RETURN VALUE
-
The converted long int value from the input string. If conversion would cause overflow the result is
LONG_MAX
orLONG_MIN
. If an error occurs or no conversion can be made 0 is returned. - SEE ALSO
-
atof
,strtod
,strtol
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
char szInput [256];
char * pEnd;
unsigned long ul;
printf ("Enter an integer value: ");
gets (szInput);
ul = strtoul (szInput,&pEnd,0);
printf ("Value entered: %lu. Its double: %lu\n",ul,ul*2);
return 0;
}
- OUTPUT
Enter an integer value: 1234567890 Value entered: 1234567890. Its double: 2469135780
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char num[10];
strcpy(num,"13");
printf("%s(Oct) is %li(Dec)\n", num, strtol(num, NULL, 8));
printf("%s(Dec) is %li(Dec)\n", num, strtol(num, NULL, 10));
printf("%s(hex) is %li(Dec)\n", num, strtol(num, NULL, 16));
puts("----------------------------------");
strcpy(num, "13hzcd");
printf("%s(Oct) is %li(Dec)\n", num, strtol(num, NULL, 8));
printf("%s(Dec) is %li(Dec)\n", num, strtol(num, NULL, 10));
printf("%s(hex) is %li(Dec)\n", num, strtol(num, NULL, 16));
puts("----------------------------------");
strcpy(num, "hzcd");
printf("%s(Oct) is %li(Dec)\n", num, strtol(num, NULL, 8));
printf("%s(Dec) is %li(Dec)\n", num, strtol(num, NULL, 10));
printf("%s(hex) is %li(Dec)\n", num, strtol(num, NULL, 16));
puts("----------------------------------");
strcpy(num, "13");
printf("%s is %li(Dec)\n", num, strtol(num, NULL, 0));
strcpy(num, "013");
printf("%s is %li(Dec)\n", num, strtol(num, NULL, 0));
strcpy(num, "0x13");
printf("%s is %li(Dec)\n", num, strtol(num, NULL, 0));
return 0;
}
- OUTPUT
$ gcc -Wall strtol2.c $ ./a.out 13(Oct) is 11(Dec) 13(Dec) is 13(Dec) 13(hex) is 19(Dec) ---------------------------------- 13hzcd(Oct) is 11(Dec) 13hzcd(Dec) is 13(Dec) 13hzcd(hex) is 19(Dec) ---------------------------------- hzcd(Oct) is 0(Dec) hzcd(Dec) is 0(Dec) hzcd(hex) is 0(Dec) ---------------------------------- 13 is 13(Dec) 013 is 11(Dec) 0x13 is 19(Dec)
strtoul
- NAME
-
strtoul - Convert string to unsigned long integer.
- SYNOPSIS
#include <stdlib.h>
unsigned long strtoul(const char * string, char** endptr, int radix);
- DESCRIPTION
-
Parses string interpreting its content as an integer value until a character that can not be interpreted is found, and returns an unsigned long value.
- PARAMETERS
-
-
string - String representing an integer number. The number is considered until a non-numeric character is found (only the digits from 0 to radix-1 are considered valid numeric characters, signs are considered valid numeric characters for this parameter). The format used is:
[whitespaces][+|-][0|0x][nnnnn]
(where whitespaces are any tab or space character and nnnnn is a sequence of valid numbers following the specified radix). Although the value returned is unsigned, signs in the string will be read and considered. -
endptr - Address of a pointer. This is filled by the function with the address where scan has ended. Serves to determine where there is the first non-numerical character in the string.
-
radix - Numeral radix in which the number to be interpreted. Must be 0 or be between 2 and 36. If it is 0 the radix of the string is determined by the initial characters of the string:
-
initial chars | interpreted by strol as |
---|---|
0x |
hexadecimal: radix 16 |
0 |
octal: radix 8 |
[1-9] |
decimal: radix 10 |
- RETURN VALUE
-
The converted
unsigned long
value from the input string. If conversion would cause overflow the result isULONG_MAX
. If an error occurs or no conversion can be made 0 is returned. - SEE ALSO
-
atof
,strtod
,strtol
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
char szInput [256];
char * pEnd;
unsigned long ul;
printf ("Enter an integer value: ");
gets (szInput);
ul = strtoul (szInput,&pEnd,0);
printf ("Value entered: %lu. Its double: %lu\n",ul,ul*2);
return 0;
}
- OUTPUT
$ gcc -Wall strtoul.c $ ./a.out Enter an integer value: 0xAc32 Value entered: 44082. Its double: 88164
system
- NAME
-
system - Execute command.
- SYNOPSIS
#include <stdlib.h>
int system(const char * command);
- DESCRIPTION
-
Invokes command interpreter to execute a command. Once terminated, the interpreter gives back control to the program returning an int value.
The system function is used to issue a DOS/Unix command. Execution of your program will not continue until the command has completed. You will not be able to get the return code from the command or have access to the command output via system. If you need access to the output consider using popen command found in many Unix variants to execute the command. Note: popen is not
defined in the ANSI standard.
|
- PARAMETERS
-
-
command - Null-terminated string containing the system command to be executed.
-
- RETURN VALUE
-
If a command was successfully executed the command interpreter returns an adequate value; generally 0 indicates that the action performed by the command interpreter terminated with no errors. A return value of -1 indicates an error, and global variable
errno
is set to one of the following errors:
value | description |
---|---|
ENOENT |
Command interpreter not found |
ENOEXEC |
Command interpreter is not executable |
ENOMEM |
Error allocating memory for the process |
E2BIG |
Argument list too big |
- SEE ALSO
-
-
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char *argv[])
{
int i;
printf("Trying to execute command '%s'.\n", argv[1]);
i = system (argv[1]);
if (i==-1)
printf("Error executing '%s'.\n", argv[1]);
else
printf("Command '%s' successfully executed.\n", argv[1]);
return 0;
}
- OUTPUT
$ gcc -Wall system.c $ ./a.out "cat system.c" Trying to execute command 'cat system.c'. #include <stdlib.h> #include <stdio.h> int main (int argc, char *argv[]) { int i; printf("Trying to execute command '%s'.\n", argv[1]); i = system (argv[1]); if (i==-1) printf("Error executing '%s'.\n", argv[1]); else printf("Command '%s' successfully executed.\n", argv[1]); return 0; } Command 'cat system.c' successfully executed. $ ./a.out moin Trying to execute command 'moin'. sh: moin: command not found Command 'moin' successfully executed.
wcstombs
- NAME
-
wcstombs - Converts a wide character to the corresponding multibyte character string.
- SYNOPSIS
#include <stdlib.h>
size_t wcstombs( char *mbstr, const wchar_t *wcstr, size_t count );
- DESCRIPTION
-
The
wcstombs()
function converts a sequence of wide characters from the arraywcstr
into a sequence of multibyte characters and stores up to n bytes of multibyte characters in the arraymbstr
. - PARAMETERS
-
-
mbstr - The address of a sequence of multibyte characters.
-
wcstr - The address of a sequence of wide characters.
-
count - The maximum number of bytes that can be stored in the multibyte output string.
-
- RETURN VALUE
-
wcstombs()
returns the number of bytes stored inmbstr
or -1 ifmbstr
contains an invalid wide character. - SEE ALSO
-
mblen
,mbstowcs
,wctomb
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
int i;
char *pmbbuf = (char *)malloc( 100 );
wchar_t *pwchello = L"Hello, world.";
printf( "Convert wide-character string:\n" );
i = wcstombs( pmbbuf, pwchello, 100 );
printf( " Characters converted: %u\n", i );
printf( " Multibyte character: %s\n\n", pmbbuf );
return 0;
}
- OUTPUT
$ gcc -Wall wcstombs.c $ ./a.out Convert wide-character string: Characters converted: 13 Multibyte character: Hello, world.
wctomb
- NAME
-
wctomb - Converts a wide character to the corresponding multibyte character.
- SYNOPSIS
#include <stdlib.h>
int wctomb(char *mbchar, wchar_t wchar);
- DESCRIPTION
-
The
wctomb()
function converts a wide character wchar into a multibyte character and, ifmbchar
is not NULL, stores the multibyte character representation inmbchar
. - PARAMETERS
-
-
mbchar - The address of a multibyte character.
-
wchar - A wide character.
-
- RETURN VALUE
-
wctomb()
returns the number of bytes in the multibyte character or -1 if the wide character is not valid. - SEE ALSO
-
mblen
,mbstowcs
,wcstombs
- EXAMPLE
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
int i;
wchar_t wc = L'a';
char *pmbnull = NULL;
char *pmb = (char *)malloc( sizeof( char ) );
printf( "Convert a wide character:\n" );
i = wctomb( pmb, wc );
printf( " Characters converted: %u\n", i );
printf( " Multibyte character: %.1s\n\n", pmb );
printf( "Attempt to convert when target is NULL:\n" );
i = wctomb( pmbnull, wc );
printf( " Characters converted: %u\n", i );
printf( " Multibyte character: %.1s\n", pmbnull );
return 0;
}
- OUTPUT
$ ./a.out Convert a wide character: Characters converted: 1 Multibyte character: a Attempt to convert when target is NULL: Characters converted: 0 Multibyte character:
string.h
memchr
- NAME
-
memchr - Search buffer for a character.
- SYNOPSIS
#include <string.h>
void *memchr ( const void *buffer, int c, size_t num );
- DESCRIPTION
-
Searches the first num bytes of memory block pointed by buffer for character
c
. - PARAMETERS
-
-
buffer - Pointer to buffer.
-
c - Key character to look for.
-
num - Number of characters to check from buffer.
-
- RETURN VALUE
-
A pointer to the first occurrence of
c
in buffer. If character is not found the function returns NULL. - SEE ALSO
-
memcmp
,memcpy
,memset
,strchr
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char * pch;
char str[] = "Example string";
pch = (char*) memchr (str, 'l', strlen(str));
if (pch!=NULL) printf ("Character l was at position %d.\n", pch-str+1);
else printf ("Character l was not found");
return 0;
}
- OUTPUT
$ gcc -Wall memchr.c $ ./a.out Character l was at position 6.
memcmp
- NAME
-
memcmp - Compare two buffers.
- SYNOPSIS
#include <string.h>
int memcmp ( const void * buffer1, const void * buffer2, size_t num );
- DESCRIPTION
-
Compares the fisrt num bytes of two memory blocks pointed by buffer1 and buffer2.
- PARAMETERS
-
-
buffer1 - Pointer to buffer.
-
buffer2 - Pointer to buffer.
-
num - Number of bytes to compare.
-
- RETURN VALUE
-
Returns a value indicating the relationship between the buffers:
return value | description |
---|---|
< 0 |
buffer1 is less than buffer2 |
0 |
buffer1 is the same as buffer2 |
> 0 |
buffer1 is greater than buffer2 |
For comparative purposes, each byte is considered as unsigned char
.
- SEE ALSO
-
memchr
,memcpy
,memset
,strchr
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char str1[256];
char str2[256];
int n, len1, len2;
printf ("Enter a sentence: ");
fgets(str1,80,stdin);
str1[strlen(str1)-1]='\0';
printf ("Enter another sentence: ");
fgets(str2,80,stdin);
str2[strlen(str2)-1]='\0';
len1=strlen(str1);
len2=strlen(str2);
n = memcmp( str1, str2, len1>len2?len1:len2 );
if (n>0) {
printf ("'%s' is greater than '%s'\n",str1,str2);
} else {
if (n<0) {
printf ("'%s' is less than '%s'\n",str1,str2);
} else {
printf ("'%s' is the same as '%s'\n",str1,str2);
}
}
return 0;
}
- OUTPUT
$ gcc -Wall memcmp.c $ ./a.out Enter a sentence: Hello world. Enter another sentence: Hello world! 'Hello world.' is greater than 'Hello world!'$ $ gcc -Wall memcmp.c $ ./a.out Enter a sentence: Hello world. Enter another sentence: Hello world! 'Hello world.' is greater than 'Hello world!' $ ./a.out Enter a sentence: Hello world. Enter another sentence: Hello world. 'Hello world.' is the same as 'Hello world.' $ ./a.out Enter a sentence: Hello world! Enter another sentence: Hello world. 'Hello world!' is less than 'Hello world.'
memcpy
- NAME
-
memcpy - Copy data between two memory locations.
- SYNOPSIS
#include <string.h>
void * memcpy ( void * dest, const void * src, size_t num );
- DESCRIPTION
-
Copies
num
bytes fromsrc
buffer to memory location pointed bydest
. - PARAMETERS
-
-
dest - Destination buffer where data is copied.
-
src - Source buffer to copy from.
-
num - Number of bytes to copy.
-
- RETURN VALUE
-
dest
is returned. - SEE ALSO
-
memchr
,memcmp
,memset
,strchr
- EXAMPLE
#include <math.h>
#include <stdio.h>
int main (void)
{
double param, result;
param = 5.5;
result = log(param);
printf ("ln(%lf) = %lf\n", param, result );
return 0;
}
- OUTPUT
$ gcc -Wall memcpy.c $ ./a.out str1: Sample string str2: Sample string str3: copy successful
memmove
- NAME
-
memmove - Copy bytes from one buffer to another buffer.
- SYNOPSIS
#include <string.h>
void *memmove ( void *dest, const void *src, size_t num );
- DESCRIPTION
-
Copies
num
bytes fromdest
buffer to memory location pointed bysrc
. Even if the destination and source buffers overlap the copy is correctly performed. - PARAMETERS
-
-
dest - Destination buffer where data is copied.
-
src - Source buffer to copy from.
-
num - Number of bytes to copy.
-
- RETURN VALUE
-
dest
is returned. - SEE ALSO
-
memcpy
,strncpy
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char str[] = "memmove can be very useful......";
puts(str);
memmove (str+20,str+15,11);
puts (str);
return 0;
}
- OUTPUT
$ gcc -Wall memmove.c $ ./a.out memmove can be very useful...... memmove can be very very useful.
memset
- NAME
-
memset - Fill buffer with specified character.
- SYNOPSIS
#include <string.h>
void *memset ( void * buffer, int c, size_t num );
- DESCRIPTION
-
Sets the first num bytes pointed by buffer to the value specified by c parameter.
- PARAMETERS
-
-
buffer - Pointer to block of data to be filled with c.
-
c - Character value to set.
-
num - Number of bytes to copy.
-
- RETURN VALUE
-
buffer
is returned. - SEE ALSO
-
memcpy
,strncpy
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char str[] = "almost every programmer should know memset.";
puts(str);
memset (str,'-',6);
puts (str);
return 0;
}
- OUTPUT
$ gcc -Wall memset.c $ ./a.out almost every programmer should know memset. ------ every programmer should know memset.
strcat
- NAME
-
strcat - Append string.
- SYNOPSIS
#include <string.h>
char *strcat(char * dest, const char * src);
- DESCRIPTION
-
Appends
src
string todest
string. The terminating null character indest
is overwritten by the first character ofsrc
. The resulting string includes a null-character at end. - PARAMETERS
-
-
dest - Pointer to a null-terminated string with enough space allocated to contain both
src
anddest
. -
src - Null-terminated string to append.
-
- RETURN VALUE
-
dest
is returned. - SEE ALSO
-
strcpy
,strncat
,strncpy
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char str[80];
strcpy (str,"strings ");
strcat (str,"have been ");
strcat (str,"concatenated.");
puts (str);
return 0;
}
- OUTPUT
$ gcc -Wall strcat.c $ ./a.out strings have been concatenated.
strchr
- NAME
-
strchr - Find character in string.
- SYNOPSIS
#include <string.h>
char *strchr(const char * string, int c);
- DESCRIPTION
-
Returns the first occurrence of c in string. The null-terminating character is included as part of the string and can also be searched.
- PARAMETERS
-
-
string - Null-terminated string scanned in the search.
-
c - Character to be found.
-
- RETURN VALUE
-
If character is found, a pointer to the first occurrence of c in string is returned. If not, NULL is returned.
- SEE ALSO
-
strrchr
,strcspn
,strcmp
,strstr
,memchr
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char str[] = "This is a sample string";
char * pch;
printf ("Looking for 's' character in \"%s\"...\n",str);
pch=strchr(str,'s');
while (pch!=NULL) {
printf ("found at %d\n",pch-str+1);
pch=strchr(pch+1,'s');
}
return 0;
}
- OUTPUT
$ gcc -Wall strchr.c $ ./a.out Looking for 's' character in "This is a sample string"... found at 4 found at 7 found at 11 found at 18
- EXAMPLE
#include <stdio.h>
#include <string.h>
void find_comment(char *tline);
int main (void)
{
char teststr[40]= {"remove the following text: # remove me"};
printf("%s\n",teststr);
find_comment(teststr);
printf("%s\n",teststr);
return 0;
}
void find_comment(char *tline)
{
char *comment;
comment = strchr(tline, '#');
if (comment != 0) {
*comment = '\0';
}
comment = strchr(tline, '\n');
if (comment != 0) {
*comment = '\0';
}
}
- OUTPUT
$ gcc -Wall strchr2.c $ ./a.out remove the following text: # remove me remove the following text:
strcmp
- NAME
-
strcmp - Compare two strings.
- SYNOPSIS
#include <string.h>
int strcmp(const char * string1, const char * string2);
- DESCRIPTION
-
Compares
string1
tostring2
character by character. This function starts comparing the first character of each string. If they are equal to each other continues with the following pair until the characters differ or until end of string is reached. - PARAMETERS
-
-
string1 - Null-terminated string to compare.
-
string2 - Null-terminated string to compare.
-
- RETURN VALUE
-
Returns a value indicating the lexicographical relation between the strings:
return value | description |
---|---|
< 0 |
string1 is less than string2 |
0 |
string1 is the same as string2 |
> 0 |
string1 is greater than string2 |
- SEE ALSO
-
strrchr
,strncmp
,strspn
,memcmp
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char szKey[] = "apple";
char szInput[80];
do {
printf ("Which is my favourite fruit? ");
gets (szInput);
} while (strcmp (szKey,szInput) != 0);
printf ("Correct answer!\n");
return 0;
}
- OUTPUT
$ gcc -Wall strcmp.c $ ./a.out Which is my favourite fruit? banana Which is my favourite fruit? apple Correct answer!
strcoll
- NAME
-
strcoll - Compare two strings using locale settings.
- SYNOPSIS
#include <string.h>
int strcoll ( const char * string1, const char * string2 );
- DESCRIPTION
-
Compares
string1
tostring2
character by character according to the character table set by current locale. This function starts comparing the first character of each string. If they are equal to each other continues with the following pair until the characters differ or until end of string is reached. The behavior of this function is the same asstrcmp
but using locale character set order to compare. - PARAMETERS
-
-
string1 - Null-terminated string to compare.
-
string2 - Null-terminated string to compare.
-
- RETURN VALUE
-
Returns a value indicating the lexicographical relation between the strings:
return value | description |
---|---|
< 0 |
string1 is less than string2 |
0 |
string1 is the same as string2 |
> 0 |
string1 is greater than string2 |
- SEE ALSO
-
strcmp
,strncmp
,memcmp
- EXAMPLE
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[1])
{
char s[10] = "müller";
if (!strcoll(s, argv[1]))
printf("The strings are identical.\n");
else
printf("The strings are different.\n");
return 0;
}
- OUTPUT
$ gcc -Wall strcoll.c $ ./a.out mueller The strings are different. $ ./a.out müller The strings are identical.
strcpy
- NAME
-
strcpy - Copy string.
- SYNOPSIS
#include <string.h>
char *strcpy ( char * dest, const char * src );
- DESCRIPTION
-
Copies the content pointed by
src
todest
stopping after the terminating null-character is copied. dest should have enough memory space allocated to contain src string. - PARAMETERS
-
-
dest - Destination string. Should be long enough to contain string2.
-
src - Null-terminated string to copy.
-
- RETURN VALUE
-
dest
is returned. - SEE ALSO
-
strcat
,strncat
,strncpy
,memcpy
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char str1[]="Sample string";
char str2[40];
char str3[40];
strcpy (str2,str1);
strcpy (str3,"copy successful");
printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
return 0;
}
- OUTPUT
$ gcc -Wall strcpy.c $ ./a.out str1: Sample string str2: Sample string str3: copy successful
strcspn
- NAME
-
strcspn - Search string for occurrence of character set.
- SYNOPSIS
#include <string.h>
size_t strcspn(const char * string1, const char * string2);
- DESCRIPTION
-
Scans
string1
character by character, returning the number of characters read until the first occurrence of any character included instring2
. The search includes terminating null-characters, so the function will return the length of string1 if none of the characters included instring2
is instring1
. - PARAMETERS
-
-
string1 - Null-terminated string to be scanned.
-
string2 - Null-terminated string containing the character set to search for.
-
- RETURN VALUE
-
Returns the position in
string1
of the first occurrence of a component character ofstring2
. - SEE ALSO
-
strspn
,strstr
,strncmp
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char str1[] = "fcba73";
char str2[] = "1234567890";
int i;
printf("str1 = %s\n", str1);
printf(" ^ \n");
printf("pos....0...4 \n");
printf("str2 = %s\n", str2);
i = strcspn (str1,str2);
printf("-----------------\n");
printf ("The first character of str2 found in str1 is at position %d\n.",i);
return 0;
}
- OUTPUT
$ gcc -Wall strcspn.c $ ./a.out str1 = fcba73 ^ pos....0...4. str2 = 1234567890 ----------------- The first character of str2 found in str1 is at position 4.
strerror
- NAME
-
strerror - Get pointer to error message string.
- SYNOPSIS
#include <string.h>
char *strerror(int errnum);
- DESCRIPTION
-
Returns a pointer to a string with the error message corresponding to the errnum error number. The returned pointer points to a statically allocated string. Further calls to this function will overwrite its content. This funcion can be called with global variable errno declared in
errno.h
to get the last error produced by a call to a C library function. - PARAMETERS
-
errnum - Error number.
- RETURN VALUE
-
A pointer to the error string describing error errnum.
- SEE ALSO
-
clearerr
,perror
- EXAMPLE
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main (int argc, char *argv[])
{
FILE * pFile;
pFile = fopen(argv[1],"r");
if (pFile == NULL) {
printf ("Error opening file %s: %s\n",argv[1], strerror(errno));
exit(EXIT_FAILURE);
}
fclose(pFile);
return 0;
}
- OUTPUT
$ gcc -Wall strerror.c $ ./a.out Error opening file (null): Bad address $ ./a.out nofile.txt Error opening file nofile.txt: No such file or directory
strlen
- NAME
-
strlen - Return string length.
- SYNOPSIS
#include <string.h>
size_t strlen ( const char * string );
- DESCRIPTION
-
Returns the number of characters in string before the terminating null-character.
- PARAMETERS
-
string - Null-terminated string.
- RETURN VALUE
-
The length of string.
- SEE ALSO
-
strcmp
,strcspn
,strchr
,strrchr
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char szInput[256];
printf ("Enter a sentence> ");
gets (szInput);
printf ("The sentence entered is %u characters long.\n",strlen(szInput));
return 0;
}
- OUTPUT
$ gcc -Wall strlen.c $ ./a.out Enter a sentence> Learning C requires endurance and carefulness! The sentence entered is 46 characters long.
strncat
- NAME
-
strncat - Append substring to string.
- SYNOPSIS
#include <string.h>
char *strncat(char * dest, const char * src, sizet_t num);
- DESCRIPTION
-
Appends
num
characters ofsrc
string to thedest
string. If the terminating null-character appears insrc
string beforenum
character have been appended, the function appends the null-character todest
and ends. The terminating null character indest
is overwritten by the first character ofsrc
. The resulting string includes a null-character at end. - PARAMETERS
-
-
dest - Pointer to a null-terminated string with enough space allocated to contain
src
plusnum
characters. -
src - Null-terminated string containing characters to be appended.
-
num - Number of characters to be appended from
src
todest
.
-
- RETURN VALUE
-
dest
is returned. - SEE ALSO
-
strcat
,strcpy
,strncpy
,memcpy
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char str1[20];
char str2[20];
strcpy(str1,"To be ");
strcpy(str2,"or not to be.\n");
strncat(str1, str2, 6);
strcat(str1," ...");
puts (str1);
return 0;
}
- OUTPUT
$ gcc -Wall strncat.c $ ./a.out To be or not ...
strncmp
- NAME
-
strncmp - Compare some characters of two strings.
- SYNOPSIS
#include <string.h>
int strncmp(const char * string1, const char * string2, sizet_t num);
- DESCRIPTION
-
Compares the first
num
characters ofstring1
to the firstnum
characters ofstring2
. The comparison is performed character by character. If a character that is not equal in both strings is found the function ends and returns a value that determines which of them was greater. - PARAMETERS
-
-
string1 - Null-terminated string to compare.
-
string2 - Null-terminated string to compare.
-
num - Maximum number of characters to compare.
-
- RETURN VALUE
-
Returns a value indicating the lexicographical relation between the strings:
return value | description |
---|---|
< 0 |
string1 is less than string2 |
0 |
string1 is the same as string2 |
> 0 |
string1 is greater than string2 |
- SEE ALSO
-
strcat
,strcpy
,strncpy
,strset
,memcpy
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char str[][5] = { "R2D2" , "C3PO" , "V4DR" , "C3A4" , "LUKE" };
int n;
printf ("Looking for human relations robots...\n");
for (n=0 ; n < 5 ; n++) {
if (strncmp (str[n],"C3**",2) == 0) {
printf ("found %s\n",str[n]);
}
}
return 0;
}
- OUTPUT
$ gcc -Wall strncmp.c $ ./a.out Looking for human relations robots... found C3PO found C3A4
strncpy
- NAME
-
strncpy - Copy characters from one string to another.
- SYNOPSIS
#include <string.h>
char *strncpy(char * dest, const char * src, sizet_t num);
- DESCRIPTION
-
Copies the first
num
characters ofsrc
todest
. No null-character is implicitly appended todest
after copying process. Sodest
may not be null-terminated if no null-characters are copied fromsrc
. Ifnum
is greater than the length ofsrc
,dest
is padded with zeros untilnum
. - PARAMETERS
-
-
dest - Destination string. Space allocated should be at least
num
characters long. -
string2 - Null-terminated string.
-
num - Number of characters to be copied.
-
- RETURN VALUE
-
dest
is returned. - SEE ALSO
-
strcat
,strcpy
,strncat
,strstr
,memcpy
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char str1[]= "To be or not to be";
char str2[6];
strncpy (str2,str1,5);
str2[5]='\0';
puts (str2);
return 0;
}
- OUTPUT
$ gcc -Wall strncpy.c $ ./a.out To be
strpbrk
- NAME
-
strpbrk - Scan string for specified characters.
- SYNOPSIS
#include <string.h>
char *strpbrk(const char * string1, const char * string2);
- DESCRIPTION
-
Scans
string1
character by character, returning a pointer to the first character that matches with any of the characters instring2
. The search does not includes the terminating null-characters. - PARAMETERS
-
-
string1 - Null-terminated string to be scanned.
-
string2 - Null-terminated string containing the character set to search for.
-
- RETURN VALUE
-
A pointer to the first appearance in
string1
of a character specified instring2
. If none of the characters specified instring2
exists instring1
, a NULL pointer is returned. - SEE ALSO
-
strcspn
,strchr
,strrchr
,strstr
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char str[] = "This is a sample string";
char key[] = "aeiou";
char * pch;
printf ("Vowels in '%s': ",str);
pch = strpbrk (str, key);
while (pch != NULL) {
printf ("%c " , *pch);
pch = strpbrk (pch+1,key);
}
printf ("\n");
return 0;
}
- OUTPUT
$ gcc -Wall strpbrk.c $ ./a.out Vowels in 'This is a sample string': i i a a e i
- EXAMPLE
#include <stdio.h>
#include <string.h>
#include <strings.h>
#define LINE_BUF 100
void find_comment(char *);
int main(void)
{
char line[LINE_BUF];
char *sep;
printf("Enter a sentence - press ENTER twice to terminate.\n");
while (fgets(line, LINE_BUF, stdin)) {
sep = line;
while (sep != 0) {
sep = strpbrk(line, ";.&:,");
if (sep != NULL) {
*sep = ' ';
}
}
if (strlen(line)==1)
break;
fputs(line, stdout);
}
return 0;
}
- OUTPUT
$ gcc -Wall strpbrk2.c $ ./a.out Enter a sentence - press ENTER twice to terminate. Hello, how are you doing? Hello how are you doing? Please, don't remove all ','! Please don't remove all ' '! abc;def.ghi&jkl:mno,pqrabc def ghi jkl mno pqr abc def ghi amp jkl mno pqrabc def ghi jkl mno pqr
Turns miscellaneous field separators into just a space separating tokens for easy parsing by sscanf
. Eventually, the character separators and replacement character will be passed in as strings.
strrchr
- NAME
-
strrchr - Find last occurrence of character in string.
- SYNOPSIS
#include <string.h>
char *strrchr(const char * string, int c);
- DESCRIPTION
-
Returns the last occurrence of
c
in string. The null-terminating character is included as part of the string and can also be searched. - PARAMETERS
-
-
string - Null-terminated string scanned in the search.
-
c - Character to be found.
-
- RETURN VALUE
-
If character is found, a pointer to the last occurrence of c in string is returned. If not, NULL is returned.
- SEE ALSO
-
strcspn
,strchr
,strcmp
,strstr
,memchr
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char str[] = "This is a sample string.\n";
char * pch;
pch = strrchr(str,'s');
printf ("Last occurrence of 's' found at position %d.\n",pch-str+1);
return 0;
}
- OUTPUT
$ gcc -Wall strrchr.c $ ./a.out Last occurrence of 's' found at position 18.
strspn
- NAME
-
strspn - Get length of substring composed of given characters.
- SYNOPSIS
#include <string.h>
size_t strspn(const char * string1, const char * string2);
- DESCRIPTION
-
Scans
string1
character by character, returning the number of characters read before the first character not included instring2
is found. The search does not include terminating null-characters. - PARAMETERS
-
-
string1 - Null-terminated string to be scanned.
-
string2 - Null-terminated string containing character set.
-
- RETURN VALUE
-
Returns the length of the initial substring of
string1
that is only composed of characters included instring2
. - SEE ALSO
-
strcspn
,strchr
,strrchr
,strstr
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
int i;
char strtext[] = "129th";
char cset[] = "1234567890";
i = strspn (strtext,cset);
printf ("Length of initial number is %d.\n",i);
return 0;
}
- OUTPUT
$ gcc -Wall strspn.c $ ./a.out Length of initial number is 3.
strstr
- NAME
-
strstr - Find substring.
- SYNOPSIS
#include <string.h>
char *strstr(const char * string1, const char * string2);
- DESCRIPTION
-
Scans
string1
for the first occurrence ofstring2
. The search does not include terminating null-characters. - PARAMETERS
-
-
string1 - Null-terminated string to search.
-
string2 - Null-terminated string containing the substring to search for.
-
- RETURN VALUE
-
A pointer to the first occurrence of
string2
instring1
. Ifstring2
is not found instring1
the function returns NULL. - SEE ALSO
-
strcspn
,strspn
,strpbrk
,strchr
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char str[] ="This is a simple string.";
char * pch;
puts (str);
pch = strstr (str,"simple");
strncpy (pch,"sample",5);
puts (str);
return 0;
}
This example searches for the "simple" substring in str
and substitutes that word for "sample".
- OUTPUT
$ gcc -Wall strstr.c $ ./a.out This is a simple string. This is a sample string.
- EXAMPLE
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char string[]="string to search";
char test[20];
printf("Enter a search string> ");
scanf("%s",test);
if (strstr(string, test)) {
puts("String found.");
} else {
puts("String not found.");
}
return 0;
}
- OUTPUT
$ gcc -Wall strstr2.c $ ./a.out Enter a search string> sear String found. $ ./a.out Enter a search string> test String not found.
strtok
- NAME
-
strtok - Sequentially truncate string if delimiter is found.
- SYNOPSIS
#include <string.h>
char *strtok(const char * string, const char * delimiters);
- DESCRIPTION
-
If string is not NULL, the function scans string for the first occurrence of any character included in delimiters. If it is found, the function overwrites the delimiter in string by a null-character and returns a pointer to the token, i.e. the part of the scanned string previous to the delimiter. After a first call to
strtok
, the function may be called with NULL as string parameter, and it will follow by where the last call tostrtok
found a delimiter. delimiters may vary from a call to another.
strtok will alter the input string by placing NULLS at the delimiter positions. A good habit is to copy the string to a temporary string and use the copy in the strtok call.More than one delimiter can be specified. So you can code, e.g.: word = strtok(string, " \t;:,"); You do not have to include the '\0' or NULL character.
|
- PARAMETERS
-
-
string - Null-terminated string to scan.
-
separator - Null-terminated string containing the separators.
-
- RETURN VALUE
-
A pointer to the last token found in string. NULL is returned when there are no more tokens to be found.
- SEE ALSO
-
strcspn
,strspn
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char str[] ="This is a sample string,just testing.";
char * pch;
printf ("Splitting string \"%s\" in tokens:\n",str);
pch = strtok (str," ");
while (pch != NULL) {
printf ("%s\n",pch);
pch = strtok (NULL, " ,.");
}
return 0;
}
- OUTPUT
$ gcc -Wall strtok.c $ ./a.out Splitting string "This is a sample string,just testing." in tokens: This is a sample string just testing
- EXAMPLE
#include <stdio.h>
#include <string.h>
int main(void)
{
char test_string[50]="string to split up";
char *sub_string;
printf("%s\n",test_string);
printf("------------------\n");
printf("%s\n", strtok(test_string, " "));
while ( (sub_string = strtok(NULL, " ")) != NULL) {
printf("%s\n", sub_string);
}
return 0;
}
- OUTPUT
$ gcc -Wall strtok2.c $ ./a.out string to split up ------------------ string to split up
strxfrm
- NAME
-
strxfrm - Transform string using locale settings.
- SYNOPSIS
#include <string.h>
size_t strxfrm(const char * dest, const char * src, size_t num);
- DESCRIPTION
-
Copies the first
num
characters ofsrc
todest
performing the appropriate transformations for the current locale settings if needed. No null-character is implicitly appended todest
after copying process. Sodest
may not be null-terminated if no null-characters are copied fromsrc
. Ifnum
is greater than the length ofsrc
,dest
is padded with zeros untilnum
. The behavior of this function is the same asstrncpy
but performing locale character transformations. - PARAMETERS
-
-
dest - Destination string. Space allocated should be at least
num
characters long. -
string2 - Null-terminated string containing string to be transformed.
-
num - Number of characters to be transformed and stored in
dest
.
-
- RETURN VALUE
-
The length of the transformed string without the null-character terminator.
- SEE ALSO
-
strcmp
,strncmp
,memcmp
- EXAMPLE
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[] = "Hello Mister Müller";
printf("The length of str = %d\n",strxfrm(NULL, str, 0));
printf("The content of str = %s\n", str);
return 0;
}
- OUTPUT
$ gcc -Wall strxfrm.c $ ./a.out The length of str = 18 The content of str = Hello Mister Müller
- EXAMPLE
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[] = "Hello Mister Müller";
printf("The length of str = %d\n",strxfrm(NULL, str, 0));
printf("The content of str = %s\n", str);
return 0;
}
- OUTPUT
$ gcc -Wall strxfrm2.c $ ./a.out Müller Bäcker Müller Bäcker (15)
time.h
TIME Summary
Standard C library with time and date related functions:
-
asctime
,clock
,ctime
,difftime
,gmtime
,localtime
,mktime
,strftime
,time
Types and constants:
-
CLOCKS_PER_SEC
constant that defines the number of clock ticks per second used by clock function. -
clock_t
andtime_t
- Data types returned by clock and time functions respectively. They are generally defined as long int. -
tm
- Structure returned or used byasctime
,gmtime
,localtime
andmktime
.
struct tm { int tm_hour; /* hour (0 - 23) */ int tm_isdst; /* daylight saving time enabled/disabled */ int tm_mday; /* day of month (1 - 31) */ int tm_min; /* minutes (0 - 59) */ int tm_mon; /* month (0 - 11 : 0 = January) */ int tm_sec; /* seconds (0 - 59) */ int tm_wday; /* Day of week (0 - 6 : 0 = Sunday) */ int tm_yday; /* Day of year (0 - 365) */ int tm_year; /* Year less 1900 */ };
asctime
- NAME
-
asctime - Convert tm structure to string.
- SYNOPSIS
#include <time.h>
char *asctime ( const struct tm * tmptr );
- DESCRIPTION
-
Converts data pointed by
tmptr
to a string containing time and date in a readable format.tmptr
is a pointer to a tm structure as the ones returned bygmtime
andlocaltime
. The returned string has the following format:Www Mmm dd hh:mm:ss yyyy
whereWww
is the weekday,Mmm
the month in letters,dd
the day of the month,hh:mm:ss
the time, andyyyy
the year. The string is followed by a new-line character (\n
) and a terminating null-character, conforming a total of 26 characters. - PARAMETERS
-
tmptr
- Pointer to tm structure containing time and date information to be converted. - RETURN VALUE
-
A pointer to the string containing the date and time information in readable format. The string pointed is statically allocated and shared by ctime and asctime functions. Each time one of these functions is called the content of the string is overwritten.
- SEE ALSO
-
ctime
,gmtime
,localtime
,time
- EXAMPLE
#include <time.h>
#include <stdio.h>
int main (void)
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current date and time are: %s", asctime (timeinfo) );
return 0;
}
- OUTPUT
$ gcc -Wall asctime.c $ ./a.out Current date and time are: Thu Sep 6 10:40:57 2012
clock
- NAME
-
clock - Return number of clock ticks since process start.
- SYNOPSIS
#include <time.h>
clock_t clock ( void );
- DESCRIPTION
-
Returns the number of clock ticks elapsed. A macro constant called
CLK_TCK
defines the relation between clock tick and second (clock ticks per second). - PARAMETERS
-
None.
- RETURN VALUE
-
The number of clock ticks elapsed since start.
clock_t
type is defined by default aslong int
by most compilers. - SEE ALSO
-
time
,difftime
- EXAMPLE
#include <time.h>
#include <stdio.h>
#ifndef CLK_TCK
#define CLK_TCK 1000
#endif
void wait ( int seconds );
int main (void)
{
int n;
printf ("Starting countdown...\n");
for (n=10; n>0; n--) {
printf ("%d\n",n);
wait (1);
}
printf ("FIRE!!!\n");
return 0;
}
void wait ( int seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLK_TCK ;
while (clock() < endwait) {}
}
- OUTPUT
$ gcc -Wall clock.c $ ./a.out Starting countdown... 10 9 8 7 6 5 4 3 2 1 FIRE!!!
ctime
- NAME
-
ctime - Convert time_t value to string.
- SYNOPSIS
#include <time.h>
char *ctime ( const time_t * timer );
- DESCRIPTION
-
Converts timer to a string containing time and date adjusted to local time zone in readable format. timer is an integer value of type time_t defined as long int by default in most compilers, and usually returned by a call to time function. The returned string has the following format:
Www Mmm dd hh:mm:ss yyyy
whereWww
is the weekday,Mmm
the month in letters,dd
the day of the month,hh:mm:ss
the time, andyyyy
the year. The string is followed by a new-line character (\n
) and a terminating null-character, conforming a total of 26 characters. - PARAMETERS
-
-
tmptr - Pointer to a time_t value, usually returned by time function.
-
- RETURN VALUE
-
A pointer to the string containing the date and time information in readable format. The string pointed is statically allocated and shared by
ctime
andasctime
functions. Each time one of these functions is called the content of the string is overwritten.ctime
also uses internally the buffer used bygmtime
andlocaltime
as return value, so a call to this function will overwrite this. - SEE ALSO
-
asctime
,gmtime
,localtime
,time
- EXAMPLE
#include <time.h>
#include <stdio.h>
int main (void)
{
time_t rawtime;
time (&rawtime);
printf ( "Current date and time are: %s", ctime(&rawtime) );
return 0;
}
- OUTPUT
$ gcc -Wall ctime.c $ ./a.out Current date and time are: Thu Sep 6 13:31:33 2012
difftime
- NAME
-
difftime - Return difference between two times.
- SYNOPSIS
#include <time.h>
double difftime(time_t timer2, time_t timer1);
- DESCRIPTION
-
Calculates the time difference between
timer1
andtimer2
in seconds. - PARAMETERS
-
-
timer2 - Later time.
-
timer1 - Former time.
-
- RETURN VALUE
-
The difference in seconds between the two times specified.
- SEE ALSO
-
asctime
,gmtime
,localtime
,time
- EXAMPLE
#include <time.h>
#include <stdio.h>
int main (void)
{
time_t start,end;
char szInput [256];
double dif;
time (&start);
printf ("Please, enter your name: ");
gets (szInput);
time (&end);
dif = difftime (end,start);
printf ("Hi %s.\n", szInput);
printf ("You have taken %.2lf seconds to type your name.\n", dif );
return 0;
}
- OUTPUT
$ gcc -Wall difftime.c $ ./a.out Please, enter your name: Tom Hi Tom. You have taken 3.00 seconds to type your name.
gmtime
- NAME
-
gmtime - Convert time_t value to tm structure as UTC time.
- SYNOPSIS
#include <time.h>
struct tm *gmtime(const time_t * timer);
- DESCRIPTION
-
Converts timer to tm structure adjusting to UTC (formerly known as GMT) timezone.
- PARAMETERS
-
-
timer - Pointer to a
time_t
value, usually returned by time function.
-
- RETURN VALUE
-
A pointer to a tm structure. This structure is statically allocated and shared by gmtime, localtime and ctime functions. Each time one of these functions is called the content of the structure is overwritten.
- SEE ALSO
-
asctime
,ctime
,localtime
,mktime
,time
- EXAMPLE
#include <time.h>
#include <stdio.h>
#define PST (-8)
#define CET (1)
#define HKG (8)
int main (void)
{
time_t rawtime;
struct tm * ptm;
time ( &rawtime );
ptm = gmtime ( &rawtime );
printf ("Time in Los Angeles: %2d:%02d\n", ptm->tm_hour+PST, ptm->tm_min);
printf ("Time in Berlin: %2d:%02d\n", ptm->tm_hour+CET, ptm->tm_min);
printf ("Time in Hong Kong: %2d:%02d\n", ptm->tm_hour+HKG, ptm->tm_min);
return 0;
}
- OUTPUT
$ gcc -Wall gmtime.c $ ./a.out Time in Los Angeles: 1:04 Time in Berlin: 10:04 Time in Hong Kong: 17:04
localtime
- NAME
-
localtime - Convert
time_t
value to atm
structure as local time. - SYNOPSIS
#include <time.h>
struct tm * localtime ( const time_t * timer );
- DESCRIPTION
-
Converts timer to
tm
structure adjusting to the local time zone. - PARAMETERS
-
-
timer - Pointer to a
time_t
value, usually returned by time function.
-
- RETURN VALUE
-
A pointer to a
tm
structure. This structure is statically allocated and shared bygmtime
,localtime
andctime
functions. Each time one of these functions is called the content of the structure is overwritten. - SEE ALSO
-
asctime
,ctime
,localtime
,mktime
,time
- EXAMPLE
#include <time.h>
#include <stdio.h>
int main (void)
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current date and time are: %s", asctime (timeinfo) );
return 0;
}
- OUTPUT
$ gcc -Wall localtime.c $ ./a.out Current date and time are: Sat Sep 8 12:40:56 2012
mktime
- NAME
-
mktime - Convert tm structure to time_t value.
- SYNOPSIS
#include <time.h>
time_t mktime ( struct tm * ptm );
- DESCRIPTION
-
Checks the members of the
tm
structure passed as parameterptm
adjusting the values if the ones provided are not in the possible range or they are incomplete or mistaken and then translates that structure to atime_t
value (seconds elapsed since Jan 1, 1970) that is returned. The original values oftm_wday
andtm_yday
members ofptm
are ignored and filled with the correspondent ones to the calculated date. The range oftm_mday
is not checked untiltm_mon
andtm_year
are determined. - PARAMETERS
-
-
ptm - Pointer to a
tm
structure, that contains data to be computed.
-
- RETURN VALUE
-
A
time_t
value corresponding to the date and time passed inptm
parameter. On error, a -1 value is returned. - SEE ALSO
-
asctime
,gmtime
,localtime
,time
- EXAMPLE
#include <time.h>
#include <stdio.h>
int main (void)
{
time_t rawtime;
struct tm * timeinfo;
int year, month ,day;
char * weekday[] = { "Sunday", "Monday", "Tuesday", "Wednesday", \
"Thursday", "Friday", "Saturday"};
printf ("Enter year: ");
scanf ("%d",&year);
printf ("Enter month: ");
scanf ("%d",&month);
printf ("Enter day: ");
scanf ("%d",&day);
time ( &rawtime );
timeinfo = localtime ( &rawtime );
timeinfo->tm_year = year - 1900;
timeinfo->tm_mon = month - 1;
timeinfo->tm_mday = day; /* call mktime: timeinfo->tm_wday will be set */
mktime ( timeinfo );
printf ("That day is a %s.\n", weekday[timeinfo->tm_wday]);
return 0;
}
- OUTPUT
$ gcc -Wall mktime.c $ ./a.out Enter year: 2012 Enter month: 8 Enter day: 1 That day is a Wednesday.
strftime
- NAME
-
strftime - Format date and time.
- SYNOPSIS
#include <time.h>
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);
- DESCRIPTION
-
The
strftime()
function formats the broken-down timetm
according to the format specification format and places the result in the character array s of size max. Ordinary characters placed in the format string are copied to s without conversion. Conversion specifiers are introduced by a'%'
character, and are replaced in s as follows:
%a |
The abbreviated weekday name according to the current locale. |
%A |
The full weekday name according to the current locale. |
%b |
The abbreviated month name according to the current locale. |
%B |
The full month name according to the current locale. |
%c |
The preferred date and time representation for the current locale. |
%d |
The day of the month as a decimal number (range 0 to 31). |
%H |
The hour as a decimal number using a 24-hour clock (range 00 to 23). |
%I |
The hour as a decimal number using a 12-hour clock (range 01 to 12). |
%j |
The day of the year as a decimal number (range 001 to 366). |
%m |
The month as a decimal number (range 10 to 12). |
%M |
The minute as a decimal number. |
%p |
Either ‘am’ or ‘pm’ according to the given time value, or the corresponding strings for the current locale. |
%S |
The second as a decimal number. |
%U |
The week number of the current year as a decimal number, starting with the first Sunday as the first day of the first week. |
%W |
The week number of the current year as a decimal number, starting with the first Monday as the first day of the first week. |
%w |
The day of the week as a decimal, Sunday being 0. |
%x |
The preferred date representation for the current locale without the time. |
%X |
The preferred time representation for the current locale without the date. |
%y |
The year as a decimal number without a century (range 00 to 99). |
%Y |
The year as a decimal number including the century. |
%Z |
The time zone or name or abbreviation. |
%% |
A literal |
- PARAMETERS
-
-
s - Points to the array containing the output date and time string.
-
max - Specifies the maximum number of bytes or wide characters to be written to the array pointed to by the
s
orwcs
parameter. -
format - Points to a sequence of characters that specify the format of the date and time to be written to the output string or wide-character string.
-
tm - Points to a type
tm
structure that contains broken-down time information.
-
- RETURN VALUE
-
The
strftime()
function returns the number of characters placed in the array s, not including the terminating NULL character. If the value equals max, it means that the array was too small. - SEE ALSO
-
ctime
,time
- EXAMPLE
#include <string.h>
#include <stdio.h>
int main (void)
{
char szKey[] = "apple";
char szInput[80];
do {
printf ("Which is my favourite fruit? ");
gets (szInput);
} while (strcmp (szKey,szInput) != 0);
printf ("Correct answer!\n");
return 0;
}
- OUTPUT
$ gcc -Wall strftime.c $ ./a.out It is Monday.
The %S seconds field can contain a value up to 61 seconds rather than up to 59 seconds to allow leap seconds that are sometimes added to years to keep clocks in correspondence with the
solar year.
|
time
- NAME
-
time - Get current time.
- SYNOPSIS
#include <time.h>
time_t time ( time_t * timer );
- DESCRIPTION
-
Get the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC from the system clock
- PARAMETERS
-
-
timer - Location where to store the retrieved value. If this is NULL the value is not stored. But it is still returned by the function. time_t is generally defined by default to long.
-
- RETURN VALUE
-
Elapsed time in seconds, as described.
- SEE ALSO
-
asctime
,gmtime
,localtime
- EXAMPLE
#include <time.h>
#include <stdio.h>
int main (void)
{
time_t seconds;
seconds = time (NULL);
printf ("%ld hours since January 1, 1970\n", seconds/3600);
return 0;
}
- OUTPUT
$ gcc -Wall time.c $ ./a.out 374241 hours since January 1, 1970
ASCII Table
The following table lists the ASCII characters and their decimal, octal and hexadecimal numbers. Characters which appear as names in parentheses (e.g. (NUL)) are non-printing characters. A table of the common non-printing characters appears after this table.
Oct | Dec | Hex | Abbr | Oct | Dec | Hex | Glyph | Oct | Dec | Hex | Glyph | Oct | Dec | Hex | Glyph |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0000 |
0 |
0x0 |
(NUL) |
0040 |
32 |
0x20 |
(SP) |
0100 |
64 |
0x40 |
@ |
0140 |
96 |
0x60 |
` |
0001 |
1 |
0x1 |
(SOH) |
0041 |
33 |
0x21 |
! |
0101 |
65 |
0x41 |
A |
0141 |
97 |
0x61 |
a |
0002 |
2 |
0x2 |
(STX) |
0042 |
34 |
0x22 |
"""" |
0102 |
66 |
0x42 |
B |
0142 |
98 |
0x62 |
b |
0003 |
3 |
0x3 |
(ETX) |
0043 |
35 |
0x23 |
# |
0103 |
67 |
0x43 |
C |
0143 |
99 |
0x63 |
c |
0004 |
4 |
0x4 |
(EOT) |
0044 |
36 |
0x24 |
$ |
0104 |
68 |
0x44 |
D |
0144 |
100 |
0x64 |
d |
0005 |
5 |
0x5 |
(ENQ) |
0045 |
37 |
0x25 |
% |
0105 |
69 |
0x45 |
E |
0145 |
101 |
0x65 |
e |
0006 |
6 |
0x6 |
(ACK) |
0046 |
38 |
0x26 |
& |
0106 |
70 |
0x46 |
F |
0146 |
102 |
0x66 |
f |
0007 |
7 |
0x7 |
(BEL) |
0047 |
39 |
0x27 |
' |
0107 |
71 |
0x47 |
G |
0147 |
103 |
0x67 |
g |
0010 |
8 |
0x8 |
(BS) |
0050 |
40 |
0x28 |
( |
0110 |
72 |
0x48 |
H |
0150 |
104 |
0x68 |
h |
0011 |
9 |
0x9 |
(HT) |
0051 |
41 |
0x29 |
) |
0111 |
73 |
0x49 |
I |
0151 |
105 |
0x69 |
i |
0012 |
10 |
0x0A |
(LF) |
0052 |
42 |
0x2A |
* |
0112 |
74 |
0x4A |
J |
0152 |
106 |
0x6A |
j |
0013 |
11 |
0x0B |
(VT) |
0053 |
43 |
0x2B |
+ |
0113 |
75 |
0x4B |
K |
0153 |
107 |
0x6B |
k |
0014 |
12 |
0x0C |
(FF) |
0054 |
44 |
0x2C |
, |
0114 |
76 |
0x4C |
L |
0154 |
108 |
0x6C |
l |
0015 |
13 |
0x0D |
(CR) |
0055 |
45 |
0x2D |
- |
0115 |
77 |
0x4D |
M |
0155 |
109 |
0x6D |
m |
0016 |
14 |
0x0E |
(SO) |
0056 |
46 |
0x2E |
. |
0116 |
78 |
0x4E |
N |
0156 |
110 |
0x6E |
n |
0017 |
15 |
0x0F |
(SI) |
0057 |
47 |
0x2F |
/ |
0117 |
79 |
0x4F |
O |
0157 |
111 |
0x6F |
o |
0020 |
16 |
0x10 |
(DLE9 |
0060 |
48 |
0x30 |
0 |
0120 |
80 |
0x50 |
P |
0160 |
112 |
0x70 |
p |
0021 |
17 |
0x11 |
(DC1) |
0061 |
49 |
0x31 |
1 |
0121 |
81 |
0x51 |
Q |
0161 |
113 |
0x71 |
q |
0022 |
18 |
0x12 |
(DC2) |
0062 |
50 |
0x32 |
2 |
0122 |
82 |
0x52 |
R |
0162 |
114 |
0x72 |
r |
0023 |
19 |
0x13 |
(DC3) |
0063 |
51 |
0x33 |
3 |
0123 |
83 |
0x53 |
S |
0163 |
115 |
0x73 |
s |
0024 |
20 |
0x14 |
(DC4) |
0064 |
52 |
0x34 |
4 |
0124 |
84 |
0x54 |
T |
0164 |
116 |
0x74 |
t |
0025 |
21 |
0x15 |
(NAK) |
0065 |
53 |
0x35 |
5 |
0125 |
85 |
0x55 |
U |
0165 |
117 |
0x75 |
u |
0026 |
22 |
0x16 |
(SYN) |
0066 |
54 |
0x36 |
6 |
0126 |
86 |
0x56 |
V |
0166 |
118 |
0x76 |
v |
0027 |
23 |
0x17 |
(ETB) |
0067 |
55 |
0x37 |
7 |
0127 |
87 |
0x57 |
W |
0167 |
119 |
0x77 |
w |
0030 |
24 |
0x18 |
(CAN) |
0070 |
56 |
0x38 |
8 |
0130 |
88 |
0x58 |
X |
0170 |
120 |
0x78 |
x |
0031 |
25 |
0x19 |
(EM) |
0071 |
57 |
0x39 |
9 |
0131 |
89 |
0x59 |
Y |
0171 |
121 |
0x79 |
y |
0032 |
26 |
0x1A |
(SUB) |
0072 |
58 |
0x3A |
: |
0132 |
90 |
0x5A |
Z |
0172 |
122 |
0x7A |
z |
0033 |
27 |
0x1B |
(ESC) |
0073 |
59 |
0x3B |
; |
0133 |
91 |
0x5B |
[ |
0173 |
123 |
0x7B |
{ |
0034 |
28 |
0x1C |
(FS) |
0074 |
60 |
0x3C |
< |
0134 |
92 |
0x5C |
\ |
0174 |
124 |
0x7C |
| |
0035 |
29 |
0x1D |
(GS) |
0075 |
61 |
0x3D |
= |
0135 |
93 |
0x5D |
] |
0175 |
125 |
0x7D |
} |
0036 |
30 |
0x1E |
(RS) |
0076 |
62 |
0x3E |
> |
0136 |
94 |
0x5E |
^ |
0176 |
126 |
0x7E |
~ |
0037 |
31 |
0x1F |
(US) |
0077 |
63 |
0x3F |
? |
0137 |
95 |
0x5F |
_ |
0177 |
127 |
0x7F |
(DEL) |
ASCII Code | Description | C Escape Sequence |
---|---|---|
(NUL) |
Null Byte |
\0 |
(BEL) |
Bell Character |
\a |
(BS) |
Backspace |
\b |
(HT) |
Horizontal Tab |
\t |
(NP) |
Formfeed |
\f |
(NL) |
Newline |
\n |
(CR) |
Carriage Return |
\r |
(VT) |
Vertical Tab |
|
(ESC) |
Escape |
|
(SP) |
Space |