About the Tutorial
C is a general-purpose, procedural, imperative computer programming language
developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to
develop the Unix operating system.
C is the most widely used computer language that keeps fluctuating at number
one scale of popularity along with Java programming language which is also
equally popular and most widely used among modern software programmers.
The C Standard Library is a set of C built-in functions, constants and header files
like <assert.h>, <ctype.h>, etc. This library will work as a reference manual for C
programmers.

Audience
The C Standard Library is a reference for C programmers to help them in their
projects related to system programming. All the C functions have been explained
in a user-friendly way and they can be copied and pasted in your C projects.

Prerequisites
A basic understanding of the C Programming language will help you in
understanding the C built-in functions covered in this library.

Copyright & Disclaimer
 Copyright 2014 by Tutorials Point (I) Pvt. Ltd.
All the content and graphics published in this e-book are the property of
Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain,
copy, distribute or republish any contents or a part of contents of this e-book in
any manner without written consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as
precisely as possible, however, the contents may contain inaccuracies or errors.
Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy,
timeliness or completeness of our website or its contents including this tutorial.
If you discover any errors on our website or in this tutorial, please notify us at
contact@tutorialspoint.com

i

Table of Contents
The C Standard Library Reference .............................................................................................................. i
Audience .................................................................................................................................................... i
Prerequisites .............................................................................................................................................. i
Copyright & Disclaimer .............................................................................................................................. i
Table of Contents ...................................................................................................................................... ii

1. <ASSERT.H> ............................................................................................................................. 1
Introduction .............................................................................................................................................. 1
Library Macros .......................................................................................................................................... 1
void assert(int expression) ......................................................................................................................... 1

2. <CTYPE.H>............................................................................................................................... 3
Introduction .............................................................................................................................................. 3
Library Functions ...................................................................................................................................... 3
int isalnum(int c) ........................................................................................................................................ 4
int isalpha(int c).......................................................................................................................................... 6
int iscntrl(int c) ........................................................................................................................................... 8
int isdigit(int c) ........................................................................................................................................... 9
int isgraph(int c) ....................................................................................................................................... 11
int islower(int c) ....................................................................................................................................... 12
int isprint(int c) ......................................................................................................................................... 14
int ispunct(int c) ....................................................................................................................................... 16
int isspace(int c) ....................................................................................................................................... 18
int isupper(int c) ....................................................................................................................................... 20
int isxdigit(int c) ........................................................................................................................................ 21
int tolower(int c) ...................................................................................................................................... 23
int toupper(int c) ...................................................................................................................................... 24
Character Classes .................................................................................................................................... 25

3. <ERRNO.H> ........................................................................................................................... 27
Introduction ............................................................................................................................................ 27
Library Macros ........................................................................................................................................ 27
extern int errno ........................................................................................................................................ 28
EDOM Domain Error ................................................................................................................................ 29
ERANGE Range Error ................................................................................................................................ 30

4. <FLOAT.H> ............................................................................................................................ 33
ii

Introduction ............................................................................................................................................ 33
Library Macros ........................................................................................................................................ 33

5. <LIMITS.H> ............................................................................................................................ 36
Introduction ............................................................................................................................................ 36
Library Macros ........................................................................................................................................ 36

6. <LOCALE.H> .......................................................................................................................... 39
Introduction ............................................................................................................................................ 39
Library Macros ........................................................................................................................................ 39
Library Functions .................................................................................................................................... 39
char *setlocale(int category, const char *locale) ..................................................................................... 40
struct lconv *localeconv(void) ................................................................................................................. 41
Library Structure ..................................................................................................................................... 44

7. <MATH.H>............................................................................................................................. 48
Introduction ............................................................................................................................................ 48
Library Macros ........................................................................................................................................ 48
Library Functions .................................................................................................................................... 48
double acos(double x) .............................................................................................................................. 50
double asin(double x) ............................................................................................................................... 51
double atan(double x) .............................................................................................................................. 52
double atan2(doubly y, double x) ............................................................................................................ 53
double cos(double x) ................................................................................................................................ 54
double cosh(double x) .............................................................................................................................. 56
double sin(double x) ................................................................................................................................ 57
double sinh(double x) .............................................................................................................................. 58
double tanh(double x) .............................................................................................................................. 59
double exp(double x) ............................................................................................................................... 59
double frexp(double x, int *exponent) .................................................................................................... 60
double ldexp(double x, int exponent) ...................................................................................................... 62
double log(double x) ................................................................................................................................ 63
double log10(double x) ............................................................................................................................ 63
double modf(double x, double *integer) ................................................................................................. 64
double pow(double x, double y) .............................................................................................................. 66
double sqrt(double x) ............................................................................................................................... 66
double ceil(double x) ................................................................................................................................ 67
double fabs(double x) .............................................................................................................................. 68
double floor(double x) ............................................................................................................................. 69
double fmod(double x, double y) ............................................................................................................. 71

iii

8. <SETJMP.H> .......................................................................................................................... 73
Introduction ............................................................................................................................................ 73
Library Variables ..................................................................................................................................... 73
Library Macros ........................................................................................................................................ 73
int setjmp(jmp_buf environment) ........................................................................................................... 73
Library Functions .................................................................................................................................... 75
void longjmp(jmp_buf environment, int value) ....................................................................................... 75

9. <SIGNAL.H> ........................................................................................................................... 77
Introduction ............................................................................................................................................ 77
Library Variables ..................................................................................................................................... 77
Library Macros ........................................................................................................................................ 77
Library Functions .................................................................................................................................... 78
void (*signal(int sig, void (*func)(int)))(int) ............................................................................................. 78
int raise(int sig)......................................................................................................................................... 81

10. <STDARG.H>........................................................................................................................ 84
Introduction ............................................................................................................................................ 84
Library Variables ..................................................................................................................................... 84
Library Macros ........................................................................................................................................ 84
void va_start(va_list ap, last_arg) ............................................................................................................ 85
type va_arg(va_list ap, type) .................................................................................................................... 86
void va_end(va_list ap) ............................................................................................................................ 88

11. <STDDEF.H> ........................................................................................................................ 90
Introduction ............................................................................................................................................ 90
Library Variables ..................................................................................................................................... 90
Library Macros ........................................................................................................................................ 90
NULL ......................................................................................................................................................... 91
offsetof(type, member-designator) ......................................................................................................... 92

12. <STDIO.H> ........................................................................................................................... 95
Introduction ............................................................................................................................................ 95
Library Variables ..................................................................................................................................... 95

iv

................................................................................................................................................................................................................ int whence) .................... size_t size) ............................................................................................................................................................................................. 125 void setbuf(FILE *stream......................................................... .................................................................................... const char *format........................ const char *format...........) .............................................. 179 13..........) ....................................... ......... 173 int putchar(int char) ............................................. ....... 95 Library Functions .... 177 void perror(const char *str) ........ 170 int getchar(void) ...........................) ............................................... 181 Library Macros .............................. 129 char *tmpnam(char *str) ............................................................................................................................................. FILE *stream) ......................................... FILE *stream) .............................................. 123 void rewind(FILE *stream) .... 101 void clearerr(FILE *stream) .......................... 140 int vfprintf(FILE *stream....................................... 103 int ferror(FILE *stream) ........ char *buffer... 172 int putc(int char.................................................................................. ......................................... long int offset................ const fpos_t *pos) .......Library Macros .............................................................) .. 109 size_t fread(void *ptr............................................................................................................................................................................................................................... 158 int sscanf(const char *str.......................................................................... va_list arg) ....... 113 int fseek(FILE *stream.......... 107 FILE *fopen(const char *filename.......................................... 175 int puts(const char *str) ..................... 115 int fsetpos(FILE *stream................................................................................................................................................... fpos_t *pos) ............................. const char *format................... 104 int fflush(FILE *stream) ............................................................................................. const char *format............................... 120 int remove(const char *filename) ...... size_t size................................................. const char *new_filename) ............................................... 164 char *fgets(char *str............................. size_t size.......................................................................... const char *mode............................................................................ ........................................................................... size_t nmemb....................................................................................................................................... 111 FILE *freopen(const char *filename................................................................................................................... const char *format.. 171 char *gets(char *str) ............... FILE *stream) .......................................................) ..................... 148 int vsprintf(char *str....................... char *buffer) ........................................................................... 168 int getc(FILE *stream) ..................... 156 int scanf(const char *format........................................................................................................ va_list arg) ......................................... 181 Library Variables .......................................................................................................................................................................... 102 int feof(FILE *stream) ............................................ 126 int setvbuf(FILE *stream.. 181 Introduction .............. size_t nmemb......... FILE *stream) ...............) ................................................................ int mode...................... va_list arg) .................................... FILE *stream) ......................... 130 int fprintf(FILE *stream................ FILE *stream) ............................................................................................................................................................ ................ 96 int fclose(FILE *stream) ....H>............................. 117 long int ftell(FILE *stream) .............................................................................................................................................................. 152 int fscanf(FILE *stream......... 136 int sprintf(char *str............................................................. 167 int fputs(const char *str....................... <STDLIB............................................ const char *mode) .................................................................................................................................................. const char *format..................... FILE *stream) ................................................................................ 122 int rename(const char *old_filename.......... 176 int ungetc(int char................. 165 int fputc(int char.................................................................... 119 size_t fwrite(const void *ptr............................................................................................................................................................................................................................................................................. 131 int printf(const char *format..... FILE *stream) ................. 181 v ........................................................................................................................................ int n............. 161 int fgetc(FILE *stream) ........................................................... 144 int vprintf(const char *format...................................................... 127 FILE *tmpfile(void) .................................. 106 int fgetpos(FILE *stream.......................................

............ size_t n) .......................................................................................................................................... size_t size............................................................................................. const void*)) ........................ 221 Library Functions ........................... size_t nitems............................................... 218 int wctomb(char *str................................................................................................................... 228 char *strcat(char *dest........................................................................... size_t nitems.................. size_t size) .................................... const void *src......................... 203 void qsort(void *base............ 221 Library Macros ............................................................................................ const char *str2) .... 210 int rand(void) ............................ 221 Library Variables ................................................................ char **endptr............................................................................. 194 void *realloc(void *ptr............ 234 int strcoll(const char *str1........ size_t n) ....................... 211 void srand(unsigned int seed) ........... 224 int memcmp(const void *str1....................................... 216 size_t wcstombs(char *str............................................................................................................................................................... const char *src) .............................................................................. const char *src................................ const char *str2) ............................................................................................................................................. 197 int atexit(void (*func)(void)) .............. const wchar_t *pwcs................ int (*compar)(const void *..................... 221 void *memchr(const void *str.............................................................................. const void *base...................... size_t n) .......... 191 void *calloc(size_t nitems....................... const void *)) ..................................... 193 void *malloc(size_t size) ... 192 void free(void *ptr) ............................................................................................. 199 char *getenv(const char *name) .............................................................................................. size_t n) .......... wchar_t wchar).......................................................................................... size_t n) .. 237 char *strncpy(char *dest...................................... 186 long int atol(const char *str) ......................................................... 200 int system(const char *string) ........................................................................................................................................... const void *str2....................................................................................................................... 225 void *memmove(void *dest................................... char **endptr................................................................. long int denom) .. const char *src.. 233 int strncmp(const char *str1.................... 185 int atoi(const char *str) ....... 207 div_t div(int numer................................. int c...... size_t n) ................ size_t n)............ size_t size..............................................................Library Functions ........ 196 void abort(void)............................................... 231 char *strchr(const char *str................... 208 long int labs(long int x) ........ const char *str..................... int (*compar)(const void *.................................................................. 205 int abs(int x) ........................................................................................ size_t n) ................................................... const char *src) ...........................................................H>......... 238 vi .................. <STRING............................................................................................. 201 void *bsearch(const void *key....................................................................................................................................................................................................................................... size_t size) ............................................................... 236 char *strcpy(char *dest.................................. 209 ldiv_t ldiv(long int numer........................... const char *str2.......................... size_t n) ........................................................................................ 232 int strcmp(const char *str1........... const char *str.............. 188 long int strtol(const char *str..................... int denom) .......... 221 Introduction ........................................................................................................... 187 double strtod(const char *str...................................................................................................................................................................... 219 14.................................................................................................................................................................................................... 212 int mblen(const char *str........................................................................................................................................................... int c............................................................................................................................................................ int base) ........... 213 size_t mbstowcs(schar_t *pwcs........... char **endptr) ............................ 182 double atof(const char *str)....................................... 198 void exit(int status) ....... int base) ..................................................................................................... size_t n) .................................................... 227 void *memset(void *str. int c) ............. 215 int mbtowc(whcar_t *pwc............................................... 229 char *strncat(char *dest................................................. 189 unsigned long int strtoul(const char *str....... size_t n) ....................................................................

...............................................................size_t strcspn(const char *str1................................................................................................ 244 size_t strspn(const char *str1.................................................................................... 245 char *strstr(const char *haystack........................................................................................................................................................ 251 Library Functions ........................................................... 243 char *strrchr(const char *str.................... const char *str2) ............................... 241 size_t strlen(const char *str) .......................................................................................................................................... const char *delim) ............ const char *str2) ........................................................................................................................................................................................................................................... 246 char *strtok(char *str. const char *format........................................................... 265 vii ............. 257 struct tm *localtime(const time_t *timer)................................... 254 char *ctime(const time_t *timer) ............................................................................................................................. 255 double difftime(time_t time1......................... time_t time2) ........................................................................ const char *needle).............................................................................................................................................................. int c) ........................................................ <TIME................ const char *str2) ........................................................................... size_t n) ............................................................ 252 clock_t clock(void) ....................................... 259 time_t mktime(struct tm *timeptr) .................. 250 Library Macros ................H> ...................................................................... const struct tm *timeptr) ............................. 251 char *asctime(const struct tm *timeptr) .............................................. 250 Introduction ...... 250 Library Variables ......... const char *src.......................................................................................................... 247 size_t strxfrm(char *dest.......... 242 char *strpbrk(const char *str1............................................................................................................................................................ 248 15.................... size_t maxsize......... 256 struct tm *gmtime(const time_t *timer) ....... 240 char *strerror(int errnum) ............................................................................................................... 262 time_t time(time_t *timer) .................................................................................... 260 size_t strftime(char *str......................

Function & Description 1 void assert(int expression) This is actually a macro and not a function.This can be a variable or any C expression. assert() displays an error message on 1 . In other words. which can be used to add diagnostics in your C program. If expression evaluates to FALSE. void assert(int expression) Description The C library macro void assert(int expression) allows diagnostic information to be written to the standard error file.N.h header file of the C Standard Library provides a macro called assert which can be used to verify assumptions made by the program and print a diagnostic message if this assumption is false. the assert macro is defined as follows: #define assert(ignore) ((void)0) Library Macros Following is the only function defined in the header assert.h: S. If NDEBUG is defined as a macro name in the source file.h> is included. it can be used to add diagnostics in your C program.1. Parameters  expression -. If expression evaluates to TRUE. Declaration Following is the declaration for assert() Macro. <ASSERT. void assert(int expression). at the point where <assert.H> C Standard Library Introduction The assert. The defined macro assert refers to another macro NDEBUG which is not a part of <assert.h>. assert() does nothing.

return(0). str). Example The following example shows the usage of assert() macro: #include <assert. a). assert(str != NULL). } Let us compile and run the above program in the interactive mode as shown below: Enter an integer value: 11 Integer entered is 11 Enter string: tutorialspoint String entered is: tutorialspoint 2 . printf("Integer entered is %d\n".h> int main() { int a. Return Value This macro does not return any value. assert(a >= 10).h> #include <stdio.C Standard Library stderr (standard error stream to display error messages and diagnostics) and aborts program execution. char str[50]. printf("String entered is: %s\n". &str). &a). scanf("%s\n". scanf("%d\n". printf("Enter an integer value: "). printf("Enter string: ").

2 int isalpha(int c) This function checks whether the passed character is alphabetic.h: S.h header file of the C Standard Library declares several functions that are useful for testing and mapping characters. Function & Description 1 int isalnum(int c) This function checks whether the passed character is alphanumeric. All the functions return non-zero (true) if the argument c satisfies the condition described. 5 int isgraph(int c) This function checks whether the passed character has graphical representation using locale. and zero (false) if not. Library Functions Following are the functions defined in the header ctype. 4 int isdigit(int c) This function checks whether the passed character is decimal digit.H> C Standard Library Introduction The ctype. 3 int iscntrl(int c) This function checks whether the passed character is control character. whose value must be EOF or representable as an unsigned char. 3 . <CTYPE.N.2. 6 int islower(int c) This function checks whether the passed character is lowercase letter. All the functions accepts int as a parameter.

#include <stdio.h> #include <ctype. 11 int isxdigit(int c) This function checks whether the passed character is a hexadecimal digit.C Standard Library 7 int isprint(int c) This function checks whether the passed character is printable. 9 int isspace(int c) This function checks whether the passed character is white-space. int isalnum(int c). Declaration Following is the declaration for isalnum() function.This is the character to be checked. 10 int isupper(int c) This function checks whether the passed character is an uppercase letter. Return Value This function returns non-zero value if c is a digit or a letter. 8 int ispunct(int c) This function checks whether the passed character is a punctuation character. else it returns 0. int isalnum(int c) Description The C library function void isalnum(int c) checks if the passed character is alphanumeric. Parameters  c -. Example The following example shows the usage of isalnum() function.h> 4 .

if( isalnum(var1) ) { printf("var1 = |%c| is alphanumeric\n". var2 ). var4 ). } else { printf("var1 = |%c| is not alphanumeric\n".C Standard Library int main() { int var1 = 'd'. } else { printf("var2 = |%c| is not alphanumeric\n". int var3 = '\t'. int var2 = '2'. var2 ). } if( isalnum(var2) ) { printf("var2 = |%c| is alphanumeric\n". var3 ). var3 ). } if( isalnum(var4) ) { printf("var4 = |%c| is alphanumeric\n". int var4 = ' '. var1 ). } else { printf("var3 = |%c| is not alphanumeric\n". var1 ). } 5 . } if( isalnum(var3) ) { printf("var3 = |%c| is alphanumeric\n".

var4 ). int isalpha(int c). Example The following example shows the usage of isalpha() function. } return(0). } Let us compile and run the above program to produce the following result: var1 = |d| is alphanumeric var2 = |2| is alphanumeric var3 = | | is not alphanumeric var4 = | | is not alphanumeric int isalpha(int c) Description The C library function void isalpha(int c) checks if the passed character is alphabetic.This is the character to be checked. else it returns 0.h> #include <ctype.h> int main() { int var1 = 'd'. Return Value This function returns non-zero value if c is an alphabet. Parameters  c -. #include <stdio. Declaration Following is the declaration for isalpha() function. 6 .C Standard Library else { printf("var4 = |%c| is not alphanumeric\n".

var1 ). var1 ). } else { printf("var4 = |%c| is not an alphabet\n". int var3 = '\t'. } else { printf("var2 = |%c| is not an alphabet\n". var3 ). } else { printf("var3 = |%c| is not an alphabet\n". var2 ). } if( isalpha(var3) ) { printf("var3 = |%c| is an alphabet\n". int var4 = ' '. var4 ). } if( isalpha(var4) ) { printf("var4 = |%c| is an alphabet\n". var2 ). if( isalpha(var1) ) { printf("var1 = |%c| is an alphabet\n". var3 ). var4 ). 7 . } else { printf("var1 = |%c| is not an alphabet\n". } if( isalpha(var2) ) { printf("var2 = |%c| is an alphabet\n".C Standard Library int var2 = '2'.

} Let us compile and run the above program to produce the following result: var1 = |d| is an alphabet var2 = |2| is not an alphabet var3 = | | is not an alphabet var4 = | | is not an alphabet int iscntrl(int c) Description The C library function void iscntrl(int c) checks if the passed character is a control character. control characters are between ASCII codes 0x00 (NUL). Return Value This function returns non-zero value if c is a control character.This is the character to be checked. else it returns 0. Parameters  c -. 0x1f (US). Declaration Following is the declaration for iscntrl() function.h> int main () { int i = 0. and 0x7f (DEL).h> #include <ctype. 8 . Specific compiler implementations for certain platforms may define additional control characters in the extended character set (above 0x7f). According to standard ASCII character set. int iscntrl(int c).C Standard Library } return(0). j = 0. #include <stdio. Example The following example shows the usage of iscntrl() function.

C Standard Library char str1[] = "all \a about \t programming".This is the character to be checked. Decimal digits are (numbers): 0 1 2 3 4 5 6 7 8 9. Parameters  c -. j++. } Let us compile and run the above program to produce the following result: all tutorials int isdigit(int c) Description The C library function void isdigit(int c) checks if the passed character is a decimal digit character. Declaration Following is the declaration for isdigit() function. char str2[] = "tutorials \n point". } /* Prints string till control character \n */ while( !iscntrl(str2[j]) ) { putchar(str2[j]). } return(0). /* Prints string till control character \a */ while( !iscntrl(str1[i]) ) { putchar(str1[i]). 9 . i++. int isdigit(int c).

} else { printf("var2 = |%c| is not a digit\n". else it returns 0. if( isdigit(var1) ) { printf("var1 = |%c| is a digit\n". var2 ). var1 ). } else { printf("var1 = |%c| is not a digit\n". } Let us compile and run the above program to produce the following result: var1 = |h| is not a digit 10 . int var2 = '2'. #include <stdio.C Standard Library Return Value This function returns non-zero value if c is a digit. Example The following example shows the usage of isdigit() function.h> int main() { int var1 = 'h'. var1 ). } if( isdigit(var2) ) { printf("var2 = |%c| is a digit\n". } return(0). var2 ).h> #include <ctype.

Declaration Following is the declaration for isgraph() function.h> #include <ctype. } else { 11 . else it returns 0. int var2 = 'm'. which is not considered as isgraph characters. Return Value This function returns non-zero value if c has a graphical representation as character.C Standard Library var2 = |2| is a digit int isgraph(int c) Description The C library function void isgraph(int c) checks if the character has graphical representation. The characters with graphical representations are all those characters that can be printed except for whitespace characters (like ' ').h> int main() { int var1 = '3'. if( isgraph(var1) ) { printf("var1 = |%c| can be printed\n". int isgraph(int c). #include <stdio. int var3 = ' '.This is the character to be checked. var1 ). Example The following example shows the usage of isgraph() function. Parameters  c -.

var1 ). } Let us compile and run the above program to produce the following result: var1 = |3| can be printed var2 = |m| can be printed var3 = | | can't be printed int islower(int c) Description The C library function int islower(int c) checks whether the passed character is a lowercase letter.C Standard Library printf("var1 = |%c| can't be printed\n". int islower(int c). } return(0). Declaration Following is the declaration for islower() function. } else { printf("var2 = |%c| can't be printed\n". } else { printf("var3 = |%c| can't be printed\n". var2 ). } if( isgraph(var2) ) { printf("var2 = |%c| can be printed\n". var2 ). } if( isgraph(var3) ) { printf("var3 = |%c| can be printed\n". 12 . var3 ). var3 ).

var2 ). Return Value This function returns a non-zero value(true) if c is a lowercase alphabetic letter else.This is the character to be checked. var1 ). } else { printf("var1 = |%c| is not lowercase character\n".h> #include <ctype. int var3 = '3'.h> int main() { int var1 = 'Q'. } if( islower(var3) ) { 13 . if( islower(var1) ) { printf("var1 = |%c| is lowercase character\n". var2 ).C Standard Library Parameters  c -. } else { printf("var2 = |%c| is not lowercase character\n". #include <stdio. zero (false). var1 ). int var2 = 'q'. } if( islower(var2) ) { printf("var2 = |%c| is lowercase character\n". Example The following example shows the usage of islower() function.

A printable character is a character that is not a control character. Parameters  c -. #include <stdio. zero (false).C Standard Library printf("var3 = |%c| is lowercase character\n". int isprint(int c). var3 ). } else { printf("var3 = |%c| is not lowercase character\n". Declaration Following is the declaration for isprint() function.h> #include <ctype. } Let us compile and run the above program to produce the following result: var1 = |Q| is not lowercase character var2 = |q| is lowercase character var3 = |3| is not lowercase character int isprint(int c) Description The C library function int isprint(int c) checks whether the passed character is printable. } return(0).This is the character to be checked. Return Value This function returns a non-zero value(true) if c is a printable character else. Example The following example shows the usage of isprint() function. var3 ).h> int main() 14 .

} if( isprint(var3) ) { printf("var3 = |%c| can be printed\n". } else { printf("var3 = |%c| can't be printed\n". } else { printf("var2 = |%c| can't be printed\n". } if( isprint(var4) ) { printf("var4 = |%c| can be printed\n". int var2 = '8'. int var4 = ' '. var2 ). var1 ). int var3 = '\t'. var2 ). } if( isprint(var2) ) { printf("var2 = |%c| can be printed\n". var4 ). } else 15 . var3 ).C Standard Library { int var1 = 'k'. var3 ). } else { printf("var1 = |%c| can't be printed\n". var1 ). if( isprint(var1) ) { printf("var1 = |%c| can be printed\n".

} Let us compile and run the above program to produce the following result: var1 = |k| can be printed var2 = |8| can be printed var3 = | | can't be printed var4 = | | can be printed int ispunct(int c) Description The C library function int ispunct(int c) checks whether the passed character is a punctuation character.This is the character to be checked. 16 .h> int main() { int var1 = 't'.C Standard Library { printf("var4 = |%c| can't be printed\n". zero (false). #include <stdio. A punctuation character is any graphic character (as in isgraph) that is not alphanumeric (as in isalnum). Return Value This function returns a non-zero value(true) if c is a punctuation character else. Example The following example shows the usage of ispunct() function. Parameters  c -. } return(0).h> #include <ctype. int ispunct(int c). Declaration Following is the declaration for ispunct() function. var4 ).

} if( ispunct(var3) ) { printf("var3 = |%c| is a punctuation character\n". } else { printf("var3 = |%c| is not a punctuation character\n". } else { printf("var1 = |%c| is not a punctuation character\n". var3 ). int var4 = ' '. var1 ). } if( ispunct(var4) ) { printf("var4 = |%c| is a punctuation character\n".C Standard Library int var2 = '1'. } else { printf("var2 = |%c| is not a punctuation character\n". var2 ). int var3 = '/'. var4 ). } if( ispunct(var2) ) { printf("var2 = |%c| is a punctuation character\n". } else { printf("var4 = |%c| is not a punctuation character\n". var2 ). 17 . var4 ). var1 ). var3 ). if( ispunct(var1) ) { printf("var1 = |%c| is a punctuation character\n".

zero (false). Example The following example shows the usage of isspace() function.This is the character to be checked. Standard white-space characters are: ' ' (0x20) space (SPC) '\t' (0x09) horizontal tab (TAB) '\n' (0x0a) newline (LF) '\v' (0x0b) vertical tab (VT) '\f' (0x0c) feed (FF) '\r' (0x0d) carriage return (CR) Declaration Following is the declaration for isspace() function.C Standard Library } return(0). } Let us compile and run the above program that will produce the following result: var1 = |t| is not a punctuation character var2 = |1| is not a punctuation character var3 = |/| is a punctuation character var4 = | | is not a punctuation character int isspace(int c) Description The C library function int isspace(int c) checks whether the passed character is white-space. Return Value This function returns a non-zero value(true) if c is a white-space character else. Parameters  c -. int isspace(int c). #include <stdio.h> 18 .

} return(0). } else { printf("var1 = |%c| is not a white-space character\n". var2 ). var1 ).C Standard Library #include <ctype. int var3 = ' '. } if( isspace(var2) ) { printf("var2 = |%c| is a white-space character\n".h> int main() { int var1 = 't'. } else { printf("var2 = |%c| is not a white-space character\n". int var2 = '1'. var1 ). if( isspace(var1) ) { printf("var1 = |%c| is a white-space character\n". var2 ). 19 . } if( isspace(var3) ) { printf("var3 = |%c| is a white-space character\n". var3 ). var3 ). } else { printf("var3 = |%c| is not a white-space character\n".

var1 ). Declaration Following is the declaration for isupper() function.This is the character to be checked. Parameters  c -. int var2 = 'm'. Example The following example shows the usage of isupper() function. #include <stdio. int isupper(int c). int var3 = '3'.C Standard Library } Let us compile and run the above program that will produce the following result: var1 = |t| is not a white-space character var2 = |1| is not a white-space character var3 = | | is a white-space character int isupper(int c) Description The C library function int isupper(int c) checks whether the passed character is uppercase letter. zero (false).h> int main() { int var1 = 'M'. if( isupper(var1) ) { printf("var1 = |%c| is uppercase character\n". 20 .h> #include <ctype. Return Value This function returns a non-zero value(true) if c is an uppercase alphabetic letter else.

} Let us compile and run the above program that will produce the following result: var1 = |M| is uppercase character var2 = |m| is not uppercase character var3 = |3| is not uppercase character int isxdigit(int c) Description The C library function int isxdigit(int c) checks whether the passed character is a hexadecimal digit. } if( isupper(var3) ) { printf("var3 = |%c| is uppercase character\n".C Standard Library } else { printf("var1 = |%c| is not uppercase character\n". 21 . } else { printf("var3 = |%c| is not uppercase character\n". var3 ). var1 ). var3 ). } else { printf("var2 = |%c| is not uppercase character\n". var2 ). } return(0). var2 ). } if( isupper(var2) ) { printf("var2 = |%c| is uppercase character\n".

if( isxdigit(var1[0]) ) { printf("var1 = |%s| is hexadecimal character\n". var2 ).C Standard Library Declaration Following is the declaration for isxdigit() function. 22 . var1 ). char var2[] = "0xE". Example The following example shows the usage of isxdigit() function. #include <stdio.h> int main() { char var1[] = "tuts". } else { printf("var1 = |%s| is not hexadecimal character\n". int isxdigit(int c). zero (false).This is the character to be checked. Return Value This function returns a non-zero value(true) if c is a hexadecimal digit else. } if( isxdigit(var2[0] )) { printf("var2 = |%s| is hexadecimal character\n". var2 ). Parameters  c -. } else { printf("var2 = |%s| is not hexadecimal character\n". var1 ).h> #include <ctype.

Return Value This function returns lowercase equivalent to c. 2 int toupper(int c) This function converts lowercase letters to uppercase.This is the letter to be converted to lowercase. } Let us compile and run the above program to produce the following result: var1 = |tuts| is not hexadecimal character var2 = |0xE| is hexadecimal character The library also contains two conversion functions that accepts and returns an "int". Example The following example shows the usage of tolower() function. int tolower(int c) Description The C library function int tolower(int c) converts a given letter to lowercase.C Standard Library } return(0).h> 23 . #include <stdio.N. else c remains unchanged. Parameters  c -. Declaration Following is the declaration for tolower() function. if such value exists. The value is returned as an int value that can be implicitly casted to char. int tolower(int c). Function & Description 1 int tolower(int c) This function converts uppercase letters to lowercase. S.

char str[] = "TUTORIALS POINT".C Standard Library #include <ctype.This is the letter to be converted to uppercase. while( str[i] ) { putchar(tolower(str[i])). else c remains unchanged. Return Value This function returns uppercase equivalent to c. function int toupper(int c) converts lowercase letter to Declaration Following is the declaration for toupper() function. Example 24 . The value is returned as an int value that can be implicitly casted to char. i++. } return(0). } Let us compile and run the above program to produce the following result: tutorials point int toupper(int c) Description The C library uppercase. if such value exists.h> int main() { int i = 0. Parameters  c -. int toupper(int c). char c.

25 . while(str[i]) { putchar (toupper(str[i])). #include <stdio. 5.N. 9 }. 8. 3. 3 Lowercase letters This is a set of lowercase letters { a b c d e f g h i j k l m n o p q r s t u v w x y z }.h> #include <ctype. 1. i++. 4. char c.h> int main() { int i = 0. } return(0). } Let us compile and run the above program to produce the following result: TUTORIALS POINT Character Classes S. 2.C Standard Library The following example shows the usage of toupper() function. 6. Character Class & Description 1 Digits This is a set of whole numbers { 0. 2 Hexadecimal digits This is the set of .{ 0 1 2 3 4 5 6 7 8 9 A B C D E F a b c d e f }. char str[] = "Tutorials Point". 7.

10 Printable characters This is a set of Alphanumeric characters. carriage return. 6 Alphanumeric characters This is a set of Digits. 13 Alphabetic characters This is a set of Lowercase letters and Uppercase letters. < = > ? @ [ \ ] ^ _ ` { | } ~ 8 Graphical characters This is a set of Alphanumeric characters and Punctuation characters. 26 . Punctuation characters and Space characters. 5 Letters This is a set of lowercase and uppercase letters.. 12 Blank characters These are spaces and tabs. vertical tab. / : . these characters have octal codes 000 through 037. 7 Punctuation characters This is a set of ! " # $ % & ' ( ) * + .C Standard Library 4 Uppercase letters This is a set of uppercase letters {A B C D E F G H I J K L M N O P Q R S T U V W X Y Z }. newline. 11 Control characters In ASCII. and space. . Lowercase letters and Uppercase letters. and 177 (DEL). form feed. 9 Space characters This is a set of tab.

N. therefore it can be both read and modified by a program. Macro & Description 1 extern int errno This is the macro set by system calls and some library functions in the event of an error to indicate what went wrong.h header file of the C Standard Library defines the integer variable errno. The errno is set to zero at program startup.h: S. over which the mathematical function is defined and errno is set to EDOM. which will expand to integer constant expressions with type int. over which the mathematical function is defined and errno is set to ERANGE.3. 3 ERANGE Range Error This macro represents a range error. which occurs if an input argument is outside the domain.H> C Standard Library Introduction The errno. This macro expands to a modifiable lvalue of type int. Certain functions of the standard C library modify its value to other than zero to signal some types of error. Library Macros Following are the macros defined in the header errno.h header file also defines a list of macros indicating different error codes. which is set by system calls and some library functions in the event of an error to indicate what went wrong. You can also modify its value or reset to zero at your convenience. <ERRNO. which occurs if an input argument is outside the range. 2 EDOM Domain Error This macro represents a domain error. The errno. 27 .

#include <stdio. Declaration Following is the declaration for errno macro. if( fp == NULL ) { fprintf(stderr. int main () { FILE *fp. } 28 . strerror(errno)). errno).txt". extern int errno Parameters  NA Return Value  NA Example The following example shows the usage of errno Macro. "Error opening file: %s\n". "Value of errno: %d\n".h> #include <errno. fprintf(stderr.h> #include <string.h> extern int errno . fp = fopen("file. } else { fclose(fp). "r").C Standard Library extern int errno Description The C library macro extern int errno is set by system calls and some library functions in the event of an error to indicate if anything went wrong.

val = sqrt(-10). } Let us compile and run the above program that will produce the following result in case file file. errno = 0. the C library macro EDOM represents a domain error. which occurs if an input argument is outside the domain.h> #include <errno.C Standard Library return(0).h> #include <math. #include <stdio.txt does not exist: Value of errno: 2 Error opening file: No such file or directory EDOM Domain Error Description As mentioned above.h> int main() { double val. over which the mathematical function is defined and errno is set to EDOM. #define EDOM some_value Parameters  NA Return Value  NA Example The following example shows the usage of EDOM Macro. if(errno == EDOM) 29 . Declaration Following is the declaration for EDOM Macro.

C Standard Library { printf("Invalid value \n"). Declaration Following is the declaration for ERANGE Macro. val = sqrt(10). #define ERANGE some_value 30 . } else { printf("Valid value\n"). } else { printf("Valid value\n"). } errno = 0. } return(0). if(errno == EDOM) { printf("Invalid value\n"). over which the mathematical function is defined and errno is set to ERANGE. which occurs if an input argument is outside the range. the C library macro ERANGE represents a range error. } Let us compile and run the above program that will produce the following result: Invalid value Valid value ERANGE Range Error Description As mentioned above.

if( errno == ERANGE ) { printf("Log(%f) is out of range\n". } x = 0.C Standard Library Parameters  NA Return Value  NA Example The following example shows the usage of ERANGE Macro.000000.h> #include <math. double value. } else { printf("Log(%f) = %f\n". value). value = log(x). #include <stdio. value = log(x).h> #include <errno. } else { 31 . x.000000. if( errno == ERANGE ) { printf("Log(%f) is out of range\n" x). x). x = 1.h> int main() { double x.

value).C Standard Library printf("Log(%f) = %f\n". } return 0.000000) = 1.609438 Log(0. x.000000) is out of range 32 . } Let us compile and run the above program that will produce the following result: Log(1.

Note that in all instances FLT refers to type float.. a floating point will have its value as follows: floating-point = ( S ) p x be or floating-point = (+/-) precision x baseexponent Library Macros The following values are implementation-specific and defined with the #define directive. 2 for binary. These constants are proposed by ANSI C. 16 for hexadecimal. <FLOAT. DBL refers to double.h header file of the C Standard Library contains a set of various platform-dependent constants related to floating point values. the number of base-b digits in the significand integer between a minimum emin and a Based on the above 4 components. e exponent. and LDBL refers to long double. Macro Description 33 .) b base or radix of the exponent representation. and so on. 10 for decimal.H> C Standard Library Introduction The float. They allow making more portable programs..4. p precision. it is good to understand that floating-point number is composed of following four elements: Component Component Description S sign ( +/. but these values may not be any lower than what is given here. an maximum emax. Before checking all the constants.

LDBL_DIG 10 FLT_MIN_EXP DBL_MIN_EXP These macros define the minimum negative integer value for an exponent in base FLT_RADIX.towards zero 1 .towards positive infinity 3 . A base-2 is binary. base-10 is the normal decimal representation. LDBL_MAX_EXP FLT_MAX_10_EXP +37 DBL_MAX_10_EXP +37 These macros define the maximum integer value for an exponent in base 10. FLT_MANT_DIG These macros define the number of digits in the number (in the FLT_RADIX base).to nearest 2 . 34 .towards negative infinity FLT_RADIX 2 This defines the base radix representation of the exponent.C Standard Library FLT_ROUNDS Defines the rounding mode for floating point addition and it can have any of the following values: -1 . base-16 is Hex. LDBL_MIN_EXP FLT_MIN_10_EXP -37 DBL_MIN_10_EXP -37 These macros define the minimum negative integer value for an exponent in base 10. DBL_MANT_DIG LDBL_MANT_DIG FLT_DIG 6 DBL_DIG 10 These macros define the maximum number decimal digits (base-10) that can be represented without change after rounding. LDBL_MIN_10_EXP -37 FLT_MAX_EXP DBL_MAX_EXP These macros define the maximum integer value for an exponent in base FLT_RADIX.indeterminable 0 .

printf("The number of digits in the number = %.C Standard Library LDBL_MAX_10_EXP +37 FLT_MAX 1E+37 DBL_MAX 1E+37 These macros define the maximum finite floatingpoint value. FLT_MAX).10e\n".2996655210e-312 35 . #include <stdio. FLT_MIN). LDBL_MIN 1E-37 Example The following example shows the usage of few of the constants defined in float.10e\n". printf("The minimum value of float = %.1754943508e-38 The number of digits in the number = 7.h file.10e\n".4028234664e+38 The minimum value of float = 1. LDBL_MAX 1E+37 FLT_EPSILON 1E-5 DBL_EPSILON 1E-9 These macros define the least significant digit representable.h> int main() { printf("The maximum value of float = %. LDBL_EPSILON 1E-9 FLT_MIN 1E-37 DBL_MIN 1E-37 These macros define the minimum floating-point values. } Let us compile and run the above program that will produce the following result: The maximum value of float = 3. FLT_MANT_DIG).h> #include <float.

for example an unsigned character can store up to a maximum value of 255. CHAR_MAX 127 Defines the value for type char and its value will be equal to SCHAR_MAX if char represents negative values. The macros defined in this header. CHAR_MIN 0 Defines the minimum value for type char and its value will be equal to SCHAR_MIN if char represents negative values. int and long. SCHAR_MAX 127 Defines the maximum value for a signed char. otherwise zero. Macro Value Description CHAR_BIT 8 Defines the number of bits in a byte.H> C Standard Library Introduction The limits. otherwise UCHAR_MAX. These limits specify that a variable cannot store any value beyond these limits. UCHAR_MAX 255 Defines the maximum value for an unsigned char. MB_LEN_MAX 1 Defines the maximum number of 36 . <LIMITS. SCHAR_MIN -128 Defines the minimum value for a signed char.h header determines various properties of the various variable types. Library Macros The following values are implementation-specific and defined with the #define directive. but these values may not be any lower than what is given here.5. limits the values of various variable types like char.

C Standard Library bytes in a multi-byte character.h file. USHRT_MAX 65535 Defines the maximum value for an unsigned short int. INT_MIN -32768 Defines the minimum value for an int. SHRT_MIN -32768 Defines the minimum value for a short int. SHRT_MAX +32767 Defines the maximum value for a short int. INT_MAX +32767 Defines the maximum value for an int. LONG_MIN -2147483648 Defines the minimum value for a long int. Example The following example shows the usage of few of the constants defined in limit. printf("The minimum value of SIGNED CHAR = %d\n".h> #include <limits. #include <stdio.h> int main() { printf("The number of bits in a byte %d\n". UINT_MAX 65535 Defines the maximum value for an unsigned int. LONG_MAX +2147483647 Defines the maximum value for a long int. ULONG_MAX 4294967295 Defines the maximum value for an unsigned long int. SCHAR_MIN). 37 . CHAR_BIT).

UCHAR_MAX). INT_MIN). printf("The minimum value of INT = %d\n". SHRT_MIN). printf("The maximum value of SHORT INT = %d\n".C Standard Library printf("The maximum value of SIGNED CHAR = %d\n". INT_MAX). } Let us compile and run the above program that will produce the following result: The number of bits in a byte 8 The minimum value of SIGNED CHAR = -128 The maximum value of SIGNED CHAR = 127 The maximum value of UNSIGNED CHAR = 255 The minimum value of SHORT INT = -32768 The maximum value of SHORT INT = 32767 The minimum value of INT = -32768 The maximum value of INT = 32767 The minimum value of CHAR = -128 The maximum value of CHAR = 127 The minimum value of LONG = -2147483648 The maximum value of LONG = 2147483647 38 . printf("The maximum value of LONG = %ld\n". return(0). LONG_MAX). SHRT_MAX). CHAR_MAX). SCHAR_MAX). printf("The minimum value of LONG = %ld\n". LONG_MIN). printf("The minimum value of CHAR = %d\n". printf("The maximum value of UNSIGNED CHAR = %d\n". printf("The maximum value of CHAR = %d\n". CHAR_MIN). printf("The minimum value of SHORT INT = %d\n". printf("The maximum value of INT = %d\n".

4 LC_MONETARY Affects the monetary information provided by localeconv function. 3 LC_CTYPE Affects all character functions.h: 39 .H> C Standard Library Introduction The locale. Library Macros Following are the macros defined in the header and these macros will be used in two functions listed below: S. 2 LC_COLLATE Affects strcoll and strxfrm functions. Macro & Description 1 LC_ALL Sets everything. Library Functions Following are the functions defined in the header locale.6. 6 LC_TIME Affects the strftime function. You will find several macros defined along with an important structure struct lconv and two important functions listed below. <LOCALE.h header defines the location specific settings.N. such as date formats and currency symbols. 5 LC_NUMERIC Affects decimal-point formatting and the information provided by localeconv function.

o LC_MESSAGES for system responses. char *setlocale(int category.If locale is NULL or the empty string "". o LC_TIME for date and time formatting with strftime(). See strcoll(). Function & Description 1 char *setlocale(int category.This is a named constant specifying the category of the functions affected by the locale setting. o LC_NUMERIC for decimal separator for localeconv(). const char *locale) Description The C library function char *setlocale(int category.C Standard Library S. const char *locale) Sets or reads location dependent information. For example: strtoupper(). o LC_ALL for all of the below. Example 40 . char *setlocale(int category.N. Declaration Following is the declaration for setlocale() function. The return value is NULL if the request cannot be honored. o LC_CTYPE for character classification and conversion. o LC_COLLATE for string comparison. const char *locale) sets or reads location dependent information. 2 struct lconv *localeconv(void) Sets or reads location dependent information. o LC_MONETARY for monetary formatting for localeconv(). locale -. the locale names will be set from the values of environment variables with the same names as the above categories. Return Value A successful call to setlocale() returns an opaque string that corresponds to the locale set. const char *locale) Parameters   category -.

h> int main () { time_t currtime. "en_GB")).C Standard Library The following example shows the usage of setlocale() function. printf("Locale is: %s\n".h> #include <stdio. setlocale(LC_ALL. char buffer[80]. buffer).80."%c". "de_DE")). } Let us compile and run the above program that will produce the following result: Locale is: en_GB Date is: Thu 23 Aug 2012 06:39:32 MST Locale is: de_DE Date is: Do 23 Aug 2012 06:39:32 MST struct lconv *localeconv(void) Description 41 . setlocale(LC_ALL. return(0). printf("Date is: %s\n". timer ). time( &currtime ). strftime(buffer.80. #include <locale."%c". printf("Date is: %s\n".h> #include <time. buffer). timer ). struct tm *timer. strftime(buffer. timer = localtime( &currtime ). printf("Locale is: %s\n".

char *int_curr_symbol. struct lconv *localeconv(void) Parameters  NA Return Value This function returns a pointer to a struct lconv for the current locale. char *positive_sign. char p_cs_precedes. 42 . char *mon_grouping. These are returned in an object of the lconv structure type. } lconv Example The following example shows the usage of localeconv() function. char int_frac_digits. char n_sep_by_space. char *negative_sign. char *grouping. char p_sep_by_space. which has the following structure: typedef struct { char *decimal_point. char *thousands_sep. Declaration Following is the declaration for localeconv() function. char *currency_symbol. char *mon_decimal_point. char *mon_thousands_sep. char p_sign_posn. char n_cs_precedes. char frac_digits. char n_sign_posn.C Standard Library The C library function struct lconv *localeconv(void) sets or reads location dependent information.

} Let us compile and run the above program that will produce the following result: Local Currency Symbol: EUR International Currency Symbol: EUR Local Currency Symbol: $ International Currency Symbol: USD Local Currency Symbol: £ International Currency Symbol: GBP 43 . printf ("International Currency Symbol: %s\n".lc->currency_symbol). setlocale(LC_MONETARY. printf("Decimal Point = %s\n". printf("Local Currency Symbol: %s\n".lc->currency_symbol).h> int main () { struct lconv * lc. setlocale(LC_MONETARY.lc->int_curr_symbol). "it_IT"). setlocale(LC_MONETARY.lc->currency_symbol). return 0. printf("International Currency Symbol: %s\n". lc = localeconv(). lc = localeconv().h> #include <stdio. lc = localeconv(). printf("Local Currency Symbol: %s\n".lc->int_curr_symbol).lc->int_curr_symbol). printf("International Currency Symbol: %s\n". printf ("Local Currency Symbol: %s\n". "en_US"). lc->decimal_point). "en_GB").C Standard Library #include <locale.

char *negative_sign. char p_sep_by_space.N. char n_sep_by_space. char *positive_sign. char *mon_decimal_point. char n_sign_posn. char *grouping. char *mon_grouping. Field & Description 1 decimal_point Decimal point character used for non-monetary values. char n_cs_precedes. char frac_digits. char p_cs_precedes. char *currency_symbol. } lconv Following is the description of each of the fields: S. char *int_curr_symbol. char int_frac_digits. char *mon_thousands_sep. 3 grouping 44 . char *thousands_sep.C Standard Library Decimal Point = . 2 thousands_sep Thousands place separator character used for non-monetary values. Library Structure typedef struct { char *decimal_point. char p_sign_posn.

8 mon_grouping A string whose elements defines the size of the grouping of digits in monetary values. The first three characters are those specified by ISO 4217:1987 and the fourth is the character. A value of 0 means that the previous value is to be used for the rest of the groups. 11 int_frac_digits Number of digits to show after the decimal point in international monetary values.C Standard Library A string that indicates the size of each group of digits in non-monetary quantities. 4 int_curr_symbol It is a string of the international currency symbols used. 9 positive_sign The character used for positive monetary values. which separates the currency symbol from the monetary quantity. 7 mon_thousands_sep The thousands place grouping character used for monetary values. Each character represents an integer value. 5 currency_symbol The local symbol used for currency. which designates the number of digits in the current group. 10 negative_sign The character used for negative monetary values. 6 mon_decimal_point The decimal point character used for monetary values. Each character represents an integer value which designates the number of digits in the current group. 12 frac_digits 45 . A value of 0 means that the previous value is to be used for the rest of the groups.

then the currency_symbol appears after a positive monetary value. then the currency_symbol is separated by a space from a positive monetary value. If equals to 0.C Standard Library Number of digits to show after the decimal point in monetary values. 14 p_sep_by_space If equals to 1. The following values are used for p_sign_posn and n_sign_posn: Value Description 0 Parentheses encapsulates the value and the currency_symbol. then the currency_symbol succeeds a negative monetary value. 16 n_sep_by_space If equals to 1. 18 n_sign_posn Represents the position of the negative_sign in a negative monetary value. If equals to 0. 17 p_sign_posn Represents the position of the positive_sign in a positive monetary value. then the currency_symbol is separated by a space from a negative monetary value. If equals to 0. If equals to 0. then there is no space between the currency_symbol and a positive monetary value. then the currency_symbol precedes a negative monetary value. 13 p_cs_precedes If equals to 1. then the currency_symbol appears before a positive monetary value. 15 n_cs_precedes If equals to 1. then there is no space between the currency_symbol and a negative monetary value. 1 The sign precedes the value and currency_symbol. 46 .

C Standard Library 2 The sign succeeds the value and currency_symbol. 47 . 4 The sign immediately succeeds the value and currency_symbol. 3 The sign immediately precedes the value and currency_symbol.

HUGE_VAL). <MATH. 3 double atan(double x) Returns the arc tangent of x in radians.N. errno might or might not be set to ERANGE. Library Functions Following are the functions defined in the header math.7. and returns a particular. the function sets errno to ERANGE to indicate a range error. In this case. If the magnitude of the result is too small. Function & Description 1 double acos(double x) Returns the arc cosine of x in radians.h header defines various mathematical functions and one macro.N. Library Macros There is only one macro defined in this library: S. 2 double asin(double x) Returns the arc sine of x in radians. Macro & Description 1 HUGE_VAL This macro is used when the result of a function may not be representable as a floating point number. very large value named by the macro HUGE_VAL or its negation (.H> C Standard Library Introduction The math. If magnitude of the correct result is too large to be represented.h: S. 48 . a value of zero is returned instead. All the functions available in this library take double as an argument and return double as the result.

10 double exp(double x) Returns the value of e raised to the xth power. double x) Returns the arc tangent in radians of y/x based on the signs of both values to determine the correct quadrant. 8 double sinh(double x) Returns the hyperbolic sine of x. 12 double ldexp(double x. 6 double cosh(double x) Returns the hyperbolic cosine of x. 13 double log(double x) Returns the natural logarithm (base-e logarithm) of x. 9 double tanh(double x) Returns the hyperbolic tangent of x. 49 . The resultant value is x = mantissa * 2 ^ exponent. int exponent) Returns x multiplied by 2 raised to the power of exponent. 11 double frexp(double x. int *exponent) The returned value is the mantissa and the integer pointed to by exponent is the exponent. 14 double log10(double x) Returns the common logarithm (base-10 logarithm) of x. 7 double sin(double x) Returns the sine of a radian angle x. 5 double cos(double x) Returns the cosine of a radian angle x.C Standard Library 4 double atan2(doubly y.

16 double pow(double x. pi] radians. Return Value This function returns principal arc cosine of x. 18 double ceil(double x) Returns the smallest integer value greater than or equal to x. double y) Returns the remainder of x divided by y. Declaration Following is the declaration for acos() function. 21 double fmod(double x. double acos(double x) Description The C library function double acos(double x) returns the arc cosine of x in radians. double acos(double x) Parameters  x -. in the interval [0. 20 double floor(double x) Returns the largest integer value less than or equal to x.This is the floating point value in the interval [-1. double y) Returns x raised to the power of y. +1]. 17 double sqrt(double x) Returns the square root of x. double *integer) The returned value is the fraction component (part after the decimal). 19 double fabs(double x) Returns the absolute value of x. and sets integer to the integer component. 50 .C Standard Library 15 double modf(double x.

val.C Standard Library Example The following example shows the usage of acos() function. ret). in the interval [-pi/2. return(0). Return Value This function returns the arc sine of x.This is the floating point value in the interval [-1. #include <stdio.+1].+pi/2] radians. val = 180. x.h> #define PI 3.0 / PI. ret. double asin(double x) Parameters  x -. x = 0. 51 . } Let us compile and run the above program that will produce the following result: The arc cosine of 0.h> #include <math.9. printf("The arc cosine of %lf is %lf degrees". Declaration Following is the declaration for asin() function.855040 degrees double asin(double x) Description The C library function double asin(double x) returns the arc sine of x in radians.14159265 int main () { double x.900000 is 25. ret = acos(x) * val.

9.h> #include <math.C Standard Library Example The following example shows the usage of asin() function.+pi/2] radians. val = 180. } Let us compile and run the above program that will produce the following result: The arc sine of 0. double atan(double x) Parameters  x -.This is the floating point value.14159265 int main () { double x. printf("The arc sine of %lf is %lf degrees". ret). Declaration Following is the declaration for atan() function. return(0). #include <stdio.h> #define PI 3.900000 is 64.0 / PI.190609 degrees double atan(double x) Description The C library function double atan(double x) returns the arc tangent of x in radians. x. val. in the interval [-pi/2. x = 0. ret = asin(x) * val. Return Value This function returns the principal arc tangent of x. 52 . ret.

C Standard Library

Example
The following example shows the usage of atan() function.
#include <stdio.h>
#include <math.h>

#define PI 3.14159265

int main ()
{
double x, ret, val;
x = 1.0;
val = 180.0 / PI;

ret = atan (x) * val;
printf("The arc tangent of %lf is %lf degrees", x, ret);

return(0);
}
Let us compile and run the above program that will produce the following result:
The arc tangent of 1.000000 is 45.000000 degrees

double atan2(doubly y, double x)
Description
The C library function double atan2(doubly y, double x) returns the arc
tangent in radians of y/x based on the signs of both values to determine the
correct quadrant.

Declaration
Following is the declaration for atan2() function.
double atan2(doubly y, double x)

Parameters

x -- This is the floating point value representing an x-coordinate.

y -- This is the floating point value representing a y-coordinate.

Return Value
53

C Standard Library

This function returns the principal arc tangent of y/x, in the interval [-pi,+pi]
radians.

Example
The following example shows the usage of atan2() function.
#include <stdio.h>
#include <math.h>

#define PI 3.14159265

int main ()
{
double x, y, ret, val;

x = -7.0;
y = 7.0;
val = 180.0 / PI;

ret = atan2 (y,x) * val;
printf("The arc tangent of x = %lf, y = %lf ", x, y);
printf("is %lf degrees\n", ret);

return(0);
}
Let us compile and run the above program that will produce the following result:
The arc tangent of x = -7.000000, y = 7.000000 is 135.000000 degrees

double cos(double x)
Description
The C library function double cos(double x) returns the cosine of a radian
angle x.

Declaration
Following is the declaration for cos() function.
double cos(double x)
54

C Standard Library

Parameters

x -- This is the floating point value representing an angle expressed in
radians.

Return Value
This function returns the cosine of x.

Example
The following example shows the usage of cos() function.
#include <stdio.h>
#include <math.h>

#define PI 3.14159265

int main ()
{
double x, ret, val;

x = 60.0;
val = PI / 180.0;
ret = cos( x*val );
printf("The cosine of %lf is %lf degrees\n", x, ret);

x = 90.0;
val = PI / 180.0;
ret = cos( x*val );
printf("The cosine of %lf is %lf degrees\n", x, ret);

return(0);
}
Let us compile and run the above program that will produce the following result:
The cosine of 60.000000 is 0.500000 degrees
The cosine of 90.000000 is 0.000000 degrees

55

C Standard Library

double cosh(double x)
Description
The C library function double cosh(double x) returns the hyperbolic cosine
of x.

Declaration
Following is the declaration for cosh() function.
double cosh(double x)

Parameters

x -- This is the floating point value.

Return Value
This function returns hyperbolic cosine of x.

Example
The following example shows the usage of cosh() function.
#include <stdio.h>
#include <math.h>

int main ()
{
double x;

x = 0.5;
printf("The hyperbolic cosine of %lf is %lf\n", x, cosh(x));

x = 1.0;
printf("The hyperbolic cosine of %lf is %lf\n", x, cosh(x));

x = 1.5;
printf("The hyperbolic cosine of %lf is %lf\n", x, cosh(x));

return(0);
}
Let us compile and run the above program to produce the following result:

56

C Standard Library

The hyperbolic cosine of 0.500000 is 1.127626
The hyperbolic cosine of 1.000000 is 1.543081
The hyperbolic cosine of 1.500000 is 2.352410

double sin(double x)
Description
The C library function double sin(double x) returns the sine of a radian
angle x.

Declaration
Following is the declaration for sin() function.
double sin(double x)

Parameters

x -- This is the floating point value representing an angle expressed in
radians.

Return Value
This function returns sine of x.

Example
The following example shows the usage of sin() function.
#include <stdio.h>
#include <math.h>

#define PI 3.14159265

int main ()
{
double x, ret, val;

x = 45.0;
val = PI / 180;
ret = sin(x*val);
printf("The sine of %lf is %lf degrees", x, ret);

return(0);
57

ret). Return Value This function returns hyperbolic sine of x. Declaration Following is the declaration for sinh() function.h> int main () { double x.707107 degrees double sinh(double x) Description The C library function double sinh(double x) returns the hyperbolic sine of x. x = 0.C Standard Library } Let us compile and run the above program to produce the following result: The sine of 45.000000 is 0. double sinh(double x) Parameters  x -. return(0).500000 is 0.This is the floating point value. } Let us compile and run the above program. ret = sinh(x). x. this will produce the following result: The hyperbolic sine of 0. ret. Example The following example shows the usage of sinh() function.5.h> #include <math. #include <stdio.521095 degrees 58 . printf("The hyperbolic sine of %lf is %lf degrees".

Example The following example shows the usage of tanh() function.h> int main () { double x. } Let us compile and run the above program that will produce the following result: The hyperbolic tangent of 0.5. Return Value This function returns hyperbolic tangent of x.C Standard Library double tanh(double x) Description The C library function double tanh(double x) returns the hyperbolic tangent of x. x.500000 is 0. ret = tanh(x).h> #include <math.This is the floating point value. Declaration Following is the declaration for tanh() function. ret. return(0). printf("The hyperbolic tangent of %lf is %lf degrees". double tanh(double x) Parameters  x -. ret).462117 degrees double exp(double x) Description 59 . #include <stdio. x = 0.

This is the floating point value. exp(x)). int *exponent) Description 60 .000000 is 2. x+1.389056 double frexp(double x.h> int main () { double x = 0. } Let us compile and run the above program that will produce the following result: The exponential value of 0.000000 is 1.C Standard Library The C library function double exp(double x) returns the value of e raised to the xth power. double exp(double x) Parameters  x -. Declaration Following is the declaration for exp() function. x+2.h> #include <math. exp(x+2)).000000 The exponential value of 1. x.718282 The exponential value of 2. printf("The exponential value of %lf is %lf\n". Return Value This function returns the exponential value of x. #include <stdio. Example The following example shows the usage of exp() function. return(0). exp(x+1)).000000 is 7. printf("The exponential value of %lf is %lf\n". printf("The exponential value of %lf is %lf\n".

This is the pointer to an int object where the value of the exponent is to be stored. #include <stdio.This is the floating point value to be computed. double frexp(double x.2lf = %. the normalized fraction is x times a power of two. The resultant value is x = mantissa * 2 ^ exponent. } Let us compile and run the above program to produce the following result: x = 1024.h> int main () { double x = 1024. fraction. fraction. x. printf("x = %. If x is zero. If the argument x is not zero. fraction = frexp(x. and the integer pointed to by exponent is the exponent. int *exponent) Parameters  x -.2lf * 2^%d\n".00 = 0. then the normalized fraction is zero and zero is stored in exp. Return Value This function returns the normalized fraction. return(0). &e).C Standard Library The C library function double frexp(double x. Declaration Following is the declaration for frexp() function. and its absolute value is always in the range 1/2 (inclusive) to 1 (exclusive).50 * 2^11 61 .h> #include <math.  exponent -. int *exponent) return value is the mantissa. Example The following example shows the usage of frexp() function. e). int e.

n = 3. ret. Return Value This function returns x * 2 exp Example The following example shows the usage of ldexp() function. x.C Standard Library double ldexp(double x. ret = ldexp(x . x = 0.  exponent -. #include <stdio. int exponent) Parameters  x -.h> #include <math. return(0).n).650000 * 2^3 = 5. ret). int Declaration Following is the declaration for ldexp() function.65.h> int main () { double x.This is the floating point value representing the significand. n. double ldexp(double x. exponent) returns x multiplied by 2 raised to the power of exponent. printf("%f * 2^%d = %f\n". } Let us compile and run the above program that will produce the following result: 0. int n.200000 62 . int exponent) Description The C library function double ldexp(double x.This is the value of the exponent.

h> int main () { double x. return(0).7. #include <stdio. } Let us compile and run the above program that will produce the following result: log(2. x. ret).C Standard Library double log(double x) Description The C library function double log(double x) returns the natural logarithm (base-e logarithm) of x. printf("log(%lf) = %lf".993252 double log10(double x) Description 63 . Declaration Following is the declaration for log() function. Example The following example shows the usage of log() function. Return Value This function returns natural logarithm of x. ret. /* finding log(2. double log(double x) Parameters  x -.This is the floating point value.h> #include <math.700000) = 0.7) */ ret = log(x). x = 2.

C Standard Library

The C library function double log10(double x) returns the common logarithm
(base-10 logarithm) of x.

Declaration
Following is the declaration for log10() function.
double log10(double x)

Parameters

x -- This is the floating point value.

Return Value
This function returns the common logarithm of x, for values of x greater than
zero.

Example
The following example shows the usage of log10() function.
#include <stdio.h>
#include <math.h>

int main ()
{
double x, ret;
x = 10000;

/* finding value of log1010000 */
ret = log10(x);
printf("log10(%lf) = %lf\n", x, ret);

return(0);
}
Let us compile and run the above program that will produce the following result:
log10(10000.000000) = 4.000000

double modf(double x, double *integer)
Description

64

C Standard Library

The C library function double modf(double x, double *integer) returns the
fraction component (part after the decimal), and sets integer to the integer
component.

Declaration
Following is the declaration for modf() function.
double modf(double x, double *integer)

Parameters

x -- This is the floating point value.

integer -- This is the pointer to an object where the integral part is to be
stored.

Return Value
This function returns the fractional part of x, with the same sign.

Example
The following example shows the usage of modf() function.
#include<stdio.h>
#include<math.h>

int main ()
{
double x, fractpart, intpart;

x = 8.123456;
fractpart = modf(x, &intpart);

printf("Integral part = %lf\n", intpart);
printf("Fraction Part = %lf \n", fractpart);

return(0);
}
Let us compile and run the above program that will produce the following result:
Integral part = 8.000000
Fraction Part = 0.123456

65

C Standard Library

double pow(double x, double y)
Description
The C library function double pow(double x, double y) returns x raised to the
power of y i.e. xy.

Declaration
Following is the declaration for pow() function.
double pow(double x, double y)

Parameters

x -- This is the floating point base value.

y -- This is the floating point power value.

Return Value
This function returns the result of raising x to the power y.

Example
The following example shows the usage of pow() function.
#include <stdio.h>
#include <math.h>

int main ()
{
printf("Value 8.0 ^ 3 = %lf\n", pow(8.0, 3));

printf("Value 3.05 ^ 1.98 = %lf", pow(3.05, 1.98));

return(0);
}
Let us compile and run the above program that will produce the following result:
Value 8.0 ^ 3 = 512.000000
Value 3.05 ^ 1.98 = 9.097324

double sqrt(double x)
Description
The C library function double sqrt(double x) returns the square root of x.
66

C Standard Library

Declaration
Following is the declaration for sqrt() function.
double sqrt(double x)

Parameters

x -- This is the floating point value.

Return Value
This function returns the square root of x.

Example
The following example shows the usage of sqrt() function.
#include <stdio.h>
#include <math.h>

int main ()
{

printf("Square root of %lf is %lf\n", 4.0, sqrt(4.0) );
printf("Square root of %lf is %lf\n", 5.0, sqrt(5.0) );

return(0);
}
Let us compile and run the above program that will produce the following result:
Square root of 4.000000 is 2.000000
Square root of 5.000000 is 2.236068

double ceil(double x)
Description
The C library function double ceil(double x) returns the smallest integer value
greater than or equal to x.

Declaration
Following is the declaration for ceil() function.
double ceil(double x)

67

C Standard Library

Parameters

x -- This is the floating point value.

Return Value
This function returns the smallest integral value not less than x.

Example
The following example shows the usage of ceil() function.
#include <stdio.h>
#include <math.h>

int main ()
{
float val1, val2, val3, val4;

val1 = 1.6;
val2 = 1.2;
val3 = 2.8;
val4 = 2.3;

printf ("value1 = %.1lf\n", ceil(val1));
printf ("value2 = %.1lf\n", ceil(val2));
printf ("value3 = %.1lf\n", ceil(val3));
printf ("value4 = %.1lf\n", ceil(val4));

return(0);
}
Let us compile and run the above program that will produce the following result:
value1 = 2.0
value2 = 2.0
value3 = 3.0
value4 = 3.0

double fabs(double x)
Description
68

b. Example The following example shows the usage of fabs() function. double fabs(double x) Parameters  x -. printf("The absolute value of %d is %lf\n". #include <stdio. b. fabs(b)).C Standard Library The C library function double fabs(double x) returns the absolute value of x.This is the floating point value.000000 double floor(double x) Description The C library function double floor(double x) returns the largest integer value less than or equal to x. a = 1234.000000 The absolute value of -344 is 344. } Let us compile and run the above program that will produce the following result: The absolute value of 1234 is 1234. a. Return Value This function returns the absolute value of x. fabs(a)).h> int main () { int a. 69 . return(0). Declaration Following is the declaration for fabs() function. printf("The absolute value of %d is %lf\n". b = -344.h> #include <math.

floor(val4)).1lf\n".3.1lf\n".C Standard Library Declaration Following is the declaration for floor() function. val3 = 2. Example The following example shows the usage of floor() function.1lf\n". Return Value This function returns the largest integral value not greater than x.h> int main () { float val1.1lf\n". val2 = 1. val4 = 2.0 70 .6. return(0). val2. } Let us compile and run the above program that will produce the following result: Value1 = 1.2. double floor(double x) Parameters  x -.0 Value2 = 1. val1 = 1. printf("Value3 = %. #include <stdio. printf("Value4 = %. floor(val3)).This is the floating point value. printf("Value1 = %. val4. floor(val2)).h> #include <math. printf("Value2 = %.8. floor(val1)).0 Value3 = 2. val3.

 y -.2. } Let us compile and run the above program that will produce the following result: 71 . b.h> #include <math. c = 2. x.e. Return Value This function returns the remainder of dividing x/y. #include <stdio. fmod(a. double y) Parameters  x -.e.7.0 double fmod(double x. Example The following example shows the usage of fmod() function. double y) Description The C library function double fmod(double x. fmod(a.This is the floating point value with the division numerator i. Declaration Following is the declaration for fmod() function.h> int main () { float a.C Standard Library Value4 = 2. printf("Remainder of %f / %d is %lf\n". int c. a.b)). double y) returns the remainder of x divided by y. c. y.This is the floating point value with the division denominator i.c)). b. a. return(0). a = 9. double fmod(double x. printf("Remainder of %f / %f is %lf\n". b = 3.

200000 / 2 is 1.700000 is 1.200000 / 3.800000 72 .200000 Remainder of 9.C Standard Library Remainder of 9.

h header defines the macro setjmp(). holding information for Library Macros There is only one macro defined in this library: S. one function longjmp(). saves the current environment into the variable environment for later use by the function longjmp(). Macro & Description 1 int setjmp(jmp_buf environment) This macro saves the current environment into the variable environment for later use by the function longjmp(). for bypassing the normal function call and return discipline.8. If this macro returns directly from the macro invocation.h: S. int setjmp(jmp_buf environment) Description The C library macro int setjmp(jmp_buf environment).H> C Standard Library Introduction The setjmp. and one variable type jmp_buf. If this macro returns directly from the macro invocation. Library Variables Following is the variable type defined in the header setjmp. <SETJMP. then a non-zero value is returned. Variable & Description 1 jmp_buf This is an array type used for macro setjmp() and function longjmp().N. it 73 .N. it returns zero but if it returns from a longjmp() function call.

it always returns zero. if( val != 0 ) { printf("Returned from a longjmp() with value = %s\n".h> int main() { int val. Example The following example shows the usage of setjmp() macro. /* save calling environment for longjmp */ val = setjmp( env_buffer ). 74 .This is the object environment information is stored. #include <stdio. Declaration Following is the declaration for setjmp() macro. the macro returns again. on its direct invocation. return(0).h> #include <setjmp. When longjmp is called with the information set to the environment. val). } printf("Jump function call\n"). of type jmp_buf where the Return Value This macro may return more than once. exit(0).C Standard Library returns zero but if it returns from a longjmp() function call. then it returns the value passed to longjmp as a second argument.h> #include <stdlib. int setjmp(jmp_buf environment) Parameters  environment -. now it returns the value passed to longjmp as second argument. First time. jmp_buf env_buffer. jmpfunction( env_buffer ).

Function & Description 1 void longjmp(jmp_buf environment. int call the Declaration Following is the declaration for longjmp() function. this will produce the following result: Jump function call Returned from a longjmp() with value = tutorialspoint. int value) Description The C library function void longjmp(jmp_buf environment. void longjmp(jmp_buf environment.  value -. } Let us compile and run the above program.com Library Functions Following is the only one function defined in the header setjmp.C Standard Library } void jmpfunction(jmp_buf env_buf) { longjmp(env_buf. int value) Parameters  environment -. value) restores the environment saved by the most recent to setjmp() macro in the same invocation of the program with corresponding jmp_buf argument. Return Value 75 .This is the value to which the setjmp expression evaluates.com").This is the object of type jmp_buf containing information to restore the environment at the setjmp's calling point. void longjmp(jmp_buf environment. "tutorialspoint. int value) This function restores the environment saved by the most recent call to setjmp() macro in the same invocation of the program with the corresponding jmp_buf argument.N.h: S.

} printf("Jump function call\n"). val). "tutorialspoint. } Let us compile and run the above program that will produce the following result: Jump function call Returned from a longjmp() with value = tutorialspoint.C Standard Library This function does not return any value.h> #include <setjmp.com 76 . #include <stdio. if( val != 0 ) { printf("Returned from a longjmp() with value = %s\n". exit(0).h> #include <stdlib. /* save calling environment for longjmp */ val = setjmp( env_buffer ). Example The following example shows the usage of longjmp() function. jmpfunction( env_buffer ).com").h> int main() { int val. } void jmpfunction(jmp_buf env_buf) { longjmp(env_buf. jmp_buf env_buffer. return(0).

h header defines a variable type sig_atomic_t. Variable & Description 1 sig_atomic_t This is of int type and is used as a variable in a signal handler.H> C Standard Library Introduction The signal. and several macros to handle different signals reported during a program's execution.h: S. <SIGNAL. The SIG_ macros are used with the signal function to define signal functions. S.9. Library Macros Following are the macros defined in the header signal. 2 SIG_ERR Represents a signal error. even in the presence of asynchronous signals. 3 SIG_IGN Signal ignore.N.h and these macros will be used in two functions listed below.N. two function calls. Macro & Description 1 SIG_DFL Default signal handler. Library Variables Following is the variable type defined in the header signal. This is an integral type of an object that can be accessed as an atomic entity. The SIG macros are used to represent a signal number in the following conditions: 77 .

a signal handler. void (*signal(int sig. Library Functions Following are the functions defined in the header signal. The sig argument is compatible with the SIG macros. Macro & Description 1 SIGABRT Abnormal program termination. 5 SIGSEGV Invalid access to storage like segment violation. Function & Description 1 void (*signal(int sig.C Standard Library S. 4 SIGINT Interrupt signal such as ctrl-C.N. void (*func)(int)))(int) Description 78 . 6 SIGTERM Termination request. void (*func)(int)))(int) This function sets a function to handle signal i. 3 SIGILL Illegal operation.N.e. 2 int raise(int sig) This function causes signal sig to be generated.h: S. 2 SIGFPE Floating-point error like division by zero.

void (*signal(int sig. SIGFPE (Signal Floating-Point Exception) Erroneous arithmetic operation. This is generally due to a corruption in the code or to an attempt to execute data. such as zero divide or an operation resulting in overflow (not necessarily with a floating-point operation). SIGSEGV (Signal Segmentation Violation) Invalid access to storage: When a program tries to read or write outside the memory it is allocated for it. Declaration Following is the declaration for signal() function. Generally generated by the application user.This is the signal number to which a handling function is set. void (*func)(int)))(int) Parameters  sig -. such as an illegal instruction. SIGINT (Signal Interrupt) Interactive attention signal. SIG_IGN Ignore Signal: The signal is ignored. a signal handler with signal number sig. SIGTERM (Signal Terminate) Termination request sent to program.e. The following are few important standard signal numbers: macro signal SIGABRT (Signal Abort) Abnormal termination. SIGILL (Signal Illegal Instruction) Invalid function image.  func -. Return Value 79 .This is a pointer to a function. This can be a function defined by the programmer or one of the following predefined functions: SIG_DFL Default handling: The signal is handled by the default action for that particular signal. void (*func)(int)))(int) sets a function to handle signal i. such as is initiated by the function.C Standard Library The C library function void (*signal(int sig.

h> #include <stdlib. Example The following example shows the usage of signal() function. To come out of the program we used CTRL + C keys.. } Let us compile and run the above program that will produce the following result and program will go in infinite loop.. sighandler). signum)..\n"). or SIG_ERR on error.\n". #include <stdio. coming out.h> #include <signal. exit(1)... while(1) { printf("Going to sleep for a second.h> void sighandler(int). } void sighandler(int signum) { printf("Caught signal %d. sleep(1).h> #include <unistd. 80 . } return(0).. Going to sleep for a second. int main() { signal(SIGINT.. Going to sleep for a second.C Standard Library This function returns the previous value of the signal handler..

This is generally due to a corruption in the code or to an attempt to execute data.. coming out. int raise(int sig) Description The C library function int raise(int sig) causes signal sig to be generated.C Standard Library Going to sleep for a second.This is the signal number to send. such as an illegal instruction.. Caught signal 2.. such as zero divide or an operation resulting in overflow (not necessarily with a floating-point operation). The sig argument is compatible with the SIG macros. Going to sleep for a second. Going to sleep for a second. Following are few important standard signal constants: macro signal SIGABRT (Signal Abort) Abnormal termination. SIGTERM (Signal Terminate) Termination request sent to program.. SIGSEGV (Signal Segmentation Violation) Invalid access to storage: When a program tries to read or write outside the memory it is allocated for it. Generally generated by the application user. such as is initiated by the abort function. SIGFPE (Signal Floating-Point Exception) Erroneous arithmetic operation.. 81 ... Declaration Following is the declaration for signal() function. SIGINT (Signal Interrupt) Interactive attention signal. int raise(int sig) Parameters  sig -. SIGILL (Signal Illegal Instruction) Invalid function image..

ret = raise(SIGINT). and non-zero otherwise.\n")..h> void signal_catchfunc(int). Example The following example shows the usage of signal() function. int main() { int ret. signal_catchfunc).\n"). } printf("Exiting. ret = signal(SIGINT.C Standard Library Return Value This function returns zero if successful. } printf("Going to raise a signal\n").. exit(0). #include <signal.h> #include <stdio.\n"). return(0). } void signal_catchfunc(int signal) { 82 . exit(0). if( ret == SIG_ERR) { printf("Error: unable to set signal handler. if( ret !=0 ) { printf("Error: unable to raise SIGINT signal.

83 .. } Let us compile and run the above program to produce the following result: Going to raise a signal !! signal caught !! Exiting..C Standard Library printf("!! signal caught !!\n").

Library Variables Following is the variable type defined in the header stdarg. The last_arg is the last known fixed argument being passed to the function i. 2 type va_arg(va_list ap.H> Introduction The stdarg. type) This macro retrieves the next argument in the parameter list of the function with type type.C Standard Library 10..h header defines a variable type va_list and three macros which can be used to get the arguments in a function when the number of arguments are not known i. last_arg) This macro initializes ap variable to be used with the va_arg and va_end macros. the argument before the ellipsis. <STDARG.e.e.. 3 void va_end(va_list ap) This macro allows a function with variable arguments which used 84 . Macro & Description 1 void va_start(va_list ap. Library Macros Following are the macros defined in the header stdarg.N. Variable & Description 1 va_list This is a type suitable for holding information needed by the three macros va_start().) at the end of the parameter list. va_arg() and va_end().N.h: S. variable number of arguments.. A function of variable arguments is defined with the ellipsis (.h: S.

last_arg).e. Declaration Following is the declaration for va_start() macro. the result is undefined.C Standard Library the va_start macro to return. void va_start(va_list ap.This is the last known fixed argument being passed to the function. 20. . 25 and 30 = %d\n". last_arg) Description The C library macro void va_start(va_list ap. 30) ). } 85 . Return Value NA Example The following example shows the usage of va_start() macro. the argument before the ellipsis. void va_start(va_list ap.. last_arg) initializes ap variable to be used with the va_arg and va_end macros. The last_arg is the last known fixed argument being passed to the function i. #include<stdarg. If va_end is not called before returning from the function.This is the object of va_list and it will hold the information needed to retrieve the additional arguments with va_arg. This macro must be called before using va_arg and va_end. 10. Parameters  ap -.h> #include<stdio.). return 0. 30) ). 20.. 20. 4. sum(4. 20 and 30 = %d\n".h> int sum(int. sum(3. 25. printf("Sum of 4. int main(void) { printf("Sum of 10.  last_arg -.

25 and 30 = 79 type va_arg(va_list ap. int i. for(i = 0.. Declaration Following is the declaration for va_arg() macro. } va_end(ap). va_list ap. This does not determine whether the retrieved argument is the last argument passed to the function. type) retrieves the next argument in the parameter list of the function with type.. } Let us compile and run the above program to produce the following result: Sum of 10. . return val. type va_arg(va_list ap. type) Parameters  ap -.) { int val = 0. i < num_args.This is the object of type va_list with information about the additional arguments and their retrieval state. 86 . This object should be initialized by an initial call to va_start before the first call to va_arg. 20.C Standard Library int sum(int num_args. va_start(ap. int). 20 and 30 = 60 Sum of 4. num_args). type) Description The C library macro type va_arg(va_list ap. i++) { val += va_arg(ap.

sum(2..C Standard Library  type -.. i < num_args.. . va_start(ap.. i++) { val += va_arg(ap.This is a type name. 15. #include <stdarg. return val. this macro expands to. } va_end(ap). num_args). } Let us compile and run the above program to produce the following result: 87 . Example The following example shows the usage of va_arg() macro.h> int sum(int.h> #include <stdio. } int sum(int num_args. Return Value This macro returns the next additional argument as an expression of type type. for(i = 0. int main() { printf("Sum of 15 and 56 = %d\n".).) { int val = 0. return 0. This type name is used as the type of the expression. 56) ). va_list ap. int). . int i.

. 15. Return Value This macro does not return any value. . void va_end(va_list ap) Parameters  ap -.. 88 ..h> int mul(int. Example The following example shows the usage of va_end() macro.) { int val = 1. va_list ap. Declaration Following is the declaration for va_end() macro.h> #include <stdio. int main() { printf("15 * 12 = %d\n".. } int mul(int num_args.. If va_end is not called before returning from the function.C Standard Library Sum of 15 and 56 = 71 void va_end(va_list ap) Description The C library macro void va_end(va_list ap) allows a function with variable arguments which used the va_start macro to return.). mul(2. 12) ). return 0. the result is undefined. #include <stdarg.This is the va_list object previously initialized by va_start in the same function.

int). } va_end(ap). i < num_args. num_args). return val. va_start(ap. for(i = 0. } Let us compile and run the above program to produce the following result: 15 * 12 = 180 89 .C Standard Library int i. i++) { val *= va_arg(ap.

2 size_t This is the unsigned the sizeof keyword. Macro & Description 1 NULL This macro is the value of a null pointer constant. 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.11. Many of these definitions also appear in other headers.h: S.H> C Standard Library Introduction The stddef. 2 offsetof(type.h: S. <STDDEF.N. The member is given by member-designator. Library Macros Following are the macros defined in the header stddef. Library Variables Following are the variable types defined in the header stddef.N.h header defines various variable types and macros. and the name of the 90 . 3 integral type and is the result of wchar_t This is an integral type of the size of a wide character constant. Variable & Description 1 ptrdiff_t This is the signed integral type and is the result of subtracting two pointers.

h> int main () { FILE *fp. if( fp != NULL ) 91 . fp = fopen("file. Declaration Following may be the declaration for NULL Macro depending on the compiler. #include <stddef.txt". NULL Description The C library Macro NULL is the value of a null pointer constant.h> #include <stdio. "r").C Standard Library structure is given in type. It may be defined as ((void*)0). 0 or 0L depending on the compiler vendor. #define NULL ((char *)0) or #define NULL 0L or #define NULL 0 Parameters  NA Return Value  NA Example The following example shows the usage of NULL Macro.

} fp = fopen("nofile.txt does not exist.txt offsetof(type. Let us compile and run the above program that will produce the following result: Opend file file. member-designator) Parameters  type -. 92 . Declaration Following is the declaration for offsetof() Macro.txt successfully Could not open file nofile. Return Value This macro returns the value of type size_t which is the offset value of member in type. fclose(fp). offsetof(type. member-designator) 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.txt\n"). The member is given by member-designator. } Assuming we have an existing file file.txt but nofile. and the name of the structure is given in type. } return(0).  member-designator -.txt".C Standard Library { printf("Opend file file. "r").This is the member designator of class type. member-designator) Description The C library macro offsetof(type.txt successfully\n"). if( fp == NULL ) { printf("Could not open file nofile.This is the class type in which member-designator is a valid member designator.

char street[50]. int phone. this will produce the following result: name offset = 0 byte in address structure. }. return(0).h> #include <stdio.\n". phone)). phone offset = 100 byte in address structure.\n". printf("phone offset = %d byte in address structure.C Standard Library Example The following example shows the usage of offsetof() Macro. name)). offsetof(struct address. offsetof(struct address. offsetof(struct address. street)). printf("street offset = %d byte in address structure.\n". int main() { printf("name offset = %d byte in address structure.h> struct address { char name[50]. } Let us compile and run the above program. street offset = 50 byte in address structure. 93 . #include <stddef.

C Standard Library 94 .

Library Variables Following are the variable types defined in the header stdio. 95 . Macro & Description 1 NULL This macro is the value of a null pointer constant.N. _IOLBF and _IONBF These are the macros which expand to integral constant expressions with distinct values and suitable for the use as third argument to the setvbuf function. 3 fpos_t This is an object type suitable for storing any position in a file.h: S.N. 2 _IOFBF.h header defines three variable types.12. Variable & Description 1 size_t This is the unsigned the sizeof keyword. Library Macros Following are the macros defined in the header stdio.H> C Standard Library Introduction The stdio.h: S. <STDIO. and various functions for performing input and output. 2 integral type and is the result of FILE This is an object type suitable for storing information for a file stream. several macros.

7 L_tmpnam This macro is an integer. If the implementation imposes no limit. 5 FOPEN_MAX This macro is an integer. stdin.C Standard Library 3 BUFSIZ This macro is an integer. and SEEK_SET These macros are used in the fseek function to locate different positions in a file. which represents the maximum number of files that the system can guarantee to be opened simultaneously. then this value should be the recommended maximum value. Library Functions Following are the functions defined in the header stdio. which represents the longest length of a char array suitable for holding the longest possible temporary filename created by the tmpnam function. which represents the size of the buffer used by the setbuf function.h: 96 . 9 TMP_MAX This macro is the maximum number of unique filenames that the function tmpnam can generate. 8 SEEK_CUR. which indicates that the end-of-file has been reached. which represents the longest length of a char array suitable for holding the longest possible filename. standard input. SEEK_END. and stdout These macros are pointers to FILE types which correspond to the standard error. 4 EOFM This macro is a negative integer. 10 stderr. 6 FILENAME_MAX This macro is an integer. and standard output streams.

long int offset. 6 int fgetpos(FILE *stream. int whence) Sets the file position of the stream to the given offset. size_t nmemb. 5 int fflush(FILE *stream) Flushes the output buffer of a stream. S. const char *mode. 3 int feof(FILE *stream) Tests the end-of-file indicator for the given stream. const char *mode) Opens the filename pointed to by filename using the given mode.C Standard Library Follow the same sequence of functions for better understanding and to make use of Try it (online compiler) option. fpos_t *pos) Gets the current file position of the stream and writes it to pos. FILE *stream) Reads data from the given stream into the array pointed to by ptr. 8 size_t fread(void *ptr. 4 int ferror(FILE *stream) Tests the error indicator for the given stream. FILE *stream) Associates a new filename with the given open stream and same time closing the old file in stream.N. 10 int fseek(FILE *stream. All buffers are flushed. because file created in the first function will be used in subsequent functions. 2 void clearerr(FILE *stream) Clears the end-of-file and error indicators for the given stream. size_t size. 9 FILE *freopen(const char *filename. Function & Description 1 int fclose(FILE *stream) Closes the stream. The argument offset signifies the number of bytes to seek from the 97 . 7 FILE *fopen(const char *filename.

21 int fprintf(FILE *stream. size_t size. char *buffer) Defines how a stream should be buffered. 15 int rename(const char *old_filename. by old_filename to be changed to new_filename.. 18 int setvbuf(FILE *stream. 14 int remove(const char *filename) Deletes the given filename so that it is no longer accessible. const fpos_t *pos) Sets the file position of the given stream to the given position. 13 size_t fwrite(const void *ptr. 12 long int ftell(FILE *stream) Returns the current file position of the given stream.) 98 . 16 void rewind(FILE *stream) Sets the file position to the beginning of the file of the given stream. size_t nmemb. const char *format. 11 int fsetpos(FILE *stream. char *buffer. 19 FILE *tmpfile(void) Creates a temporary file in binary update mode (wb+). 17 void setbuf(FILE *stream.. 20 char *tmpnam(char *str) Generates and returns a valid temporary filename which does not exist.C Standard Library given whence position. size_t size) Another function to define how a stream should be buffered. The argument pos is a position given by the function fgetpos. . const char *new_filename) Causes the filename referred to. FILE *stream) Writes data from the array pointed to by ptr to the given stream. int mode.

va_list arg) Sends formatted output to a string using an argument list.. va_list arg) Sends formatted output to a stream using an argument list. 26 int vsprintf(char *str.) Reads formatted input from a string. whichever comes first. . the newline character is read. 29 int sscanf(const char *str. . 23 int sprintf(char *str. const char *format.. 30 int fgetc(FILE *stream) Gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream.. 31 char *fgets(char *str. const char *format. 99 . 25 int vprintf(const char *format..) Sends formatted output to stdout.. 22 int printf(const char *format. const char *format..) Reads formatted input from stdin... va_list arg) Sends formatted output to stdout using an argument list. 24 int vfprintf(FILE *stream. 27 int fscanf(FILE *stream. const char *format. 28 int scanf(const char *format.) Sends formatted output to a string. or the end-of-file is reached. const char *format.. FILE *stream) Reads a line from the specified stream and stores it into the string pointed to by str. .) Reads formatted input from a stream.C Standard Library Sends formatted output to a stream. int n. It stops when either (n-1) characters are read.. . .

A newline character is appended to the output. 36 char *gets(char *str) Reads a line from stdin and stores it into the string pointed to. 38 int putchar(int char) Writes a character (an unsigned char) specified by the argument char to stdout. by str.C Standard Library 32 int fputc(int char. 33 int fputs(const char *str. 39 int puts(const char *str) Writes a string to stdout up to but not including the null character. FILE *stream) Pushes the character char (an unsigned char) onto the specified stream so that the next character is read. FILE *stream) Writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream. 35 int getchar(void) Gets a character (an unsigned char) from stdin. 40 int ungetc(int char. 100 . FILE *stream) Writes a string to the specified stream up to but not including the null character. 37 int putc(int char. whichever comes first. It stops when either the newline character is read or when the end-offile is reached. 34 int getc(FILE *stream) Gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream. FILE *stream) Writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream.

"This is tutorialspoint. fprintf(fp. Declaration Following is the declaration for fclose() function. #include <stdio.com").h> int main() { FILE *fp. On failure. int fclose(FILE *stream) Description The C library function int fclose(FILE *stream) closes the stream.This is the pointer to a FILE object that specifies the stream to be closed. First the string str is printed followed by a colon and then a space.C Standard Library 41 void perror(const char *str) Prints a descriptive error message to stderr. Example The following example shows the usage of fclose() function. fp = fopen("file. } 101 . "%s". Return Value This method returns zero if the stream is successfully closed. "w"). int fclose(FILE *stream) Parameters  stream -. return(0). EOF is returned. fclose(fp). All buffers are flushed.txt".

h> int main() { FILE *fp. "w"). char c. Return Value This should not fail and do not set the external variable errno but in case it detects that its argument is not a valid stream. Example The following example shows the usage of clearerr() function. c = fgetc(fp). and then it will write following text line and finally it will close the file using fclose() function.txt\n"). This is tutorialspoint.com void clearerr(FILE *stream) Description The C library function void clearerr(FILE *stream) clears the end-of-file and error indicators for the given stream. } 102 . Declaration Following is the declaration for clearerr() function.txt. #include <stdio.C Standard Library Let us compile and run the above program that will create a file file. it must return -1 and set errno to EBADF. void clearerr(FILE *stream) Parameters  stream -.This is the pointer to a FILE object that identifies the stream. fp = fopen("file.txt". if( ferror(fp) ) { printf("Error in reading from file : file.

Return Value This function returns a non-zero value when End-of-File indicator associated with the stream is set. if( ferror(fp) ) { printf("Error in reading from file : file. which is an empty file.h> int main () { FILE *fp. #include <stdio. int feof(FILE *stream) Parameters  stream -. } Assuming we have a text file file.C Standard Library clearerr(fp). Error reading from file "file. 103 .txt\n"). Declaration Following is the declaration for feof() function.txt. return(0). Example The following example shows the usage of feof() function.This is the pointer to a FILE object that identifies the stream.txt" int feof(FILE *stream) Description The C library function int feof(FILE *stream) tests the end-of-file indicator for the given stream. this will produce the following result because we try to read a file which we opened in write only mode. let us compile and run the above program. } fclose(fp). else zero is returned.

return(0). fp = fopen("file. if( feof(fp) ) { break . return(-1). 104 .C Standard Library int c.txt. } Assuming we have a text file file. which has the following content.com int ferror(FILE *stream) Description The C library function int ferror(FILE *stream) tests the error indicator for the given stream. } fclose(fp). } printf("%c". } while(1) { c = fgetc(fp).txt". c). if(fp == NULL) { perror("Error in opening file")."r"). This file will be used as an input for our example program: This is tutorialspoint. Declaration Following is the declaration for ferror() function. this will produce the following result: This is tutorialspoint.com Let us compile and run the above program.

if( ferror(fp) ) { printf("Error in reading from file : file.This is the pointer to a FILE object that identifies the stream. the function returns a non-zero value else. #include <stdio. } fclose(fp). Let us compile and run the above program that will produce the following result because we try to read a file which we opened in write only mode. if( ferror(fp) ) { printf("Error in reading from file : file.txt\n"). 105 .txt\n").txt". c = fgetc(fp). Example The following example shows the usage of ferror() function.txt. Return Value If the error indicator associated with the stream was set.C Standard Library int ferror(FILE *stream) Parameters  stream -. } clearerr(fp).h> int main() { FILE *fp. char c. which is an empty file. fp = fopen("file. "w"). return(0). } Assuming we have a text file file. it returns a zero value.

feof). Declaration Following is the declaration for fflush() function.e. fprintf(stdout. buff. EOF is returned and the error indicator is set (i.h> int main() { char buff[1024]. fprintf(stdout. fflush( stdout ). Return Value This function returns a zero value on success. "Going to set full buffering on\n"). _IOFBF. #include <stdio. "This output will go into buff\n"). fprintf(stdout. "This is tutorialspoint.h> #include <string. 106 . memset( buff. 1024). If an error occurs. int fflush(FILE *stream) Parameters  stream -. Example The following example shows the usage of fflush() function.This is the pointer to a FILE object that specifies a buffered stream. '###BOT_TEXT###'.txt" int fflush(FILE *stream) Description The C library function int fflush(FILE *stream) flushes the output buffer of a stream. setvbuf(stdout.com\n"). sizeof( buff )).C Standard Library Error reading from file "file.

C Standard Library fprintf(stdout. Declaration Following is the declaration for fgetpos() function. after which it again starts buffering the output and finally sleeps for 5 seconds. "will come after sleeping 5 seconds\n").This is the pointer to a fpos_t object. return(0). fpos_t *pos) gets the current file position of the stream and writes it to pos. sleep(5). Return Value This function returns zero on success. Example The following example shows the usage of fgetpos() function. else non-zero value in case of an error. Going to set full buffering on This is tutorialspoint. fprintf(stdout.com This output will go into buff and this will appear when programm will come after sleeping 5 seconds int fgetpos(FILE *stream. int fgetpos(FILE *stream. fpos_t *pos) Parameters  stream -.  pos -.h> 107 . It sends remaining output to the STDOUT before program comes out. fpos_t *pos) Description The C library function int fgetpos(FILE *stream.This is the pointer to a FILE object that identifies the stream. #include <stdio. "and this will appear when programm\n"). Here program keeps buffering the output into buff until it faces first call to fflush(). } Let us compile and run the above program that will produce the following result.

World! in the file.h> int main () { FILE *fp. while(1) { 108 . return(0). fp = fopen("file.txt which will have the following content. fp). int c. &position). fputs("This is going to override previous content". First of all we get the initial position of the file using fgetpos() function and then we write Hello. but later we have used fsetpos() function to reset the write pointer at the beginning of the file and then over-write the file with the following content: This is going to override previous content Now let us see the content of the above file using the following program: #include <stdio."r"). fpos_t position. fp = fopen("file. &position)."w+").txt". fgetpos(fp. World!". int n = 0. } Let us compile and run the above program to create a file file.txt". fputs("Hello.C Standard Library int main () { FILE *fp. fclose(fp). fp). fsetpos(fp.

"a" Appends to a file. Writing operations.  mode -.This is the C string containing the name of the file to be opened. } fclose(fp). FILE *fopen(const char *filename. If a file with the same name already exists. "w" Creates an empty file for writing. return(0). c). const char *mode) Parameters  filename -. its content is erased and the file is considered as a new empty file. The file is created if it does not exist.This is the C string containing a file access mode. } FILE *fopen(const char *filename. Declaration Following is the declaration for fopen() function. The file must exist. 109 . It includes: mode Description "r" Opens a file for reading.C Standard Library c = fgetc(fp). if( feof(fp) ) { break . const char *mode) Description The C library function FILE *fopen(const char *filename. const char *mode) opens the filename pointed to. by filename using the given mode. } printf("%c". append data at the end of the file.

"in".txt". "w+").C Standard Library "r+" Opens a file to update both reading and writing. } Let us compile and run the above program that will create a file file. "We". Example The following example shows the usage of fopen() function. return(0).txt with the following content: We are in 2012 Now let us see the content of the above file using the following program: #include <stdio. 2012). Otherwise.h> #include <stdlib. fclose(fp). "w+" Creates an empty file for both reading and writing.h> int main() { FILE * fp.h> int main () { FILE *fp. The file must exist. Return Value This function returns a FILE pointer. fprintf(fp. NULL is returned and the global variable errno is set to indicate the error. #include <stdio. "%s %s %s %d". "a+" Opens a file for reading and appending. fp = fopen ("file. "are". 110 .

size_t size. return(0). FILE *stream) reads data from the given stream into the array pointed to. size_t size. each one with a size of size bytes. } size_t fread(void *ptr.txt". by ptr. fp = fopen("file. Declaration Following is the declaration for fread() function.This is the number of elements. size_t nmemb.  nmemb -.  size -. size_t size.This is the size in bytes of each element to be read. c). size_t fread(void *ptr. FILE *stream) Description The C library function size_t fread(void *ptr. if( feof(fp) ) { break . size_t nmemb. while(1) { c = fgetc(fp).C Standard Library int c. } fclose(fp).This is the pointer to a block of memory with a minimum size of size*nmemb bytes. Return Value 111 . FILE *stream) Parameters  ptr -.  stream -."r").This is the pointer to a FILE object that specifies an input stream. size_t nmemb. } printf("%c".

C Standard Library

The total number of elements successfully read are returned as a size_t object,
which is an integral data type. If this number differs from the nmemb
parameter, then either an error had occurred or the End Of File was reached.

Example
The following example shows the usage of fread() function.
#include <stdio.h>
#include <string.h>

int main()
{
FILE *fp;
char c[] = "this is tutorialspoint";
char buffer[20];

/* Open file for both reading and writing */
fp = fopen("file.txt", "w+");

/* Write data to the file */
fwrite(c, strlen(c) + 1, 1, fp);

/* Seek to the beginning of the file */
fseek(fp, SEEK_SET, 0);

/* Read and display data */
fread(buffer, strlen(c)+1, 1, fp);
printf("%s\n", buffer);
fclose(fp);

return(0);
}
Let us compile and run the above program that will create a file file.txt and
write a content this is tutorialspoint. After that, we use fseek() function to reset
writing pointer to the beginning of the file and prepare the file content which is
as follows:
this is tutorialspoint
112

C Standard Library

FILE *freopen(const char *filename, const char *mode, FILE *stream)
Description
The C library function FILE *freopen(const char *filename, const char
*mode, FILE *stream) associates a new filename with the given open stream
and at the same time closes the old file in the stream.

Declaration
Following is the declaration for freopen() function.
FILE *freopen(const char *filename, const char *mode, FILE *stream)

Parameters

filename -- This is the C string containing the name of the file to be
opened.

mode -- This is the C string containing a file access mode. It includes:

mode

Description

"r"

Opens a file for reading. The file must exist.

"w"

Creates an empty file for writing. If a file with the same name already
exists then its content is erased and the file is considered as a new
empty file.

"a"

Appends to a file. Writing operations appends data at the end of the
file. The file is created if it does not exist.

"r+"

Opens a file to update both reading and writing. The file must exist.

"w+"

Creates an empty file for both reading and writing.

"a+"

Opens a file for reading and appending.

stream -- This is the pointer to a FILE object that identifies the stream to
be re-opened.

Return Value
If the file was re-opened successfully, the function returns a pointer to an object
identifying the stream or else, null pointer is returned.

Example
The following example shows the usage of freopen() function.

113

C Standard Library

#include <stdio.h>

int main ()
{
FILE *fp;

printf("This text is redirected to stdout\n");

fp = freopen("file.txt", "w+", stdout);

printf("This text is redirected to file.txt\n");

fclose(fp);

return(0);
}
Let us compile and run the above program that will send the following line at
STDOUT because initially we did not open stdout:
This text is redirected to stdout
After a call to freopen(), it associates STDOUT to file file.txt, so whatever we
write at STDOUT, goes inside file.txt. So, the file file.txt will have the following
content.
This text is redirected to file.txt
Now let's see the content of the above file using the following program:
#include <stdio.h>

int main ()
{
FILE *fp;
int c;

fp = fopen("file.txt","r");
while(1)
114

C Standard Library

{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}

int fseek(FILE *stream, long int offset, int whence)
Description
The C library function int fseek(FILE *stream, long int
whence) sets the file position of the stream to the given offset.

offset,

int

Declaration
Following is the declaration for fseek() function.
int fseek(FILE *stream, long int offset, int whence)

Parameters

stream -- This is the pointer to a FILE object that identifies the stream.

offset -- This is the number of bytes to offset from whence.

whence -- This is the position from where offset is added. It is specified
by one of the following constants:

Constant

Description

SEEK_SET

Beginning of file

SEEK_CUR

Current position of the file pointer

SEEK_END

End of file

Return ValueThis function returns zero if successful, or else it returns a non-zero
value.
115

C Standard Library

Example
The following example shows the usage of fseek() function.
#include <stdio.h>

int main ()
{
FILE *fp;

fp = fopen("file.txt","w+");
fputs("This is tutorialspoint.com", fp);

fseek( fp, 7, SEEK_SET );
fputs(" C Programming Langauge", fp);
fclose(fp);

return(0);
}
Let us compile and run the above program that will create a file file.txt with the
following content. Initially program creates the file and writes This is
tutorialspoint.com, but later we had reset the write pointer at 7th position from
the beginning and used puts() statement which over-write the file with the
following content:
This is C Programming Langauge
Now let's see the content of the above file using the following program:
#include <stdio.h>

int main ()
{
FILE *fp;
int c;

fp = fopen("file.txt","r");
while(1)
{
116

const fpos_t *pos) Description The C library function int fsetpos(FILE *stream. c).h> int main () { FILE *fp. or else it returns a non-zero value and sets the global variable errno to a positive value.  pos -. Return Value This function returns zero value if successful. return(0). #include <stdio. const fpos_t *pos) sets the file position of the given stream to the given position. which can be interpreted with perror. int fsetpos(FILE *stream. } printf("%c". } fclose(fp). Example The following example shows the usage of fsetpos() function. } int fsetpos(FILE *stream.This is the pointer to a FILE object that identifies the stream.C Standard Library c = fgetc(fp). Declaration Following is the declaration for fsetpos() function. if( feof(fp) ) { break . const fpos_t *pos) Parameters  stream -. The argument pos is a position given by the function fgetpos.This is the pointer to a fpos_t object containing a position previously obtained with fgetpos. 117 .

First of all we get the initial position of the file using fgetpos() function. fsetpos(fp.h> int main () { FILE *fp. while(1) { c = fgetc(fp)."r").C Standard Library fpos_t position.txt". fgetpos(fp. fp). return(0). } 118 ."w+"). fp = fopen("file. fputs("This is going to override previous content". fputs("Hello. &position). } Let us compile and run the above program to create a file file. fp = fopen("file. int c. fclose(fp). fp). if( feof(fp) ) { break .txt which will have the following content. World!". and then we write Hello. World! in the file but later we used fsetpos() function to reset the write pointer at the beginning of the file and then over-write the file with the following content: This is going to override previous content Now let's see the content of the above file using the following program: #include <stdio.txt". &position).

This is the pointer to a FILE object that identifies the stream. long int ftell(FILE *stream) Parameters  stream -.h> int main () { FILE *fp. return(-1). int len. and the global variable errno is set to a positive value. return(0). Return Value This function returns the current value of the position indicator. c). fp = fopen("file. } fclose(fp). "r"). If an error occurs. Declaration Following is the declaration for ftell() function. } 119 .txt". Example The following example shows the usage of ftell() function. if( fp == NULL ) { perror ("Error opening file").C Standard Library printf("%c". } long int ftell(FILE *stream) Description The C library function long int ftell(FILE *stream) returns the current file position of the given stream. -1L is returned. #include <stdio.

size_t fwrite(const void *ptr. size_t nmemb. size_t nmemb. SEEK_END).  nmemb -. size_t size. fclose(fp).This is the pointer to a FILE object that specifies an output stream.This is the pointer to the array of elements to be written. } Let us assume we have a text file file.txt. Return Value 120 . FILE *stream) Parameters  ptr -. Declaration Following is the declaration for fwrite() function. size_t nmemb.txt = 27 bytes size_t fwrite(const void *ptr. size_t size. len = ftell(fp).  stream -.  size -. printf("Total size of file. which has the following content: This is tutorialspoint. 0. by ptr to the given stream. each one with a size of size bytes.txt = %d bytes\n".C Standard Library fseek(fp. len). size_t size.This is the number of elements. return(0). FILE *stream) writes data from the array pointed to. FILE *stream) Description The C library function size_t fwrite(const void *ptr.This is the size in bytes of each element to be written.com Now let us compile and run the above program that will produce the following result if file has above mentioned content otherwise it will give different result based on the file content: Total size of file.

Example The following example shows the usage of fwrite() function.com". fp = fopen( "file. which is an integral data type. it will show an error.C Standard Library This function returns the total number of elements successfully returned as a size_t object.txt" .com Now let's see the content of the above file using the following program: #include <stdio. return(0). If this number differs from the nmemb parameter.txt which will have following content: This is tutorialspoint. fclose(fp)."r"). #include<stdio. char str[] = "This is tutorialspoint. 1 .h> int main () { FILE *fp. "w" ). fwrite(str . while(1) { c = fgetc(fp). 121 . fp = fopen("file. sizeof(str) . } Let us compile and run the above program that will create a file file.txt". fp ).h> int main () { FILE *fp. int c.

char filename[] = "file.h> #include <string. int remove(const char *filename) Parameters  filename -. } int remove(const char *filename) Description The C library function int remove(const char given filename so that it is no longer accessible. #include <stdio. Example The following example shows the usage of remove() function. -1 is returned.This is the C string containing the name of the file to be deleted.C Standard Library if( feof(fp) ) { break . On error. and errno is set appropriately. *filename) deletes the Declaration Following is the declaration for remove() function. zero is returned. } printf("%c". Return Value On success. 122 .txt". c).h> int main () { int ret. } fclose(fp). return(0). FILE *fp.

fprintf(fp. ret = remove(filename). const char *new_filename) Description The C library function int rename(const char *old_filename. using the above program.com"). const char *new_filename) Parameters 123 .C Standard Library fp = fopen(filename. Declaration Following is the declaration for rename() function.txt having some content. "w"). So we are going to delete this file. fclose(fp). } else { printf("Error: unable to delete the file"). if(ret == 0) { printf("File deleted successfully"). "This is tutorialspoint. } return(0). Let us compile and run the above program to produce the following message and the file will be deleted permanently. } Let us assume we have a text file file. const char *new_filename) causes the filename referred to by old_filename to be changed to new_filename. int rename(const char *old_filename. File deleted successfully int rename(const char *old_filename. "%s".

#include <stdio.C Standard Library  old_filename -. Example The following example shows the usage of rename() function.  new_filename -. newname). if(ret == 0) { printf("File renamed successfully").txt. zero is returned. Return Value On success. Let us compile and run the above program to produce the following message and the file will be renamed to newfile. } Let us assume we have a text file file. So.txt". having some content.txt". we are going to rename this file. File renamed successfully 124 . -1 is returned. } return(0). and errno is set appropriately. } else { printf("Error: unable to rename the file"). char oldname[] = "file.This is the C string containing the new name for the file. ret = rename(oldname. using the above program. On error.h> int main () { int ret.txt file.This is the C string containing the name of the file to be renamed and/or moved. char newname[] = "newfile.

while(1) { ch = fgetc(fp).txt" . Return Value This function does not return any value. Declaration Following is the declaration for rewind() function. fclose(fp). Example The following example shows the usage of rewind() function. fp ).h> int main() { char str[] = "This is tutorialspoint. FILE *fp. #include <stdio. 125 . "r" ). if( feof(fp) ) { break .This is the pointer to a FILE object that identifies the stream. sizeof(str) . int ch. /* First let's write some content in the file */ fp = fopen( "file. void rewind(FILE *stream) Parameters  stream -. fwrite(str . "w" ). fp = fopen( "file.txt" . 1 .C Standard Library void rewind(FILE *stream) Description The C library function void rewind(FILE *stream) sets the file position to the beginning of the file of the given stream.com".

but before any input or output operation has taken place. ch).com Now let us compile and run the above program to produce the following result: This is tutorialspoint.com This is tutorialspoint.txt that have the following content: This is tutorialspoint.com void setbuf(FILE *stream. } printf("%c". } fclose(fp). while(1) { ch = fgetc(fp). if( feof(fp) ) { break . printf("\n").C Standard Library } printf("%c". This function should be called once the file associated with the stream has already been opened. ch). char *buffer) Description The C library function void setbuf(FILE *stream. } rewind(fp). char *buffer) defines how a stream should be buffered. 126 . } Let us assume we have a text file file. Declaration Following is the declaration for setbuf() function. return(0).

C Standard Library void setbuf(FILE *stream. Example The following example shows the usage of setbuf() function. size_t size)defines how a stream should be buffered. int mode. setbuf(stdout. size_t size) Description The C library function int setvbuf(FILE *stream. puts("This is tutorialspoint"). fflush(stdout). return(0).  buffer -.h> int main() { char buf[BUFSIZ]. Return Value This function does not return any value. This is tutorialspoint int setvbuf(FILE *stream.This is the pointer to a FILE object that identifies an open stream. which is a macro constant to be used as the length of this array. char *buffer.This is the user allocated buffer. Declaration 127 . } Let us compile and run the above program to produce the following result. char *buffer) Parameters  stream -. This should have a length of at least BUFSIZ bytes. int mode. Here program sends output to the STDOUT just before it comes out. char *buffer. You can also use fflush() function to flush the output. #include <stdio. buf). otherwise it keeps buffering the output.

int setvbuf(FILE *stream. data is written once the buffer is full.  buffer -. size_t size) Parameters  stream -. char *buffer. #include <stdio.This specifies a mode for file buffering: mode Description _IOFBF Full buffering: On output. Example The following example shows the usage of setvbuf() function.This is the pointer to a FILE object that identifies an open stream. whatsoever happens first.h> int main() { char buff[1024]. sizeof( buff )).  mode -.This is the user allocated buffer.C Standard Library Following is the declaration for setvbuf() function. data is written when a newline character is inserted into the stream or when the buffer is full. _IOLBF Line buffering: On output. '###BOT_TEXT###'. int mode. On Input the buffer is filled when an input operation is requested and the buffer is empty. The buffer and size parameters are ignored. If set to NULL. On Input.  size -. memset( buff. the buffer is filled till the next newline character when an input operation is requested and buffer is empty. non-zero value is returned. _IONBF No buffering: No buffer is used. 128 . Each I/O operation is written as soon as possible.This is the buffer size in bytes Return Value This function returns zero on success else. the function automatically allocates a buffer of the specified size.

"and this will appear when programm\n"). fprintf(stdout. It sends remaining output to the STDOUT before the program comes out.com This output will go into buff and this will appear when programm will come after sleeping 5 seconds FILE *tmpfile(void) Description The C library function FILE *tmpfile(void) creates a temporary file in binary update mode (wb+). return(0). buff.C Standard Library fprintf(stdout. The temporary file created is automatically deleted when the stream is closed (fclose) or when the program terminates. "Going to set full buffering on\n"). fprintf(stdout. "This is tutorialspoint. FILE *tmpfile(void) Parameters  NA 129 . after which it again starts buffering the output and finally sleeps for 5 seconds. sleep(5). fprintf(stdout. "will come after sleeping 5 seconds\n"). Here program keeps buffering the output into buff until it faces first call to fflush(). _IOFBF. fflush( stdout ).com\n"). 1024). "This output will go into buff\n"). Declaration Following is the declaration for tmpfile() function. setvbuf(stdout. } Let us compile and run the above program to produce the following result. fprintf(stdout. Going to set full buffering on This is tutorialspoint.

the function returns a stream pointer to the temporary file created. fp = tmpfile(). Declaration Following is the declaration for tmpnam() function. } Let us compile and run the above program to create a temporary file in /tmp folder but once your program is out. char *tmpnam(char *str) 130 .C Standard Library Return Value If successful. If str is null then it simply returns the tmp file name. it will be deleted automatically and the program will produce the following result: Temporary file created char *tmpnam(char *str) Description The C library function char *tmpnam(char *str) generates and returns a valid temporary filename which does not exist. If the file cannot be created. /* you can use tmp file here */ fclose(fp).h> int main () { FILE *fp. return(0). printf("Temporary file created\n"). Example The following example shows the usage of tmpfile() function. #include <stdio. then NULL is returned.

#include <stdio. ptr = tmpnam(NULL). printf("Temporary name 2: %s\n".. tmpnam(buffer). ptr). char *ptr. this points to an internal buffer that will be overwritten the next time this function is called. Return Value  Return value is a pointer to the C string containing the proposed name for a temporary file. str is returned. printf("Temporary name 1: %s\n". } Let us compile and run the above program to produce the following result: Temporary name 1: /tmp/filebaalTb Temporary name 2: /tmp/filedCIbb0 int fprintf(FILE *stream. const char *format. Example The following example shows the usage of tmpnam() function. . If str was a null pointer. If the function fails to create a suitable filename.C Standard Library Parameters  str -..) Description 131 . return(0).This is the pointer to an array of chars where the proposed temp name will be stored as a C string.  If str was not a null pointer. it returns a null pointer.h> int main() { char buffer[L_tmpnam]. buffer).

) sends formatted output to a stream.. . Declaration Following is the declaration for fprintf() function.C Standard Library The C library function int fprintf(FILE *stream. const char *format.This is the C string that contains the text to be written to the stream. int fprintf(FILE *stream.precision][length]specifier.  format -.) Parameters  stream -.This is the pointer to a FILE object that identifies the stream. const char *format. . which is explained below: specifier Output c Character d or i Signed decimal integer e Scientific notation (mantissa/exponent) using e character E Scientific notation (mantissa/exponent) using E character f Decimal floating point g Uses the shorter of %e or %f G Uses the shorter of %E or %f o Signed octal s String of characters u Unsigned decimal integer x Unsigned hexadecimal integer 132 .. Format tags prototype is %[flags][width][. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested...

E and f. By default. * The width is not specified in the format string. The value is not truncated even if the result is larger. Right justification is the default (see width sub-specifier).C Standard Library X Unsigned hexadecimal integer (capital letters) p Pointer address n Nothing printed % Character flags Description - Left-justifies within the given field width. width Description (number) Minimum number of characters to be printed. if no digits follow then no decimal point is written. (space) If no sign is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed. it forces the written output to contain a decimal point even if no digits would follow. 0x or 0X respectively for values different than zero. the result is padded with blank spaces. but as an additional integer value argument preceding the argument that has to be formatted. Used with e. a blank space is inserted before the value. If the value to be printed is shorter than this number. only negative numbers are preceded with a -ve sign. where padding is specified (see width sub-specifier). The value is preceded with 0. + Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. # Used with o. By default. 0 Left-pads the number with zeroes (0) instead of spaces. x or X specifiers. 133 .

Example The following example shows the usage of fprintf() function. u.C Standard Library . length Description h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i. For e. A precision of 0 means that no character is written for the value 0. x. x and X). X): precision specifies the minimum number of digits to be written. d. the default is 1. o. l The argument is interpreted as a long int or unsigned long int for integer specifiers (i. o.precision Description . each containing one value to be inserted instead of each %-tag specified in the format parameter. u. the total number of characters written is returned otherwise. E. f. For g and G specifiers: This is the maximum number of significant digits to be printed. d. By default all characters are printed until the ending null character is encountered.number For integer specifiers (d. if any. the result is padded with leading zeros. If the period is specified without an explicit value for precision. There should be the same number of these arguments as the number of %-tags that expect a value. 134 . u. a negative number is returned. 0 is assumed. Return Value If successful. E and f specifiers: this is the number of digits to be printed after the decimal point. g and G). For c type: it has no effect. but as an additional integer value argument preceding the argument that has to be formatted. For s: this is the maximum number of characters to be printed. the function may expect a sequence of additional arguments.  additional arguments -. o. When no precision is specified. and as a wide character or wide character string for specifiers c and s. . L The argument is interpreted as a long double (only applies to floating point specifiers: e.* The precision is not specified in the format string. The value is not truncated even if the result is longer. i. x and X). If the value to be written is shorter than this number.Depending on the format string.

txt with the following content: We are in 2012 Now let's see the content of the above file using the following program: #include <stdio.h> int main () { FILE *fp. "%s %s %s %d".txt". fclose(fp). "in". } 135 .txt". while(1) { c = fgetc(fp). int c.h> #include <stdlib. fp = fopen ("file. return(0). } Let us compile and run the above program that will create a file file."r"). "are". fp = fopen("file. if( feof(fp) ) { break .C Standard Library #include <stdio. 2012).h> int main() { FILE * fp. "We". "w+"). fprintf(fp.

precision][length]specifier... . . Declaration Following is the declaration for printf() function..This is the string that contains the text to be written to stdout.C Standard Library printf("%c"...) Description The C library function int printf(const char *format. ..) Parameters  format -. which is explained below: specifier Output c Character d or i Signed decimal integer e Scientific notation (mantissa/exponent) using e character E Scientific notation (mantissa/exponent) using E character f Decimal floating point g Uses the shorter of %e or %f. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. } fclose(fp). return(0).) sends formatted output to stdout. G Uses the shorter of %E or %f 136 . int printf(const char *format. Format tags prototype is %[flags][width][. c). } int printf(const char *format.

it no digits point is or E but Description 137 . # Used with o. E forces the written output to contain a decimal point even if would follow. + Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. width 0x or 0X and f. (space) If no sign is going to be written. By default. if no digits follow. only negative numbers are preceded with a -ve sign. Used with g or G the result is the same as with e trailing zeros are not removed. no decimal written. Used with e. where padding is specified (see width sub-specifier). 0 Left-pads the number with zeroes (0) instead of spaces. a blank space is inserted before the value. Right justification is the default (see width sub-specifier). x or X specifiers the value is preceded with 0.C Standard Library o Signed octal s String of characters u Unsigned decimal integer x Unsigned hexadecimal integer X Unsigned hexadecimal integer (capital letters) p Pointer address n Nothing printed % Character flags Description - Left-justify within the given field width. By default. respectively for values different than zero.

For c type: it has no effect. E. The value is not truncated even if the result is larger. If the period is specified without an explicit value for precision. By default all characters are printed until the ending null character is encountered.  additional arguments -. l The argument is interpreted as a long int or unsigned long int for integer specifiers (i. f. . For e. .number For integer specifiers (d.* The precision is not specified in the format string. x. u. and as a wide character or wide character string for specifiers c and s. For s: this is the maximum number of characters to be printed. A precision of 0 means that no character is written for the value 0. For g and G specifiers: This is the maximum number of significant digits to be printed. u.precision Description . When no precision is specified. i. If the value to be written is shorter than this number. the result is padded with blank spaces. 0 is assumed. length Description h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i. x and X). but as an additional integer value argument preceding the argument that has to be formatted. but as an additional integer value argument preceding the argument that has to be formatted. the result is padded with leading zeros. o. each containing one value to be inserted instead of each %-tag specified in the format 138 . o. If the value to be printed is shorter than this number. d. the default is 1.Depending on the format string. the function may expect a sequence of additional arguments. E and f specifiers: this is the number of digits to be printed after the decimal point. x and X). d.C Standard Library (number) Minimum number of characters to be printed. u. L The argument is interpreted as a long double (only applies to floating point specifiers: e. * The width is not specified in the format string. The value is not truncated even if the result is longer. g and G). o. X): precision specifies the minimum number of digits to be written.

Character = X 139 . Character = V ASCII value = 87. There should be the same number of these arguments as the number of %-tags that expect a value. On failure. Character = S ASCII value = 84. Return Value If successful. Character = Q ASCII value = 82. for( ch = 75 . ch . Character = R ASCII value = 83. Character = L ASCII value = 77. #include <stdio. Character = T ASCII value = 85. Character = M ASCII value = 78. } return(0).h> int main () { int ch.C Standard Library parameter (if any). Example The following example shows the usage of printf() function. ch++ ) { printf("ASCII value = %d. Character = %c\n". Character = K ASCII value = 76. Character = P ASCII value = 81. ch <= 100. Character = N ASCII value = 79. Character = U ASCII value = 86. a negative number is returned. } Let us compile and run the above program to produce the following result: ASCII value = 75. Character = O ASCII value = 80. ch ). Character = W ASCII value = 88. the total number of characters written is returned.

. Character = ^ ASCII value = 95... const char *format. as explained below: specifier Output c Character d or i Signed decimal integer 140 .) sends formatted output to a string pointed to. Format tags prototype: %[flags][width][. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested.) Parameters  str -. Character = _ ASCII value = 96. Character = b ASCII value = 99. Character = Y ASCII value = 90. const char *format. int sprintf(char *str. Declaration Following is the declaration for sprintf() function. . by str. const char *format... Character = a ASCII value = 98.) Description The C library function int sprintf(char *str.. Character = \ ASCII value = 93.precision][length]specifier. .  format -. Character = d int sprintf(char *str.This is the pointer to an array of char elements where the resulting C string is stored. Character = [ ASCII value = 92.This is the String that contains the text to be written to buffer. Character = c ASCII value = 100.C Standard Library ASCII value = 89. Character = ] ASCII value = 94. Character = ` ASCII value = 97. Character = Z ASCII value = 91. .

x or X specifiers the value is preceded with 0. # Used with o. By default.C Standard Library e Scientific notation (mantissa/exponent) using e character E Scientific notation (mantissa/exponent) using E character f Decimal floating point g Uses the shorter of %e or %f. 0x or 141 . Right justification is the default (see width sub-specifier). G Uses the shorter of %E or %f o Signed octal s String of characters u Unsigned decimal integer x Unsigned hexadecimal integer X Unsigned hexadecimal integer (capital letters) p Pointer address n Nothing printed % Character flags Description - Left-justify within the given field width. a blank space is inserted before the value. (space) If no sign is going to be written. only negative numbers are preceded with a -ve sign. + Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers.

x. length Description 142 . By default all characters are printed until the ending null character is encountered. 0 is assumed. X): precision specifies the minimum number of digits to be written. * The width is not specified in the format string. 0 Left-pads the number with zeroes (0) instead of spaces. the result is padded with blank spaces. If the period is specified without an explicit value for precision. E and f. For g and G specifiers: This is the maximum number of significant digits to be printed.number For integer specifiers (d.precision Description . E and f specifiers: this is the number of digits to be printed after the decimal point. Used with g or G the result is the same as with e or E but trailing zeros are not removed. A precision of 0 means that no character is written for the value 0. For s: this is the maximum number of characters to be printed. The value is not truncated even if the result is longer. If the value to be printed is shorter than this number.C Standard Library 0X respectively for values different than zero. but as an additional integer value argument preceding the argument that has to be formatted. If the value to be written is shorter than this number. o. the result is padded with leading zeros. no decimal point is written. The value is not truncated even if the result is larger. By default. it forces the written output to contain a decimal point even if no digits would follow. where padding is specified (see width sub-specifier). When no precision is specified. For e. . but as an additional integer value argument preceding the argument that has to be formatted. Used with e. For c type: it has no effect. i.* The precision is not specified in the format string. if no digits follow. width Description (number) Minimum number of characters to be printed. . the default is 1. u.

"Value of Pi = %f".C Standard Library h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i. g and G). otherwise a negative number is returned in case of failure. E. #include <stdio. puts(str). Example The following example shows the usage of sprintf() function. x and X). x and X). sprintf(str.h> int main() { char str[80]. d. Return Value If successful. } Let us compile and run the above program. u. u. f.Depending on the format string.h> #include <math. this will produce the following result: Value of Pi = 3. o. the function may expect a sequence of additional arguments. M_PI). o. and as a wide character or wide character string for specifiers c and s.  additional arguments -.141593 143 . l The argument is interpreted as a long int or unsigned long int for integer specifiers (i. There should be the same number of these arguments as the number of %-tags that expect a value. the total number of characters written is returned excluding the null-character appended at the end of the string. d. return(0). each containing one value to be inserted instead of each %-tag specified in the format parameter (if any). L The argument is interpreted as a long double (only applies to floating point specifiers: e.

va_list arg) Description The C library function int vfprintf(FILE *stream. Format tags prototype: %[flags][width][. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested.C Standard Library int vfprintf(FILE *stream. va_list arg) sends formatted output to a stream using an argument list passed to it. as explained below: specifier Output c Character d or i Signed decimal integer e Scientific notation (mantissa/exponent) using e character E Scientific notation (mantissa/exponent) using E character f Decimal floating point g Uses the shorter of %e or %f G Uses the shorter of %E or %f o Signed octal s String of characters u Unsigned decimal integer 144 . const char *format. va_list arg) Parameters  stream -.  format -. const char *format.This is the C string that contains the text to be written to the stream. const char *format.This is the pointer to a FILE object that identifies the stream. int vfprintf(FILE *stream. Declaration Following is the declaration for vfprintf() function.precision][length]specifier.

if no digits follow. where padding is specified (see width sub-specifier). 0 Left-pads the number with zeroes (0) instead of spaces.C Standard Library x Unsigned hexadecimal integer X Unsigned hexadecimal integer (capital letters) p Pointer address n Nothing printed % Character flags Description - Left-justify within the given field width. x or X specifiers the value is preceded with 0. E and f. Used with e. The value is not truncated even if the result is larger. (space) If no sign is going to be written. Right justification is the default (see width sub-specifier). 0x or 0X respectively for values different than zero. a blank space is inserted before the value. If the value to be printed is shorter than this number. By default. width Description (number) Minimum number of characters to be printed. but as an additional integer value argument preceding the argument that has to be 145 . only negative numbers are preceded with a -ve sign. it forces the written output to contain a decimal point even if no digits would follow. no decimal point is written. By default. # Used with o. + Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. * The width is not specified in the format string. Used with g or G the result is the same as with e or E but trailing zeros are not removed. the result is padded with blank spaces.

number For integer specifiers (d. If the period is specified without an explicit value for precision. the total number of characters written is returned otherwise. X): precision specifies the minimum number of digits to be written. E. If the value to be written is shorter than this number. d. f. x and X). g and G). and as a wide character or wide character string for specifiers c and s. i.precision Description . When no precision is specified. the result is padded with leading zeros. Return Value If successful. a negative number is returned.  arg -. . For s: this is the maximum number of characters to be printed. Example The following example shows the usage of vfprintf() function. This should be initialized by the va_start macro defined in <stdarg>. x and X). u. o. x. 0 is assumed. u. length Description h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i. l The argument is interpreted as a long int or unsigned long int for integer specifiers (i.C Standard Library formatted. u. For g and G specifiers: This is the maximum number of significant digits to be printed. L The argument is interpreted as a long double (only applies to floating point specifiers: e. 146 . .* The precision is not specified in the format string. o. o. A precision of 0 means that no character is written for the value 0. For e. E and f specifiers: this is the number of digits to be printed after the decimal point. the default is 1. For c type: it has no effect. d.An object representing the variable arguments list. but as an additional integer value argument preceding the argument that has to be formatted. The value is not truncated even if the result is longer. By default all characters are printed until the ending null character is encountered.

) { va_list args. fp = fopen("file. format).txt". char *format. args). 10). } Let us compile and run the above program that will open a file file. vfprintf(stream.h> int main () { FILE *fp. WriteFrmtd(fp. va_end(args).. } int main () { FILE *fp.C Standard Library #include <stdio. return(0). . "This is just one argument %d \n". 147 .h> void WriteFrmtd(FILE *stream. fclose(fp)."w").. va_start(args. format.h> #include <stdarg.txt for writing in the current directory and will write the following content: This is just one argument 10 Now let's see the content of the above file using the following program: #include <stdio.

if( feof(fp) ) { break . as explained below: specifier Output c Character 148 . } int vprintf(const char *format. return(0). va_list arg) sends formatted output to stdout using an argument list passed to it. } printf("%c"."r"). va_list arg) Description The C library function int vprintf(const char *format.This is the String that contains the text to be written to buffer. Format tags prototype would be: %[flags][width][. va_list arg) Parameters  format -. int vprintf(const char *format. fp = fopen("file. c). } fclose(fp).precision][length]specifier.C Standard Library int c.txt". It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Declaration Following is the declaration for vprintf() function. while(1) { c = fgetc(fp).

only negative numbers are preceded with a -ve sign. 149 . Right justification is the default (see width sub-specifier). + Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default.C Standard Library d or i Signed decimal integer e Scientific notation (mantissa/exponent) using e character E Scientific notation (mantissa/exponent) using E character f Decimal floating point g Uses the shorter of %e or %f G Uses the shorter of %E or %f o Signed octal s String of characters u Unsigned decimal integer x Unsigned hexadecimal integer X Unsigned hexadecimal integer (capital letters) p Pointer address n Nothing printed % Character flags Description - Left-justify within the given field width. (space) If no sign is going to be written. a blank space is inserted before the value.

x. length Description 150 . u. the result is padded with blank spaces. The value is not truncated even if the result is longer. E and f. If the period is specified without an explicit value for precision. For e. o. Used with e. 0x or 0X respectively for values different than zero. no decimal point is written. . the default is 1. it forces the written output to contain a decimal point even if no digits would follow. Used with g or G the result is the same as with e or E but trailing zeros are not removed. By default all characters are printed until the ending null character is encountered. For c type: it has no effect. The value is not truncated even if the result is larger. but as an additional integer value argument preceding the argument that has to be formatted. E and f specifiers: this is the number of digits to be printed after the decimal point. If the value to be printed is shorter than this number.number For integer specifiers (d. the result is padded with leading zeros.precision Description . For g and G specifiers: This is the maximum number of significant digits to be printed. 0 is assumed.* The precision is not specified in the format string. If the value to be written is shorter than this number. . When no precision is specified. where padding is specified (see width sub-specifier). i. width Description (number) Minimum number of characters to be printed. but as an additional integer value argument preceding the argument that has to be formatted. A precision of 0 means that no character is written for the value 0. By default. x or X specifiers the value is preceded with 0. For s: this is the maximum number of characters to be printed. * The width is not specified in the format string. X): precision specifies the minimum number of digits to be written. 0 Left-pads the number with zeroes (0) instead of spaces.C Standard Library # Used with o. if no digits follow.

E. l The argument is interpreted as a long int or unsigned long int for integer specifiers (i. WriteFrmtd("%d variable %s\n". return(0). va_start(args. d. o. L The argument is interpreted as a long double (only applies to floating point specifiers: e. This should be initialized by the va_start macro defined in <stdarg>.) { va_list args. 2..C Standard Library h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i. o. u. .h> #include <stdarg. } int main () { WriteFrmtd("%d variable argument\n". x and X). va_end(args). Return Value If successful.  arg -. 1). d. Example The following example shows the usage of vprintf() function. "arguments"). u. g and G). vprintf(format. and as a wide character or wide character string for specifiers c and s. args). f.. #include <stdio. the total number of characters written is returned otherwise a negative number is returned. format).h> void WriteFrmtd(char *format. x and X).An object representing the variable arguments list. } 151 .

va_list arg) sends formatted output to a string using an argument list passed to it. int vsprintf(char *str. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and are formatted as requested. va_list arg) Parameters  str -.This is the array of char elements where the resulting string is to be stored. const char *format. Declaration Following is the declaration for vsprintf() function. Format tags prototype: %[flags][width][.C Standard Library Let us compile and run the above program that will produce the following result: 1 variable argument 2 variable arguments int vsprintf(char *str. const char *format. as explained below: specifier Output c Character d or i Signed decimal integer e Scientific notation (mantissa/exponent) using e character E Scientific notation (mantissa/exponent) using E character f Decimal floating point g Uses the shorter of %e or %f G Uses the shorter of %E or %f 152 . const char *format.  format -.This is the C string that contains the text to be written to the str.precision][length]specifier. va_list arg) Description The C library function int vsprintf(char *str.

# Used with o. Used with e.C Standard Library o Signed octal s String of characters u Unsigned decimal integer x Unsigned hexadecimal integer X Unsigned hexadecimal integer (capital letters) p Pointer address n Nothing printed % Character flags Description - Left-justify within the given field width. By default. x or X specifiers the value is preceded with 0. no decimal point is written. 0 Left-pads the number with zeroes (0) instead of spaces. Used with g or G the result is the same as with e or E but trailing zeros are not removed. width Description 153 . a blank space is inserted before the value. if no digits follow. + Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. 0x or 0X respectively for values different than zero. E and f. Right justification is the default (see width sub-specifier). only negative numbers are preceded with a -ve sign. By default. (space) If no sign is going to be written. where padding is specified (see width sub-specifier). it forces the written output to contain a decimal point even if no digits would follow.

X): precision specifies the minimum number of digits to be written. The value is not truncated even if the result is larger. o. x. If the value to be printed is shorter than this number. L The argument is interpreted as a long double (only applies to floating point specifiers: e. This should be initialized by the va_start macro defined in <stdarg>. x and X). A precision of 0 means that no character is written for the value 0. i.number For integer specifiers (d. d. the result is padded with leading zeros. E. l The argument is interpreted as a long int or unsigned long int for integer specifiers (i. the result is padded with blank spaces.An object representing the variable arguments list. d. For c type: it has no effect. the default is 1. x and X). The value is not truncated even if the result is longer. For e. E and f specifiers: this is the number of digits to be printed after the decimal point. .precision Description . u. length Description h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i. 154 .* The precision is not specified in the format string. u. If the period is specified without an explicit value for precision. o. For g and G specifiers: This is the maximum number of significant digits to be printed. * The width is not specified in the format string.C Standard Library (number) Minimum number of characters to be printed.  arg -. and as a wide character or wide character string for specifiers c and s. . o. but as an additional integer value argument preceding the argument that has to be formatted. If the value to be written is shorter than this number. u. but as an additional integer value argument preceding the argument that has to be formatted. f. g and G). For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. 0 is assumed. When no precision is specified.

. aptr). float f = 27. . return(ret). va_start(aptr. otherwise a negative number is returned.h> #include <stdarg. str). Example The following example shows the usage of vsprintf() function. char str[50] = "tutoriaspoint. va_end(aptr). i. } int main() { int i = 5. f.) { va_list aptr. the total number of characters written is returned. format). int ret.C Standard Library Return Value If successful. buffer).. ret = vsprintf(buffer.com". format. printf("%s\n".0. #include <stdio.h> char buffer[80]. } Let us compile and run the above program. this will produce the following result: 155 . int vspfunc(char *format. return(0). vspfunc("%d %f %s".

const char *format.) Description The C library function int fscanf(FILE *stream. int fscanf(FILE *stream. const char *format.) reads formatted input from a stream. See next table.This is the C string that contains one or more of the following items: Whitespace character. . i.) Parameters  stream -.This is the pointer to a FILE object that identifies the stream.. i and n).com int fscanf(FILE *stream.000000 tutoriaspoint. or double (for e.. i and n).C Standard Library 5 27. f and g) for the data pointed by the corresponding additional argument: h : short int (for d. modifiers Specifies a size different from int (in the case of d.e. u and x).. i and n). u and x) or float (in the case of e. Declaration Following is the declaration for fscanf() function.. width This specifies the maximum number of characters to be read in the current reading operation.. f and g) L : long double (for e. f and g) type A character specifying the type of data to be read and how it is expected to be read..  format -. which is explained below: argument Description * This is an optional starting asterisk indicates that the data is to be read from the stream but ignored. u and x) l : long int (for d. const char *format. or unsigned short int (for o. fscanf type specifiers: type Qualifying Input Type of argument 156 . . . it is not stored in the corresponding argument. unsigned int (in the case of o. Non-whitespace character and Format specifiers. A format specifier will be as [=%[*][width][modifiers]type=]. or unsigned long int (for o.

Return Value This function returns the number of input items successfully matched and assigned. char * u Unsigned decimal integer. G Floating point: Decimal number containing a decimal point.sign int * e.C Standard Library c Single character: Reads the next character. f.Depending on the format string. There should be the same number of these arguments as the number of %-tags that expect a value. each containing one value to be inserted instead of each %-tag specified in the format parameter(if any). Example The following example shows the usage of fscanf() function. the function may expect a sequence of additional arguments.sign and optionally followed by the e or E character and a decimal number. This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank. optionally preceded by a + or . If a width different from 1 is specified. Two examples of valid entries are -732. #include <stdio. g. newline and tab). the function reads width characters and stores them in the successive locations of the array passed as argument. E.h> 157 . X Hexadecimal Integer int *  additional arguments -.h> #include <stdlib. char * d Decimal integer: Number optionally preceded with a + or . which can be fewer than provided for. No null character is appended at the end. unsigned int * x.12e4 float * o Octal Integer: int * s String of characters. or even zero in the event of an early matching failure.103 and 7.

. printf("Read Integer |%d|\n". str1. fp = fopen ("file.. fclose(fp).. &year). fscanf(fp. str2[10]. year ). str3 ). fp). } Let us compile and run the above program that will produce the following result: Read String1 |We| Read String2 |are| Read String3 |in| Read Integer |2012| int scanf(const char *format. int year. str3[10]. str2. FILE * fp.C Standard Library int main() { char str1[10]. printf("Read String1 |%s|\n".. . str3. printf("Read String2 |%s|\n". fputs("We are in 2012".) reads formatted input from stdin.txt". 158 .. str1 ). str2 ). printf("Read String3 |%s|\n". rewind(fp). "%s %s %s %d". return(0). "w+").) Description The C library function int scanf(const char *format.

. modifiers Specifies a size different from int (in the case of d. int scanf(const char *format. or double (for e. f and g) type A character specifying the type of data to be read and how it is expected to be read. unsigned int (in the case of o. it is not stored in the corresponding argument. f and g) L : long double (for e. No null character is appended at the end. . If a width different from 1 is specified. i and n). i. or unsigned short int (for o. fscanf type specifiers: type Qualifying Input Type of argument c Single character: Reads the next character. Non-whitespace character and Format specifiers. See next table. f and g) for the data pointed by the corresponding additional argument: h : short int (for d. i and n). A format specifier will be like [=%[*][width][modifiers]type=] as explained below: argument Description * This is an optional starting asterisk indicates that the data is to be read from the stream but ignored. u and x). u and x) l : long int (for d. u and x) or float (in the case of e. or unsigned long int (for o.e.C Standard Library Declaration Following is the declaration for scanf() function. width This specifies the maximum number of characters to be read in the current reading operation. char * 159 ..This is the C string that contains one or more of the following items: Whitespace character.) Parameters  format -. the function reads width characters and stores them in the successive locations of the array passed as argument. i and n).

12e4 float * o Octal Integer: int * s String of characters.h> int main() { char str1[20].103 and 7.sign int * e. G Floating point: Decimal number containing a decimal point. newline and tab). E.sign and optionally followed by the e or E character and a decimal number. str2[30]. the function may expect a sequence of additional arguments. each containing one value to be inserted instead of each %-tag specified in the format parameter. Return Value If successful. #include <stdio. optionally preceded by a + or . if any. Example The following example shows the usage of scanf() function. char * u Unsigned decimal integer. printf("Enter name: ").Depending on the format string. X Hexadecimal Integer int *  additional arguments -. unsigned int * x. f. &str1). the total number of characters written is returned. Two examples of valid entries are -732. otherwise a negative number is returned. g. scanf("%s". There should be the same number of these arguments as the number of %-tags that expect a value.C Standard Library d Decimal integer: Number optionally preceded with a + or . 160 . This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank.

Declaration Following is the declaration for sscanf() function. const char *format.tutorialspoint. const char *format.) Parameters  str -. scanf("%s"...com Entered Name: admin Entered Website: www..) reads formatted input from a string.This is the C string that contains one or more of the following items: Whitespace character. &str2). return(0). Non-whitespace character and Format specifiers A format specifier follows this prototype: [=%[*][width][modifiers]type=] argument Description 161 . const char *format.. str1).C Standard Library printf("Enter your website name: "). str2). ..com int sscanf(const char *str.) Description The C library function int sscanf(const char *str. int sscanf(const char *str..  format -. } Let us compile and run the above program that will produce the following result in interactive mode: Enter name: admin Enter your website name: www.This is the C string that the function processes as its source to retrieve the data. printf("Entered Name: %s\n". . . printf("Entered Website:%s".tutorialspoint.

unsigned int (in the case of o. width This specifies the maximum number of characters to be read in the current reading operation. modifiers Specifies a size different from int (in the case of d. If a width different from 1 is specified. or unsigned short int (for o.sign and optionally followed by the e or E character and a decimal number. f. the function reads width characters and stores them in the successive locations of the array passed as argument. char * d Decimal integer: Number optionally preceded with a + or . or unsigned long int (for o. Two examples of valid entries are -732. i and n). f and g) L : long double (for e. g.e. See next table. f and g) for the data pointed by the corresponding additional argument: h : short int (for d. which indicates that the data is to be read from the stream but ignored. or double (for e.sign int * e. This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank. E. u and x) l : long int (for d. fscanf type specifiers: type Qualifying Input Type of argument c Single character: Reads the next character.C Standard Library * This is an optional starting asterisk. f and g) type A character specifying the type of data to be read and how it is expected to be read. optionally preceded by a + or . u and x). G Floating point: Decimal number containing a decimal point. u and x) or float (in the case of e. No null character is appended at the end.103 and 7. it is not stored in the corresponding argument. newline and char * 162 . i and n). i. i and n).12e4 float * o Octal Integer: int * s String of characters.

an ampersand sign (&). printf("%s %d. sscanf( dtm. "%s %s %d %d". month."%d".h> int main() { int day. the function returns the number of variables filled. unsigned int * x. "Saturday March 25 1989" ). Example The following example shows the usage of sscanf() function. i.e. like: int n. each one pointing to an object of the type specified by their corresponding %-tag within the format string. u Unsigned decimal integer. char weekday[20]. month. X Hexadecimal Integer int *  other arguments -. day.This function expects a sequence of pointers as additional arguments. weekday ).C Standard Library tab).&n). In the case of an input failure before any data could be successfully read. #include <stdio.h> #include <stdlib. EOF is returned. &year ). If you want to store the result of a sscanf operation on a regular variable you should precede its identifier with the reference operator. an additional argument should be specified. } Let us compile and run the above program that will produce the following result: 163 . return(0). year. year. For each format specifier in the format string that retrieves data. strcpy( dtm. sscanf (str. in the same order. weekday. month[20]. Return Value On success. %d = %s\n". dtm[100]. &day.

} do { 164 . if(fp == NULL) { perror("Error in opening file"). Return Value This function returns the character read as an unsigned char cast to an int or EOF on end of file or error. int fgetc(FILE *stream) Parameters  stream -.This is the pointer to a FILE object that identifies the stream on which the operation is to be performed. #include <stdio.txt". int n = 0. Example The following example shows the usage of fgetc() function. fp = fopen("file.C Standard Library March 25. Declaration Following is the declaration for fgetc() function. int c."r"). 1989 = Saturday int fgetc(FILE *stream) Description The C library function int fgetc(FILE *stream) gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream.h> int main () { FILE *fp. return(-1).

we have a text file file.This is the pointer to an array of chars where the string read is stored. the newline character is read. } Let us assume. whichever comes first. Usually. Declaration Following is the declaration for fgets() function. which has the following content. 165 . FILE *stream) Parameters  str -. the length of the array passed as str is used. }while(1). This file will be used as an input for our example program: We are in 2012 Now.txt. int n. c). It stops when either (n-1) characters are read. return(0). FILE *stream) Description The C library function char *fgets(char *str. if( feof(fp) ) { break .This is the maximum number of characters to be read (including the final null-character).  n -. FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str.  stream -.This is the pointer to a FILE object that identifies the stream where characters are read from. fclose(fp). int n. or the end-of-file is reached. } printf("%c". int n. char *fgets(char *str. let us compile and run the above program that will produce the following result: We are in 2012 char *fgets(char *str.C Standard Library c = fgetc(fp).

the function returns the same str parameter. "r").C Standard Library Return Value On success. } fclose(fp). the contents of str remain unchanged and a null pointer is returned. char str[60]. a null pointer is returned. return(-1). /* opening file for reading */ fp = fopen("file.txt" .h> int main() { FILE *fp. If an error occurs. if(fp == NULL) { perror("Error opening file"). Example The following example shows the usage of fgets() function. 60. we have a text file file. fp)!=NULL ) { /* writing content to stdout */ puts(str).txt. } if( fgets (str. #include <stdio. let us compile and run the above program that will produce the following result: 166 . return(0). If the End-of-File is encountered and no characters have been read. which has the following content. } Let us assume. This file will be used as an input for our example program: We are in 2012 Now.

ch <= 100. FILE *stream) Description The C library function int fputc(int char.txt". #include <stdio. This is passed as its int promotion. FILE *stream) Parameters  char -.  stream -. fp). Declaration Following is the declaration for fputc() function. FILE *stream) writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream. "w+"). int ch. EOF is returned and the error indicator is set.This is the pointer to a FILE object that identifies the stream where the character is to be written. Example The following example shows the usage of fputc() function. 167 . fp = fopen("file. } fclose(fp). Return Value If there are no errors. If an error occurs. the same character that has been written is returned.h> int main () { FILE *fp.C Standard Library We are in 2012 int fputc(int char. int fputc(int char. for( ch = 33 . ch++ ) { fputc(ch.This is the character to be written.

FILE *stream) Description The C library function int fputs(const char *str. int c. while(1) { c = fgetc(fp).txt in the current directory. } printf("%c".-. Declaration Following is the declaration for fputs() function. FILE *stream) writes a string to the specified stream up to but not including the null character.<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd Now let's see the content of the above file using the following program: #include <stdio./0123456789:. if( feof(fp) ) { break . fp = fopen("file. return(0). } fclose(fp).h> int main () { FILE *fp."r"). which will have following content: !"#$%&'()*+. 168 . } Let us compile and run the above program that will create a file file.C Standard Library return(0).txt". c). } int fputs(const char *str.

C Standard Library int fputs(const char *str.h> int main () { FILE *fp. Return Value This function returns a non-negative value. fclose(fp). FILE *stream) Parameters  str -. #include <stdio.This is a system programming language. } Let us compile and run the above program. fp). or else on error it returns EOF. fp). fputs("This is a system programming language.txt with the following content: This is c programming.".This is an array containing the null-terminated sequence of characters to be written. fputs("This is c programming. this will create a file file.h> int main () { 169 . fp = fopen("file. "w+").This is the pointer to a FILE object that identifies the stream where the string is to be written. Example The following example shows the usage of fputs() function.  stream -.txt". Now let's see the content of the above file using the following program: #include <stdio.". return(0).

} int getc(FILE *stream) Description The C library function int getc(FILE *stream) gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream. } printf("%c".h> 170 . while(1) { c = fgetc(fp). } fclose(fp). #include<stdio. c). Example The following example shows the usage of getc() function. int getc(FILE *stream) Parameters  stream -. Declaration Following is the declaration for getc() function. Return Value This function returns the character read as an unsigned char cast to an int or EOF on end of file or error. int c.C Standard Library FILE *fp. return(0). fp = fopen("file.txt".This is the pointer to a FILE object that identifies the stream on which the operation is to be performed. if( feof(fp) ) { break ."r").

#include <stdio. int getchar(void) Parameters  NA Return Value This function returns the character read as an unsigned char cast to an int or EOF on end of file or error.h> 171 . stdout). This is equivalent to getc with stdin as its argument. return(0). putc(c. printf("Enter character: "). Example The following example shows the usage of getchar() function. printf("Character entered: "). } Let us compile and run the above program that will produce the following result: Enter character: a Character entered: a int getchar(void) Description The C library function int getchar(void) gets a character (an unsigned char) from stdin.C Standard Library int main() { char c. Declaration Following is the declaration for getchar() function. c = getc(stdin).

c = getchar().This is the pointer to an array of chars where the C string is stored. } Let us compile and run the above program that will produce the following result: Enter character: a Character entered: a char *gets(char *str) Description The C library function char *gets(char *str) reads a line from stdin and stores it into the string pointed to by str. char *gets(char *str) Parameters  str -. and NULL on error or when end of file occurs. return(0). It stops when either the newline character is read or when the end-of-file is reached. Example The following example shows the usage of gets() function.C Standard Library int main () { char c. Return Value This function returns str on success. printf("Enter character: "). while no characters have been read. Declaration Following is the declaration for gets() function.h> 172 . printf("Character entered: "). putchar(c). whichever comes first. #include <stdio.

com int putc(int char.C Standard Library int main() { char str[50]. FILE *stream) Parameters  char -.  stream -. The character is passed as its int promotion. str). gets(str). Return Value This function returns the character written as an unsigned char cast to an int or EOF on error.This is the character to be written. FILE *stream) writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream. FILE *stream) Description The C library function int putc(int char. 173 . } Let us compile and run the above program that will produce the following result: Enter a string : tutorialspoint. printf("Enter a string : "). return(0). printf("You entered: %s". int putc(int char.This is the pointer to a FILE object that identifies the stream where the character is to be written. Declaration Following is the declaration for putc() function.com You entered: tutorialspoint. Example The following example shows the usage of putc() function.

C Standard Library #include <stdio. while(1) { c = fgetc(fp). ch <= 100.h> int main () { FILE *fp.txt".-. fp). } Let us compile and run the above program that will create a file file."r").<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd Now let's see the content of the above file using the following program: #include <stdio.txt in the current directory which will have following content: !"#$%&'()*+. if( feof(fp) ) { 174 . } fclose(fp). "w")./0123456789:. for( ch = 33 . fp = fopen("file. ch++ ) { putc(ch. fp = fopen("file.h> int main () { FILE *fp.txt". int c. return(0). int ch.

This is passed as its int promotion. Example The following example shows the usage of putchar() function. ch <= 'Z' . } 175 . Return Value This function returns the character written as an unsigned char cast to an int or EOF on error. int putchar(int char) Parameters  char -. c). } printf("%c". } fclose(fp). Declaration Following is the declaration for putchar() function.h> int main () { char ch. ch++) { putchar(ch).This is the character to be written.C Standard Library break . for(ch = 'A' . #include <stdio. } int putchar(int char) Description The C library function int putchar(int char) writes a character (an unsigned char) specified by the argument char to stdout. return(0).

Example The following example shows the usage of puts() function. A newline character is appended to the output. non-negative value is returned. puts(str2). char str2[15]. 176 .This is the C string to be written. #include <stdio.C Standard Library return(0). int puts(const char *str) Parameters  str -. "tutorialspoint"). } Let us compile and run the above program that will produce the following result: ABCDEFGHIJKLMNOPQRSTUVWXYZ int puts(const char *str) Description The C library function int puts(const char *str) writes a string to stdout up to but not including the null character. Return Value If successful. Declaration Following is the declaration for puts() function. On error. strcpy(str2. the function returns EOF. "compileonline"). puts(str1).h> int main() { char str1[15]. strcpy(str1.h> #include <string.

FILE *stream) pushes the character char (an unsigned char) onto the specified stream so that the this is available for the next read operation. int c. char buffer [256]. This is passed as its int promotion. int ungetc(int char. #include <stdio. FILE *stream) Parameters  char -. 177 . FILE *stream) Description The C library function int ungetc(int char.This is the character to be put back.  stream -. Declaration Following is the declaration for ungetc() function.C Standard Library return(0). Return Value If successful. EOF is returned and the stream remains unchanged.This is the pointer to a FILE object that identifies an input stream. Example The following example shows the usage of ungetc() function.h> int main () { FILE *fp. it returns the character that was pushed back otherwise. } Let us compile and run the above program to produce the following result: tutorialspoint compileonline int ungetc(int char.

255. return(-1). This file will be used as an input for our example program: this is tutorials point !c standard library !library functions and macros Now let us compile and run the above program that will produce the following result: this is tutorials point +c standard library +library functions and macros 178 . "r"). /* replace ! with + */ if( c == '!' ) { ungetc ('+'. } fgets(buffer. we have a text file file. stdout). } while(!feof(fp)) { c = getc (fp). } Let us assume. } else { ungetc(c. which contains the following data. } return(0).txt".C Standard Library fp = fopen("file. fp). fp). fputs(buffer. fp). if( fp == NULL ) { perror("Error in opening file").txt.

/* now let's try to open same file */ fp = fopen("file. First the string str is printed. Example The following example shows the usage of perror() function.This is the C string containing a custom message to be printed before the error message itself.txt").txt".h> int main () { FILE *fp. } fclose(fp). return(-1). Return Value This function does not return any value. Declaration Following is the declaration for perror() function. 179 .txt". "newfile. /* first rename if there is any file */ rename("file. if( fp == NULL ) { perror("Error: "). "r"). followed by a colon then a space. return(0). #include <stdio.C Standard Library void perror(const char *str) Description The C library function void perror(const char *str) prints a descriptive error message to stderr. void perror(const char *str) Parameters  str -.

C Standard Library } Let us compile and run the above program that will produce the following result because we are trying to open a file which does not exist: Error: : No such file or directory 180 .

2 EXIT_FAILURE 181 .h header defines four variable types. 2 integral type and is the result of wchar_t This is an integer type of the size of a wide character constant.h: S.h: S. Library Variables Following are the variable types defined in the header stdlib. and various functions for performing general functions. 4 ldiv_t This is the structure returned by the ldiv function. <STDLIB. 3 div_t This is the structure returned by the div function.N.H> C Standard Library Introduction The stdlib. Variable & Description 1 size_t This is the unsigned the sizeof keyword.13. Library Macros Following are the macros defined in the header stdlib. Macro & Description 1 NULL This macro is the value of a null pointer constant.N. several macros.

by the argument str to a long integer (type long int). Library Functions Following are the functions defined in the header stdio. by the argument str to a floating-point number (type double). 3 long int atol(const char *str) Converts the string pointed to. by the argument str to a long integer (type long int).h: S. 4 double strtod(const char *str. char **endptr. by the argument str to a floating-point number (type double). 182 . by the argument str to an integer (type int). 5 long int strtol(const char *str. char **endptr) Converts the string pointed to.C Standard Library This is the value for the exit function to return in case of failure. Function & Description 1 double atof(const char *str) Converts the string pointed to. 4 RAND_MAX This macro is the maximum value returned by the rand function. 5 MB_CUR_MAX This macro is the maximum number of bytes in a multi-byte character set which cannot be larger than MB_LEN_MAX.N. 2 int atoi(const char *str) Converts the string pointed to. 3 EXIT_SUCCESS This is the value for the exit function to return in case of success. int base) Converts the string pointed to.

13 void exit(int status) Causes the program to terminate normally. char **endptr. malloc. 14 char *getenv(const char *name) Searches for the environment string pointed to by name and returns the associated value to the string. 15 int system(const char *string) The command specified by string is passed to the host environment to be executed by the command processor. 9 void *malloc(size_t size) Allocates the requested memory and returns a pointer to it. 7 void *calloc(size_t nitems. int base) Converts the string pointed to. 8 void free(void *ptr Deallocates the memory previously allocated by a call to calloc.C Standard Library 6 unsigned long int strtoul(const char *str. orrealloc. 12 int atexit(void (*func)(void)) Causes the specified function func to be called when the program terminates normally. size_t size) Attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc. 183 . 11 void abort(void) Causes an abnormal program termination. size_t size) Allocates the requested memory and returns a pointer to it. by the argument str to an unsigned long integer (type unsigned long int). 10 void *realloc(void *ptr.

int (*compar)(const void *. 17 void qsort(void *base. 18 int abs(int x) Returns the absolute value of x. long int denom) Divides numer (numerator) by denom (denominator). size_t size. 19 div_t div(int numer. int denom) Divides numer (numerator) by denom (denominator). size_t nitems. const char *str. size_t size. const char *str. size_t nitems. size_t n) Returns the length of a multibyte character pointed to by the argument str. 24 int mblen(const char *str. 22 int rand(void) Returns a pseudo-random number in the range of 0 to RAND_MAX. 26 int mbtowc(whcar_t *pwc. 20 long int labs(long int x) Returns the absolute value of x. 23 void srand(unsigned int seed) This function seeds the random number generator used by the function rand. 21 ldiv_t ldiv(long int numer. int (*compar)(const void *. 25 size_t mbstowcs(schar_t *pwcs. const void *)) Performs a binary search. const void*)) Sorts an array. size_t n) Converts the string of multibyte characters pointed to by the argument str to the array pointed to by pwcs. const void *base.C Standard Library 16 void *bsearch(const void *key. size_t n) 184 .

27 size_t wcstombs(char *str. wchar_t wchar) Examines the code which corresponds to a multibyte character given by the argument wchar. #include <stdio.This is the string having the representation of a floating-point number.h> #include <string. Declaration Following is the declaration for atof() function. it returns zero (0.C Standard Library Examines the multibyte character pointed to by the argument str. double atof(const char *str) Parameters  str -. Return Value This function returns the converted floating point number as a double value. If no valid conversion could be performed. size_t n) Converts the codes stored in the array pwcs to multibyte characters and stores them in the string str. 28 int wctomb(char *str. double atof(const char *str) Description The C library function double atof(const char *str) converts the string argument str to a floating-point number (type double).0). Example The following example shows the usage of atof() function. 185 . const wchar_t *pwcs.h> #include <stdlib. char str[20].h> int main() { float val.

str. Float value = 0.000000 String value = tutorialspoint. char *str) converts the string Declaration Following is the declaration for atoi() function.This is the string representation of an integral number.000000 int atoi(const char *str) Description The C library function int atoi(const argument str to an integer (type int). #include <stdio. printf("String value = %s. printf("String value = %s.com. it returns zero.h> #include <string. int atoi(const char *str) Parameters  str -. val = atof(str). val). Float value = %f\n". "98993489"). val). return(0). val = atof(str). If no valid conversion could be performed. Return Value This function returns the converted integral number as an int value.C Standard Library strcpy(str. Float value = 98993488.h> #include <stdlib. "tutorialspoint.h> 186 . strcpy(str. str.com"). Float value = %f\n". } Let us compile and run the above program that will produce the following result: String value = 98993489. Example The following example shows the usage of atoi() function.

str. Example 187 . Int value = 0 long int atol(const char *str) Description The C library function long int atol(const char *str) converts the string argument str to a long integer (type long int). Declaration Following is the declaration for atol() function. "tutorialspoint. Int value = %d\n". } Let us compile and run the above program that will produce the following result: String value = 98993489. val).This is the string containing the representation of an integral number. printf("String value = %s. str. Int value = %d\n". If no valid conversion could be performed. val = atoi(str).C Standard Library int main() { int val. strcpy(str. Return Value This function returns the converted integral number as a long int. it returns zero. "98993489"). val). char str[20]. strcpy(str. printf("String value = %s. val = atoi(str). Int value = 98993489 String value = tutorialspoint.com.com"). long int atol(const char *str) Parameters  str -. return(0).

If endptr is not NULL.C Standard Library The following example shows the usage of atol() function. double strtod(const char *str. val = atol(str). "98993489"). } Let us compile and run the above program. Long value = 98993489 String value = tutorialspoint. strcpy(str. "tutorialspoint. Long value = 0 double strtod(const char *str. printf("String value = %s. char **endptr) converts the string pointed to by the argument str to a floating-point number (type double). char str[20].h> int main() { long val. Long value = %ld\n". a pointer to the character after the last character used in the conversion is stored in the location referenced by endptr.h> #include <stdlib. str. strcpy(str. Declaration Following is the declaration for strtod() function. val = atol(str). return(0). Long value = %ld\n".com").h> #include <string. char **endptr) Description The C library function double strtod(const char *str. str. printf("String value = %s.com. char **endptr) 188 . val). #include <stdio. this will produce the following result: String value = 98993489. val).

int base) Description The C library function long int strtol(const char *str. &ptr). char **endptr.This is the reference to an already allocated object of type char*.This is the value to be converted to a string. else zero value (0.h> int main() { char str[30] = "20. or be the special value 0. 189 .0) is returned. char *ptr.303000 String part is | This is test| long int strtol(const char *str. ret). double ret. printf("String part is |%s|". Return Value This function returns the converted floating point number as a double value. return(0). ret = strtod(str. ptr). Example The following example shows the usage of strtod() function.C Standard Library Parameters  str -. which must be between 2 and 36 inclusive. printf("The number(double) is %lf\n". char **endptr.30300 This is test". int base) converts the initial part of the string in str to a long int value according to the given base. } Let us compile and run the above program that will produce the following result: The number(double) is 20. whose value is set by the function to the next character in str after the numerical value. #include <stdio.h> #include <stdlib.  endptr -.

This is the reference to an object of type char*. int base) Parameters  str -.h> #include <stdlib. } Let us compile and run the above program that will produce the following result: The number(unsigned long integer) is 2030300 String part is | This is test| 190 . 10). char **endptr. long ret.  base -.C Standard Library Declaration Following is the declaration for strtol() function.h> int main() { char str[30] = "2030300 This is test". #include <stdio. or be the special value 0.This is the base.This is the string containing the representation of an integral number. ret). Example The following example shows the usage of strtol() function. &ptr. char *ptr. Return Value This function returns the converted integral number as a long int value. ptr). else zero value is returned. printf("String part is |%s|".  endptr -. return(0). long int strtol(const char *str. which must be between 2 and 36 inclusive. ret = strtol(str. whose value is set by the function to the next character in str after the numerical value. printf("The number(unsigned long integer) is %ld\n".

h> int main() { char str[30] = "2030300 This is test".  endptr -. #include <stdio.C Standard Library unsigned long int strtoul(const char *str. return(0). printf("String part is |%s|". long ret.  base -.This is the reference to an object of type char*. printf("The number(unsigned long integer) is %lu\n". whose value is set by the function to the next character in str after the numerical value. ptr). a zero value is returned. ret). char *ptr.h> #include <stdlib. int base) function converts the initial part of the string in str to an unsigned long int value according to the given base.This is the base. ret = strtoul(str. Declaration Following is the declaration for strtoul() function. Return Value This function returns the converted integral number as a long int value. int base) Parameters  str -. or be the special value 0. char **endptr. 10).This is the string containing the representation of an unsigned integral number. or be the special value 0. 191 . &ptr. char **endptr. char **endptr. which must be between 2 and 36 inclusive. unsigned long int strtoul(const char *str. int base) Description The C library function unsigned long int strtoul(const char *str. which must be between 2 and 36 inclusive. If no valid conversion could be performed. Example The following example shows the usage of strtoul() function.

size_t size) Parameters  nitems -. size_t size) allocates the requested memory and returns a pointer to it. #include <stdio.&n). Declaration Following is the declaration for calloc() function. The difference in malloc and calloc is that malloc does not set the memory to zero whereas calloc sets allocated memory to zero. n.h> #include <stdlib.C Standard Library } Let us compile and run the above program that will produce the following result: The number(unsigned long integer) is 2030300 String part is | This is test| void *calloc(size_t nitems. scanf("%d".This is the size of elements.  size -. size_t size) Description The C library function void *calloc(size_t nitems. Return Value This function returns a pointer to the allocated memory. or NULL if the request fails. printf("Number of elements to be entered:").h> int main() { int i.This is the number of elements to be allocated. void *calloc(size_t nitems. Example The following example shows the usage of calloc() function. 192 . int *a.

for( i=0 . for( i=0 .C Standard Library a = (int*)calloc(n. } Let us compile and run the above program that will produce the following result: Number of elements to be entered:3 Enter 3 numbers: 22 55 14 The numbers entered are: 22 55 14 void free(void *ptr) Description The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc.&a[i]). void free(void *ptr) Parameters  ptr -. i++ ) { scanf("%d". printf("Enter %d numbers:\n". } printf("The numbers entered are: ").a[i]). } return(0).n). If a null pointer is passed as argument. i < n .This is the pointer to a memory block previously allocated with malloc. i < n . no action occurs. calloc or realloc to be deallocated. i++ ) { printf("%d ". Declaration Following is the declaration for free() function. or realloc. malloc. sizeof(int)). 193 .

/* Initial memory allocation */ str = (char *) malloc(15).h> #include <stdlib. #include <stdio.C Standard Library Return Value This function does not return any value. 25). Address = %u\n". Address = %u\n".com").com. /* Reallocating memory */ str = (char *) realloc(str. Address = 355090448 String = tutorialspoint. strcat(str. /* Deallocate allocated memory */ free(str). } Let us compile and run the above program that will produce the following result: String = tutorialspoint. strcpy(str.h> int main() { char *str. return(0). printf("String = %s. "tutorialspoint"). str. str). Address = 355090448 void *malloc(size_t size) Description 194 . str). printf("String = %s. str. ". Example The following example shows the usage of free() function.

return(0). /* Initial memory allocation */ str = (char *) malloc(15). Declaration Following is the declaration for malloc() function. printf("String = %s. ". Example The following example shows the usage of malloc() function.This is the size of the memory block.h> #include <stdlib. #include <stdio. str. free(str). "tutorialspoint"). str). Address = %u\n". /* Reallocating memory */ str = (char *) realloc(str. Address = %u\n". } 195 . str).C Standard Library The C library function void *malloc(size_t size) allocates the requested memory and returns a pointer to it. strcat(str.h> int main() { char *str. printf("String = %s. str. Return Value This function returns a pointer to the allocated memory.com"). in bytes. or NULL if the request fails. 25). void *malloc(size_t size) Parameters  size -. strcpy(str.

This is the pointer to a memory block previously allocated with malloc. size_t size) Description The C library function void *realloc(void *ptr. size_t size) Parameters  ptr -. #include <stdio. calloc or realloc to be reallocated. If this is NULL.com. Return Value This function returns a pointer to the newly allocated memory.  size -. strcpy(str. void *realloc(void *ptr.h> #include <stdlib. the memory block pointed by ptr is deallocated and a NULL pointer is returned. /* Initial memory allocation */ str = (char *) malloc(15). Address = 355090448 String = tutorialspoint.This is the new size for the memory block. size_t size) attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc. or NULL if the request fails. Address = 355090448 void *realloc(void *ptr.h> int main() { char *str. "tutorialspoint").C Standard Library Let us compile and run the above program that will produce the following result: String = tutorialspoint. Declaration Following is the declaration for realloc() function. If it is 0 and ptr points to an existing block of memory. Example The following example shows the usage of realloc() function. in bytes. a new block is allocated and a pointer to it is returned by the function. 196 .

Address = %u\n". Address = %u\n". Declaration Following is the declaration for abort() function. str. Example The following example shows the usage of abort() function.h> int main () 197 . void abort(void) Parameters  NA Return Value This function does not return any value.h> #include <stdlib.com"). free(str). Address = 355090448 String = tutorialspoint.C Standard Library printf("String = %s. ". str). strcat(str. return(0). /* Reallocating memory */ str = (char *) realloc(str. } Let us compile and run the above program that will produce the following result: String = tutorialspoint. printf("String = %s. 25). str). #include <stdio. str.com. Address = 355090448 void abort(void) Description The C library function void abort(void) aborts the program execution and comes out directly from the place of the call.

which does not exist: Going to open nofile.C Standard Library { FILE *fp.txt\n").txt Going to abort the program Aborted (core dumped) int atexit(void (*func)(void)) Description The C library function int atexit(void (*func)(void)) causes the specified function func to be called when the program terminates.txt file. } Let us compile and run the above program that will produce the following result when it tries to open nofile.txt". } printf("Going to close nofile."r" ). fclose(fp). Return Value 198 . fp = fopen( "nofile. printf("Going to open nofile. if(fp == NULL) { printf("Going to abort the program\n"). abort(). Declaration Following is the declaration for atexit() function. You can register your termination function anywhere you like. but it will be called at the time of the program termination.txt\n"). int atexit(void (*func)(void)) Parameters  func -. return(0).This is the function to be called at the termination of the program.

\n"). } Let us compile and run the above program that will produce the following result: Starting main program. Example The following example shows the usage of atexit() function.. Exiting main program.. printf("Starting main program. printf("Exiting main program. } int main () { /* register the termination function */ atexit(functionA ).... Any open file descriptors belonging to the process are closed and any children of the process are inherited by process 1..\n"). 199 .C Standard Library This function returns a zero value if the function is registered successfully. otherwise a non-zero value is returned if it is failed. return(0). This is functionA void exit(int status) Description The C library function void exit(int status) terminates the calling process immediately... and the process parent is sent a SIGCHLD signal.h> #include <stdlib. init.h> void functionA () { printf("This is functionA\n"). #include <stdio.

Return Value This function does not return any value.h> #include <stdlib. Exiting the program.. void exit(int status) Parameters  status -.. Example The following example shows the usage of exit() function. #include <stdio....This is the status value returned to the parent process... 200 .\n")..C Standard Library Declaration Following is the declaration for exit() function.. exit(0)...\n")... printf("End of the program. printf("Exiting the program.. by name and returns the associated value to the string. char *getenv(const char *name) Description The C library function char *getenv(const char *name) searches for the environment string pointed to.h> int main () { printf("Start of the program.\n"). return(0).. } Let us compile and run the above program that will produce the following result: Start of the program.

#include <stdio. Example The following example shows the usage of getenv() function. Return Value This function returns a null-terminated string with the value of the requested environment variable. or NULL if that environment variable does not exist. printf("HOME : %s\n". getenv("HOME")).h> #include <stdlib.h> int main () { printf("PATH : %s\n". getenv("ROOT")). char *getenv(const char *name) Parameters  name -. getenv("PATH")). return(0). printf("ROOT : %s\n".C Standard Library Declaration Following is the declaration for getenv() function. } Let us compile and run the above program that will produce the following result: PATH : /sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin HOME : / ROOT : (null) int system(const char *string) Description The C library function int system(const char *command) passes the command name or program name specified by command to the host environment to be executed by the command processor and returns after the command has been completed. 201 .This is the C string containing the name of the requested variable.

This is the C string containing the name of the requested variable.1 apache apache 0 Aug 22 05:28 mod_mono_server_asp rw-----. } Let us compile and run the above program that will produce the following result on my unix machine: drwxr-xr-x 2 apache apache 4096 Aug 22 07:25 hsperfdata_apache drwxr-xr-x 2 railo railo 4096 Aug 21 18:48 hsperfdata_railo rw-----. and the return status of the command otherwise. int system(const char *command) Parameters  command -. Return Value The value returned is -1 on error.1 apache apache 8 Aug 21 18:48 mod_mono_dashboard_XXGLOBAL_1 rw-----. #include <stdio.h> #include <string.C Standard Library Declaration Following is the declaration for system() function. "ls -l" ).h> int main () { char command[50]. strcpy( command. system(command).1 apache apache 0 Aug 21 18:48 mod_mono_server_global 202 .1 apache apache 8 Aug 21 18:48 mod_mono_dashboard_asp_2 srwx---.1 apache apache 0 Aug 22 05:28 mod_mono_server_asp_1280495620 srwx---. Example The following example shows the usage of system() function to list down all the files and directories in the current directory under unix machine. return(0).

size_t nitems. #include <stdio.c void *bsearch(const void *key. "dir" ).h> #include <string. by key. for a member that matches the object pointed to. const void *)) function searches an array of nitems objects. int (*compar)(const void *. the initial member of which is pointed to by base. const void *base. const void *)) Description The C library function void *bsearch(const void *key. Declaration Following is the declaration for bsearch() function.h> int main () { char command[50].doc sachin saurav file. } Let us compile and run the above program that will produce the following result on my windows machine: a. The size of each member of the array is specified by size. size_t nitems. size_t size. const void *base. return(0). system(command).C Standard Library The following example shows the usage of system() function to list down all the files and directories in the current directory under windows machine. The contents of the array should be in ascending sorted order according to the comparison function referenced by compar. 203 . strcpy( command. size_t size.txt amit. int (*compar)(const void *.

const void * b) { return ( *(int*)a .This is the number of elements in the array pointed by base. } int values[] = { 5.  size -.This is the pointer to the object that serves as key for the search.*(int*)b ).  nitems -. /* using bsearch() to find value 32 in the array */ item = (int*) bsearch (&key. 5.This is the pointer to the first object of the array where the search is performed. size_t nitems.C Standard Library void *bsearch(const void *key. const void *base.  base -.  compar -. size_t size. type-casted as a void*.h> #include <stdlib. Example The following example shows the usage of bsearch() function. type-casted as a void*. 20. Return Value This function returns a pointer to an entry in the array that matches the search key. If key is not found. int (*compar)(const void *. 29.h> int cmpfunc(const void * a. a NULL pointer is returned. sizeof (int).This is the size in bytes of each element in the array. values.This is the function that compares two elements. #include <stdio. int main () { int *item. cmpfunc). int key = 32. 63 }. const void *)) Parameters  key -. if( item != NULL ) 204 . 32.

} else { printf("Item = %d could not be found\n". Declaration Following is the declaration for qsort() function. #include <stdio. const void*)) Parameters  base -. size_t nitems. size_t nitems. void qsort(void *base.  nitems -.This is the function that compares two elements. size_t nitems.h> 205 . size_t size. Example The following example shows the usage of qsort() function.C Standard Library { printf("Found item = %d\n". int (*compar)(const void *. int (*compar)(const void *.This is the pointer to the first element of the array to be sorted. } Let us compile and run the above program that will produce the following result: Found item = 32 void qsort(void *base. const void*)) Description The C library function void qsort(void *base.  size -. size_t size.  compar -.This is the size in bytes of each element in the array. Return Value This function does not return any value. int (*compar)(const void *.This is the number of elements in the array pointed by base. *item). *item). } return(0). const void*)) sorts an array. size_t size.

*(int*)b ). 25 }. n < 5. } int main() { int n. 100. for( n = 0 . } return(0). 56. n++ ) { printf("%d ". 2. values[n]). values[n]).h> int values[] = { 88. 5. } Let us compile and run the above program that will produce the following result: Before sorting the list is: 88 56 100 2 25 After sorting the list is: 2 25 56 88 100 206 . sizeof(int). printf("Before sorting the list is: \n"). n++ ) { printf("%d ". cmpfunc). int cmpfunc (const void * a. const void * b) { return ( *(int*)a . } qsort(values. printf("\nAfter sorting the list is: \n"). for( n = 0 . n < 5.C Standard Library #include <stdlib.

h> int main () { int a. a). a = abs(5). Declaration Following is the declaration for abs() function.This is the integral value. printf("value of a = %d\n". b = abs(-10). b.h> #include <stdlib. this will produce the following result: value of a = 5 value of b = 10 207 .C Standard Library int abs(int x) Description The C library function int abs(int x) returns the absolute value of int x. } Let us compile and run the above program. b). #include <stdio. Example The following example shows the usage of abs() function. return(0). int abs(int x) Parameters  x -. printf("value of b = %d\n". Return Value This function returns the absolute value of x.

printf("Quotient part of (27/ 4) = %d\n". int denom) Description The C library function div_t div(int (numerator) by denom (denominator).rem). output = div(27. printf("Remainder part of (27/4) = %d\n".This is the denominator.This is the numerator. return(0). div_t div(int numer.  denom -. Return Value This function returns the value in a structure defined in <cstdlib>.rem). output. 4). 3). output = div(27. } Let us compile and run the above program that will produce the following result: 208 .h> int main() { div_t output. printf("Remainder part of (27/3) = %d\n".h> #include <stdlib. #include <stdio. which has two members. output. output.quot). int rem. printf("Quotient part of (27/ 3) = %d\n". int denom) Parameters  numer -. output. int denom) divides numer Declaration Following is the declaration for div() function. Example The following example shows the usage of div() function. numer.C Standard Library div_t div(int numer. For div_t: int quot.quot).

b = labs(-1005090L). printf("Value of a = %ld\n". a). a = labs(65987L). #include <stdio. return(0).b.h> int main () { long int a.C Standard Library Quotient part of (27/ 4) = 6 Remainder part of (27/4) = 3 Quotient part of (27/ 3) = 9 Remainder part of (27/3) = 0 long int labs(long int x) Description The C library function long int labs(long int x) returns the absolute value of x. b).h> #include <stdlib. } 209 . printf("Value of b = %ld\n". long int labs(long int x) Parameters  x -. Declaration Following is the declaration for labs() function. Return Value This function returns the absolute value of x. Example The following example shows the usage of labs() function.This is the integral value.

quot). 210 . Return Value This function returns the value in a structure defined in <cstdlib>. For ldiv_t: long quot.h> int main () { ldiv_t output. output. div_t div(long int numer. output. long int denom) Description The C library function div_t div(long int numer.C Standard Library Let us compile and run the above program that will produce the following result: Value of a = 65987 Value of b = 1005090 ldiv_t ldiv(long int numer. 30000L).h> #include <stdlib. Example The following example shows the usage of ldiv() function. Declaration Following is the declaration for ldiv() function.This is the denominator. long int denom) divides numer (numerator) by denom (denominator).This is the numerator. printf("Remainder = %ld\n".rem). return(0).  denom -. long int denom) Parameters  numer -. long rem. which has two members. output = ldiv(100000L. #include <stdio. printf("Quotient = %ld\n".

211 . n = 5. RAND_MAX is a constant whose default value implementations but it is granted to be at least 32767. may vary between Declaration Following is the declaration for rand() function. time_t t. Example The following example shows the usage of rand() function. #include <stdio.h> int main() { int i. int rand(void) Parameters  NA Return Value This function returns an integer value between 0 and RAND_MAX. /* Intializes random number generator */ srand((unsigned) time(&t)). n.h> #include <stdlib.C Standard Library } Let us compile and run the above program that will produce the following result: Quotient = 3 Remainder = 10000 int rand(void) Description The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX.

C Standard Library /* Print 5 random numbers from 0 to 49 */ for( i = 0 . i < n . Declaration Following is the declaration for srand() function. Return Value This function does not return any value.This is an integer value to be used as seed by the pseudo-random number generator algorithm. } Let us compile and run the above program that will produce the following result: 38 45 29 29 47 void srand(unsigned int seed) Description The C library function void srand(unsigned int seed) seeds the random number generator used by the function rand. } return(0). #include <stdio.h> 212 .h> #include <time. rand() % 50).h> #include <stdlib. i++ ) { printf("%d\n". Example The following example shows the usage of srand() function. void srand(unsigned int seed) Parameters  seed -.

int mblen(const char *str. size_t n) Parameters 213 . i < n . /* Print 5 random numbers from 0 to 50 */ for( i = 0 .C Standard Library int main() { int i. n. by the argument str. i++ ) { printf("%d\n". } return(0). Declaration Following is the declaration for mblen() function. /* Intializes random number generator */ srand((unsigned) time(&t)). size_t n) returns the length of a multi-byte character pointed to. n = 5. rand() % 50). } Let us compile and run the above program that will produce the following result: 38 45 29 29 47 int mblen(const char *str. size_t n) Description The C library function int mblen(const char *str. time_t t.

MB_CUR_MAX). Return Value The mblen() function returns the number of bytes passed from the multi-byte sequence starting at str. if an invalid multi-byte sequence was encountered or if it could not parse a complete multi-byte character. printf( "Length in bytes of multibyte character %x: %u\n".  n -. wchar_t *pwcs = (wchar_t *)malloc( sizeof( wchar_t )). pwc. MB_CUR_MAX ). if a null wide character was recognized. len = mblen( pmb.This is the pointer to the first byte of a multibyte character.h> int main() { int len. len).h> #include <string.This is the maximum number of bytes to be checked for character length. printf( "Length in bytes of multibyte character %x: %u\n". #include <stdio. len = wcstombs( pmb. pmb. if a non-null wide character was recognized. char *pmb = (char *)malloc( MB_CUR_MAX ). len ). pmb). wchar_t *pwc = L"Hi". It returns -1.4x\n". char *pmbnull = NULL. 214 . printf("Hex value of first multibyte character: %#. printf("Characters converted %d\n". len = mblen( pmb. len ). pmb = NULL. MB_CUR_MAX ).C Standard Library  str -.h> #include <stdlib. Example The following example shows the usage of mblen() function. pmb. It returns 0. printf("Converting to multibyte string\n").

by the argument str to the array pointed to by pwcs. size_t mbstowcs(schar_t *pwcs. const char *str. const char *str.h> #include<stdlib. Example The following example shows the usage of mbstowcs() function.  str -. #include<stdio. size_t n) Description The C library function size_t mbstowcs(schar_t *pwcs.This is the pointer to an array of wchar_t elements that is long enough to store a wide string max characters long. Declaration Following is the declaration for mbstowcs() function. const char *str.h> 215 .  n -. If an invalid multi-byte character is encountered.This is the maximum number of wchar_t characters to be interpreted.C Standard Library return(0). size_t n) Parameters  pwcs -. Return Value This function returns the number of characters translated. size_t n) converts the string of multi-byte characters pointed to.This is the C multibyte character string to be interpreted. } Let us compile and run the above program that will produce the following result: Converting to multibyte string Characters converted 1 Hex value of first multibyte character: 0x168c6010 Length in bytes of multibyte character 168c6010: 1 Length in bytes of multibyte character 0: 0 size_t mbstowcs(schar_t *pwcs. excluding the ending null-character. a -1 value is returned.h> #include<string.

pwc. printf("Converting to multibyte string\n"). size_t n) Description The C library function int mbtowc(whcar_t *pwc. printf("Characters converted %d\n". len). 216 .4x\n". wchar_t *pwc = L"Hi". MB_CUR_MAX). MB_CUR_MAX). len). pwcs). pmb). char *pmb = (char *)malloc( MB_CUR_MAX ).4x\n\n". size_t n) converts a multibyte sequence to a wide character. const char *str. printf("Hex value of first multibyte character: %#. printf("Hex value of first wide character %#. char *pmbnull = NULL. printf("Characters converted %d\n". } Let us compile and run the above program that will produce the following result: Converting to multibyte string Characters converted 1 Hex value of first multibyte character: 0x19a60010 Converting back to Wide-Character string Characters converted 1 Hex value of first wide character 0x19a60030 int mbtowc(whcar_t *pwc. len = wcstombs( pmb. wchar_t *pwcs = (wchar_t *)malloc( sizeof( wchar_t )). pmb.C Standard Library int main() { int len. len = mbstowcs( pwcs. printf("Converting back to Wide-Character string\n"). const char *str. Declaration Following is the declaration for mbtowc() function. return(0).

mb ).h> int main() { char *str = "This is tutorialspoint. int len. 217 . } Let us compile and run the above program that will produce the following result which will be in multi-byte. const char *str. the mbtowc() function returns the number of consumed bytes starting at str. or 0 if s points to a null byte.This is the maximum number of bytes to be checked for character length.com". return(0).  str -. a kind of binary output. str. mbtowc(mb. size_t n) Parameters  pwc -. #include <stdio. len*strlen(str) ). Return Value  If str is not NULL.This is the pointer to an object of type wchar_t.h> #include <stdlib. MB_CUR_MAX). or zero if the encoding is stateless. Example The following example shows the usage of mbtowc() function.  If str is NULL. wchar_t mb[100]. len = mblen(NULL.h> #include <string. the mbtowc() function returns non-zero if the encoding has non-trivial shift state.C Standard Library int mbtowc(whcar_t *pwc. or -1 upon failure.  n -. wprintf(L"%ls \n".This is the pointer to the first byte of a multi-byte character.

BUFFER_SIZE). const wchar_t *pwcs. const wchar_t *pwcs.h> #include <stdlib. size_t n) Parameters  str -. #include <stdio.This is the maximum number of bytes to be written to str. excluding the ending null-character. size_t n) Description The C library function size_t wcstombs(char *str. char *MB = (char *)malloc( BUFFER_SIZE ). Return Value This function returns the number of bytes (not characters) converted and written to str.This is the pointer to an array of char elements at least n bytes long.tutorialspoint.h> #define BUFFER_SIZE 50 int main() { size_t ret. -1 value is returned. const wchar_t *pwcs. Example The following example shows the usage of wcstombs() function.  pwcs -. 218 . If an invalid multibyte character is encountered. wchar_t *WC = L"http://www. WC.This is wide-character string to be converted. size_t wcstombs(char *str. /* converting wide-character string */ ret = wcstombs(MB. At most n bytes are written to str. Declaration Following is the declaration for wcstombs() function.C Standard Library ??? size_t wcstombs(char *str.  n -. size_t n) converts the wide-character string pwcs to a multibyte string starting at str.com".

ret).This is the wide character of type wchar_t. -1 is returned. wchar_t wchar) function converts the wide character wchar to its multibyte representation and stores it at the beginning of the character array pointed to by str. Return Value  If str is not NULL. wchar_t wchar) Description The C library function int wctomb(char *str. wchar_t wchar) Parameters  str -. #include <stdio.  wchar -. return(0). } Let us compile and run the above program that will produce the following result: Characters converted = 29 Multibyte character = http://www. MB). int wctomb(char *str.h> 219 . printf("Multibyte character = %s\n\n". the wctomb() function returns non-zero if the encoding has non-trivial shift state.C Standard Library printf("Characters converted = %u\n".  If str is NULL. or zero if the encoding is stateless.This is the pointer to an array large enough to hold a multibyte character.tutorialspoint.com int wctomb(char *str. If wchar cannot be represented as a multibyte sequence.h> #include <stdlib. Example The following example shows the usage of wctomb() function. Declaration Following is the declaration for wctomb() function. the wctomb() function returns the number of bytes that have been written to the byte array at str.

} Let us compile and run the above program that will produce the following result: Converting wide character: Characters converted: 1 Multibyte character: a Trying to convert when target is NULL: Characters converted: 0 Multibyte character: 220 . wchar_t wc = L'a'. pmb). i = wctomb( pmb. printf("Trying to convert when target is NULL:\n"). wc ). printf("Multibyte character: %. printf("Characters converted: %u\n". char *pmbnull = NULL.1s\n". wc ). i = wctomb( pmbnull.C Standard Library int main() { int i. char *pmb = (char *)malloc(sizeof( char )). i). /* this will not print any value */ printf("Multibyte character: %.1s\n". return(0). pmbnull). printf("Characters converted: %u\n". i). printf("Converting wide character:\n").

<STRING. Macro & Description 1 NULL This macro is the value of a null pointer constant. Library Functions Following are the functions defined in the header string. Function & Description 1 void *memchr(const void *str.N. by the argument str.N. size_t n) Searches for the first occurrence of the character c (an unsigned char) in the first n bytes of the string pointed to. Variable & Description 1 size_t This is the unsigned the sizeof keyword. one macro. const void *str2. int c. and various functions for manipulating arrays of characters. size_t n) 221 . Library Variables Following is the variable type defined in the header string.h: S.h: S. integral type and is the result of Library Macros Following is the macro defined in the header string.C Standard Library 14. 2 int memcmp(const void *str1.h header defines one variable type.h: S.N.H> Introduction The string.

10 int strncmp(const char *str1. 3 void *memcpy(void *dest. by str1 to the string pointed to by str2. 12 result is dependent on the char *strcpy(char *dest. size_t n) Another function to copy n characters from str2 to str1. 11 int strcoll(const char *str1. const char *str2. const void *src. 9 int strcmp(const char *str1. const char *src) Appends the string pointed to. by the argument str.C Standard Library Compares the first n bytes of str1 and str2. size_t n) Appends the string pointed to. int c) Searches for the first occurrence of the character c (an unsigned char) in the string pointed to. size_t n) Copies the character c (an unsigned char) to the first n characters of the string pointed to. const char *src. int c. 8 char *strchr(const char *str. size_t n) Copies n characters from src to dest. by destup to n characters long. const char *src) Copies the string pointed to. The LC_COLLATE setting of the location. 6 char *strcat(char *dest. const char *str2) Compares string str1 to str2. const void *src. by src to the end of the string pointed to. size_t n) Compares at most the first n bytes of str1 and str2. const char *str2) Compares the string pointed to. 5 void *memset(void *str. 222 . by the argument str. 7 char *strncat(char *dest. by src to dest. 4 void *memmove(void *dest. by src to the end of the string pointed to by dest.

21 char *strtok(char *str. 17 char *strpbrk(const char *str1.C Standard Library 13 char *strncpy(char *dest. 19 size_t strspn(const char *str1. size_t n) Copies up to n characters from the string pointed to. const char *src. by src to dest. size_t n) Transforms the first n characters of the string src into corrent locale and places them in the string dest. const char *str2) Finds the first character in the string str1 that matches any character specified in str2. 22 size_t strxfrm(char *dest. const char *needle) Finds the first occurrence of the entire string needle (not including the terminating null character) which appears in the string haystack. 14 size_t strcspn(const char *str1. 15 char *strerror(int errnum) Searches an internal array for the error number errnum and returns a pointer to an error message string. 223 . const char *str2) Calculates the length of the initial segment of str1 which consists entirely of characters not in str2. const char *str2) Calculates the length of the initial segment of str1 which consists entirely of characters in str2. 20 char *strstr(const char *haystack. const char *delim) Breaks string str into a series of tokens separated by delim. const char *src. 16 size_t strlen(const char *str) Computes the length of the string str up to but not including the terminating null character. 18 char *strrchr(const char *str. int c) Searches for the last occurrence of the character c (an unsigned char) in the string pointed to by the argument str.

const char ch = '. void *memchr(const void *str.This is the value to be passed as an int. } 224 . by the argument str.'.  n -. but the function performs a byte per byte search using the unsigned char conversion of this value.  c -.This is the number of bytes to be analyzed. ch.tutorialspoint. int c. ch. #include <stdio.|%s|\n".h> int main () { const char str[] = "http://www. ret). int c. return(0). strlen(str)). Return Value This function returns a pointer to the matching byte or NULL if the character does not occur in the given memory area. ret = memchr(str. Example The following example shows the usage of memchr() function. size_t n) Description The C library function void *memchr(const void *str. size_t n) searches for the first occurrence of the character c (an unsigned char) in the first n bytes of the string pointed to.h> #include <string.C Standard Library void *memchr(const void *str.com". char *ret. printf("String after |%c| is .This is the pointer to the block of memory where the search is performed. Declaration Following is the declaration for memchr() function. size_t n) Parameters  str -. int c.

const void *str2.This is the pointer to a block of memory. const void *str2.This is the pointer to a block of memory. memcpy(str2.h> int main () { char str1[15]. 6).  n -. char str2[15]. "abcdef".h> #include <string. size_t n)) compares the first n bytes of memory area str1 and memory area str2. Declaration Following is the declaration for memcmp() function.This is the number of bytes to be compared.|. Return Value  if Return value is < 0 then it indicates str1 is less than str2.tutorialspoint. memcpy(str1. const void *str2.C Standard Library Let us compile and run the above program that will produce the following result: String after |. Example The following example shows the usage of memcmp() function. "ABCDEF". size_t n) Description The C library function int memcmp(const void *str1.  if Return value is > 0 then it indicates str2 is less than str1.com| int memcmp(const void *str1. 225 .| is . 6). #include <stdio. size_t n) Parameters  str1 -. int ret. int memcmp(const void *str1.  str2 -.  if Return value is = 0 then it indicates str1 is equal to str2.

Declaration Following is the declaration for memcpy() function. void *memcpy(void *str1.This is pointer to the destination array where the content is to be copied. } Let us compile and run the above program that will produce the following result: str2 is less than str1 void *memcpy(void *dest. type-casted to a pointer of type void*. 5). const void *str2. size_t n) Description The C library function void *memcpy(void *str1. const void *src. str2.This is the number of bytes to be copied. size_t n) copies n characters from memory area str2 to memory area str1. const void *str2. 226 .This is pointer to the source of data to be copied.  n -. } return(0). size_t n) Parameters  str1 -. type-casted to a pointer of type void*. } else if(ret < 0) { printf("str1 is less than str2"). } else { printf("str1 is equal to str2"). if(ret > 0) { printf("str2 is less than str1").  str2 -.C Standard Library ret = memcmp(str1.

const void *str2. dest). but for overlapping memory blocks. #include <stdio.h> int main () { const char src[50] = "http://www.This is a pointer to the destination array where the content is to be copied. printf("After memcpy dest = %s\n".tutorialspoint. size_t n) copies n characters from str2 to str1. Example The following example shows the usage of memcpy() function. type-casted to a pointer of type void*. size_t n) Description The C library function void *memmove(void *str1. printf("Before memcpy dest = %s\n".tutorialspoint. char dest[50].C Standard Library Return Value This function returns a pointer to destination.com". which is str1. } Let us compile and run the above program that will produce the following result: Before memcpy dest = After memcpy dest = http://www. return(0). dest). 227 . src. const void *src.h> #include <string. memcpy(dest. strlen(src)+1). size_t n) Parameters  str1 -. Declaration Following is the declaration for memmove() function. void *memmove(void *str1. memmove() is a safer approach than memcpy(). const void *str2.com void *memmove(void *dest.

type-casted to a pointer of type void*. printf("Before memmove dest = %s. #include <stdio. size_t n) Description The C library function void *memset(void *str. int c. size_t n) copies the character c (an unsigned char) to the first n characters of the string pointed to. Declaration Following is the declaration for memset() function.This is the number of bytes to be copied. src). } Let us compile and run the above program that will produce the following result: Before memmove dest = oldstring. src = %s\n".h> #include <string. size_t n) 228 . 9).C Standard Library  str2 -. by the argument str.  n -. Example The following example shows the usage of memmove() function.h> int main () { const char dest[] = "oldstring".This is a pointer to the source of data to be copied. dest. src = %s\n". src = newstring void *memset(void *str. void *memset(void *str. memmove(dest. which is str1. int c. src. int c. dest. return(0). src). const char src[] = "newstring". Return Value This function returns a pointer to the destination. src = newstring After memmove dest = newstring. printf("After memmove dest = %s.

h library function char *strcat(char *dest.This is a pointer to the block of memory to fill.This is the number of bytes to be set to the value. return(0). #include <stdio.  c -."This is string.7). Example The following example shows the usage of memset() function.h library function $$$$$$$ string. but the function fills the block of memory using the unsigned char conversion of this value. Return Value This function returns a pointer to the memory area str. The value is passed as an int. const char *src) appends the string pointed to by src to the end of the string pointed to by dest.C Standard Library Parameters  str -.h library function"). strcpy(str. } Let us compile and run the above program that will produce the following result: This is string. puts(str).  n -.h> int main () { char str[50].This is the value to be set. memset(str. puts(str). const char *src) Description The C library function char *strcat(char *dest. 229 .h> #include <string.'$'.

strcpy(src.h> int main () { char src[50]. #include <stdio. src). char *strcat(char *dest.This is pointer to the destination array. Example The following example shows the usage of strcat() function.  src -. return(0).h> #include <string. and should be large enough to contain the concatenated resulting string. Return Value This function returns a pointer to the resulting string dest. const char *src) Parameters  dest -.This is the string to be appended. which should contain a C string. "This is destination"). strcpy(dest. } Let us compile and run the above program that will produce the following result: Final destination string : |This is destinationThis is source| 230 . printf("Final destination string : |%s|".C Standard Library Declaration Following is the declaration for strcat() function. This should not overlap the destination. "This is source"). strcat(dest. dest[50]. dest).

This is the string to be appended. strcpy(dest. Return Value This function returns a pointer to the resulting string dest. Example The following example shows the usage of strncat() function. char *strncat(char *dest. strcpy(src. const char *src. size_t n) appends the string pointed to by src to the end of the string pointed to by dest up to n characters long.This is pointer to the destination array.  src -. size_t n) Parameters  dest -. "This is destination").h> int main () { char src[50]. 15). 231 .C Standard Library char *strncat(char *dest.  n -. src. const char *src. dest). strncat(dest. #include <stdio.This is the maximum number of characters to be appended. dest[50]. printf("Final destination string : |%s|". Declaration Following is the declaration for strncat() function. const char *src.h> #include <string. which should contain a C string. return(0). size_t n) Description The C library function char *strncat(char *dest. and should be large enough to contain the concatenated resulting string which includes the additional null-character. "This is source").

h> #include <string. #include <stdio.|%s|\n".This is the character to be searched in str. printf("String after |%c| is . or NULL if the character is not found. Return Value This returns a pointer to the first occurrence of the character c in the string str.'. ch. const char ch = '. int c) Description The C library function char *strchr(const char *str.tutorialspoint. Example The following example shows the usage of strchr() function.com". 232 . Declaration Following is the declaration for strchr() function.  c -.h> int main () { const char str[] = "http://www. ch). ret = strchr(str. ret). char *strchr(const char *str.This is the C string to be scanned.C Standard Library } Let us compile and run the above program that will produce the following result: Final destination string : |This is destinationThis is source| char *strchr(const char *str. int c) Parameters  str -. int c) searches for the first occurrence of the character c (an unsigned char) in the string pointed to by the argument str. char *ret.

int ret. Declaration Following is the declaration for strcmp() function. by str1 to the string pointed to by str2. #include <stdio. const char *str2) Description The C library function int strcmp(const char *str1.tutorialspoint. Return Value This function return values that are as follows:  if Return value is < 0 then it indicates str1 is less than str2.This is the first string to be compared.h> int main () { char str1[15]. Example The following example shows the usage of strncmp() function.This is the second string to be compared. char str2[15]. int strcmp(const char *str1. const char *str2) compares the string pointed to.C Standard Library return(0). const char *str2) Parameters  str1 -.  if Return value is = 0 then it indicates str1 is equal to str2. 233 .com| int strcmp(const char *str1.  if Return value is > 0 then it indicates str2 is less than str1.  str2 -.| is .h> #include <string.|. } Let us compile and run the above program that will produce the following result: String after |.

This is the first string to be compared. size_t n) Description The C library function int strncmp(const char *str1.  str2 -. } else if(ret > 0) { printf("str2 is less than str1"). } else { printf("str1 is equal to str2"). const char *str2. } return(0). const char *str2. size_t n) Parameters  str1 -. int strncmp(const char *str1. Declaration Following is the declaration for strncmp() function. "ABCDEF"). "abcdef"). if(ret < 0) { printf("str1 is less than str2"). 234 .C Standard Library strcpy(str1. strcpy(str2. ret = strcmp(str1. const char *str2. size_t n) compares at most the first n bytes of str1 and str2. } Let us compile and run the above program that will produce the following result: str2 is less than str1 int strncmp(const char *str1. str2).This is the second string to be compared.

 if Return value is = 0 then it indicates str1 is equal to str2. Example The following example shows the usage of strncmp() function. } else { printf("str1 is equal to str2").h> #include <string. #include <stdio.h> int main () { char str1[15]. if(ret < 0) { printf("str1 is less than str2").The maximum number of characters to be compared. strcpy(str1. strcpy(str2. } else if(ret > 0) { printf("str2 is less than str1"). "abcdef"). str2. char str2[15]. ret = strncmp(str1. Return Value This function return values that are as follows:  if Return value is < 0 then it indicates str1 is less than str2.  if Return value is > 0 then it indicates str2 is less than str1. "ABCDEF"). int ret.C Standard Library  n -. 4). 235 .

const char *str2) compares string str1 to str2. } Let us compile and run the above program that will produce the following result: str2 is less than str1 int strcoll(const char *str1. const char *str2) Description The C library function int strcoll(const char *str1.C Standard Library } return(0). Declaration Following is the declaration for strcoll() function.This is the first string to be compared. #include <stdio. char str2[15]. const char *str2) Parameters  str1 -.  if Return value is = 0 then it indicates str1 is equal to str2. int strcoll(const char *str1.This is the second string to be compared.h> #include <string. Return Value This function return values that are as follows:  if Return value is < 0 then it indicates str1 is less than str2.h> int main () { char str1[15]. 236 . The result is dependent on the LC_COLLATE setting of the location. Example The following example shows the usage of strcoll() function.  str2 -.  if Return value is > 0 then it indicates str2 is less than str1.

} return(0).C Standard Library int ret. if(ret > 0) { printf("str1 is less than str2"). } else if(ret < 0) { printf("str2 is less than str1"). const char *src) 237 . const char *src) copies the string pointed to. by src to dest. strcpy(str1. } else { printf("str1 is equal to str2"). const char *src) Description The C library function char *strcpy(char *dest. } Let us compile and run the above program that will produce the following result: str1 is less than str2 char *strcpy(char *dest. strcpy(str2. "abc"). str2). char *strcpy(char *dest. Declaration Following is the declaration for strcpy() function. ret = strcoll(str1. "ABC").

"This is tutorialspoint. #include <stdio. Example The following example shows the usage of strcpy() function. strcpy(src.This is the pointer to the destination array where the content is to be copied. const char *src. src). size_t n) Description The C library function char *strncpy(char *dest. sizeof(dest)). Declaration 238 . size_t n) copies up to n characters from the string pointed to. the remainder of dest will be padded with null bytes.h> int main() { char src[40]. memset(dest.com"). const char *src. In a case where the length of src is less than that of n. printf("Final copied string : %s\n". by src to dest.com char *strncpy(char *dest. } Let us compile and run the above program that will produce the following result: Final copied string : This is tutorialspoint.C Standard Library Parameters  dest -. return(0). dest).h> #include <string.  src -. Return Value This returns a pointer to the destination string dest. strcpy(dest. '###BOT_TEXT###'. char dest[100].This is the string to be copied.

com").C Standard Library Following is the declaration for strncpy() function. Example The following example shows the usage of strncpy() function. memset(dest. Return Value This function returns the final copy of the copied string.  n -. printf("Final copied string : %s\n".h> #include <string. sizeof(dest)). size_t n) Parameters  dest -.This is the string to be copied. const char *src.  src -. char *strncpy(char *dest. return(0). '###BOT_TEXT###'. } Let us compile and run the above program that will produce the following result: Final copied string : This is tu 239 . strncpy(dest. src. dest). 10). Here we have used function memset() to clear the memory location. "This is tutorialspoint.h> int main() { char src[40].The number of characters to be copied from source. #include <stdio.This is the pointer to the destination array where the content is to be copied. char dest[12]. strcpy(src.

printf("First matched character is at %d\n".This is the main C string to be scanned.  str2 -. const char str1[] = "ABCDEF4960910". const char *str2) calculates the length of the initial segment of str1. which consists entirely of characters not in str2. len + 1).This is the string containing a list of characters to match in str1. Example The following example shows the usage of strcspn() function.h> int main () { int len. return(0). #include <stdio. const char *str2) Description The C library function size_t strcspn(const char *str1. const char *str2) Parameters  str1 -. size_t strcspn(const char *str1. } Let us compile and run the above program that will produce the following result: 240 . which are not in the string str2. Return Value This function returns the number of characters in the initial segment of string str1. Declaration Following is the declaration for strcspn() function. const char str2[] = "013".C Standard Library size_t strcspn(const char *str1. str2). len = strcspn(str1.h> #include <string.

usually errno. } 241 . Example The following example shows the usage of strerror() function.txt". } return(0)."r").h> int main () { FILE *fp. Declaration Following is the declaration for strerror() function. strerror(errno)).C Standard Library First matched character is at 10 char *strerror(int errnum) Description The C library function char *strerror(int errnum) searches an internal array for the error number errnum and returns a pointer to an error message string. fp = fopen("file. The error strings produced by strerror depend on the developing platform and compiler.h> #include <errno.h> #include <string. Return Value This function returns a pointer to the error string describing error errnum. #include <stdio.This is the error number. if( fp == NULL ) { printf("Error: %s\n". char *strerror(int errnum) Parameters  errnum -.

"This is tutorialspoint.This is the string whose length is to be found. but not including the terminating null character. Return Value This function returns the length of string. return(0). len = strlen(str). Example The following example shows the usage of strlen() function. printf("Length of |%s| is |%d|\n".com").C Standard Library Let us compile and run the above program that will produce the following result because we are trying to open a file which does not exist: Error: No such file or directory size_t strlen(const char *str) Description The C library function size_t strlen(const char *str) computes the length of the string str up to. size_t strlen(const char *str) Parameters  str -. #include <stdio.h> int main () { char str[50]. Declaration Following is the declaration for strlen() function. } Let us compile and run the above program that will produce the following result: 242 . str.h> #include <string. int len. len). strcpy(str.

const char *str2) Description The C library function char *strpbrk(const char *str1. char *strpbrk(const char *str1.com| is |26| char *strpbrk(const char *str1. char *ret. Return Value This function returns a pointer to the character in str1 that matches one of the characters in str2. if(ret) { printf("First matching character: %c\n".This is the C string to be scanned.  str2 -. Declaration Following is the declaration for strpbrk() function. *ret). Example The following example shows the usage of strpbrk() function. const char *str2) finds the first character in the string str1 that matches any character specified in str2. ret = strpbrk(str1. str2). const char *str2) Parameters  str1 -. #include <stdio. const char str2[] = "34". This does not include the terminating null-characters. or NULL if no such character is found. } else 243 .C Standard Library Length of |This is tutorialspoint.This is the C string containing the characters to match.h> int main () { const char str1[] = "abcde2fghi3jk4l".h> #include <string.

Declaration Following is the declaration for strrchr() function.com". It is passed as its int promotion.  c -. } return(0). Example The following example shows the usage of strrchr() function. Return Value This function returns a pointer to the last occurrence of character in str. by the argument str.C Standard Library { printf("Character not found"). If the value is not found. #include <stdio.tutorialspoint. } Let us compile and run the above program that will produce the following result: First matching character: 3 char *strrchr(const char *str. int c) Parameters  str -.This is the C string. 244 .This is the character to be located. int c) Description The C library function char *strrchr(const char *str. const char str[] = "http://www. the function returns a null pointer.h> #include <string. int c) searches for the last occurrence of the character c (an unsigned char) in the string pointed to. char *strrchr(const char *str. but it is internally converted back to char.h> int main () { int len.

This is the main C string to be scanned. size_t strspn(const char *str1. Declaration Following is the declaration for strspn() function.h> #include <string. Return Value This function returns the number of characters in the initial segment of str1 which consist only of characters from str2. printf("String after |%c| is . } Let us compile and run the above program that will produce the following result: String after |. char *ret. Example The following example shows the usage of strspn() function.com| size_t strspn(const char *str1. ret). return(0).| is .'.|. ch.|%s|\n". #include <stdio. const char *str2) Parameters  str1 -. const char *str2) calculates the length of the initial segment of str1 which consists entirely of characters in str2.C Standard Library const char ch = '.h> int main () { 245 .This is the string containing the list of characters to match in str1. const char *str2) Description The C library function size_t strspn(const char *str1.  str2 -. ch). ret = strrchr(str.

const char str1[] = "ABCDEFG019874".This is the small string to be searched within haystack string. str2). #include <stdio.h> #include <string. const char *needle) Parameters  haystack -. The terminating '###BOT_TEXT###' characters are not compared.  needle -. char *strstr(const char *haystack. } Let us compile and run the above program that will produce the following result: Length of initial segment matching 4 char *strstr(const char *haystack. Return Value This function returns a pointer to the first occurrence in haystack of any of the entire sequence of characters specified in needle.h> 246 .C Standard Library int len. or a null pointer if the sequence is not present in haystack. const char *needle) Description The C library function char *strstr(const char *haystack.This is the main C string to be scanned. return(0). len = strspn(str1. Example The following example shows the usage of strstr() function. const char *needle) finds the first occurrence of the substring needle in the string haystack. const char str2[] = "ABCD". len ). printf("Length of initial segment matching %d\n". Declaration Following is the declaration for strstr() function.

Example The following example shows the usage of strtok() function.The contents of this string are modified and broken into smaller strings (tokens). 247 .This is the C string containing the delimiters. return(0). needle). } Let us compile and run the above program that will produce the following result: The substring is: Point char *strtok(char *str. printf("The substring is: %s\n". char *strtok(char *str.  delim -. A null pointer is returned if there are no tokens left to retrieve. ret = strstr(haystack.C Standard Library int main() { const char haystack[20] = "TutorialsPoint". Return Value This function returns a pointer to the last token found in the string. const char *delim) Description The C library function char *strtok(char *str. Declaration Following is the declaration for strtok() function. ret). char *ret. const char *delim) breaks string str into a series of tokens using the delimiter delim. const char *delim) Parameters  str -. const char needle[10] = "Point". These may vary from one call to another.

s). const char s[2] = "-". 248 . size_t n) Description The C library function size_t strxfrm(char *dest.tutorialspoint. const char *src. token = strtok(NULL.com . Declaration Following is the declaration for strxfrm() function.com website size_t strxfrm(char *dest. /* walk through other tokens */ while( token != NULL ) { printf( " %s\n". /* get the first token */ token = strtok(str.website".www.C Standard Library #include <string. s). char *token. const char *src.tutorialspoint.h> #include <stdio. } return(0). token ). size_t n) transforms the first n characters of the string src into current locale and place them in the string dest. } Let us compile and run the above program that will produce the following result: This is www.h> int main() { const char str[80] = "This is .

not including the terminating null-character. Return Value This function returns the length of the transformed string.This is the pointer to the destination array where the content is to be copied.  src -. 20).h> #include <string. strcpy(src. const char *src. src. Example The following example shows the usage of strxfrm() function. int len. len). return(0).h> int main() { char dest[20]. printf("Length of string |%s| is: |%d|". dest. len = strxfrm(dest. "Tutorials Point").This is the C string to be transformed into current locale. size_t n) Parameters  dest -. } Let us compile and run the above program that will produce the following result: Length of string |Tutorials Point| is: |15| 249 .  n -.C Standard Library size_t strxfrm(char *dest. char src[20]. It can be a null pointer if the argument for n is zero.The maximum number of characters to be copied to str1. #include <stdio.

The tm structure has the following definition: struct tm { int tm_sec. /* month. range 0 to 365 */ 250 .15. 2 integral type and is the result of clock_t This is a type suitable for storing the processor time.h header defines four variable types.N.H> C Standard Library Introduction The time. range 0 to 11 */ int tm_year. /* day of the week. /* hours. /* day in the year. Library Variables Following are the variable types defined in the header time. two macro and various functions for manipulating date and time. 4 struct tm This is a structure used to hold the time and date. /* seconds. range 0 to 23 */ int tm_mday. /* The number of years since 1900 */ int tm_wday. range 0 to 6 */ int tm_yday. /* day of the month. /* minutes. range 1 to 31 */ int tm_mon.h: S. range 0 to 59 */ int tm_min. range 0 to 59 */ int tm_hour. Variable & Description 1 size_t This is the unsigned the sizeof keyword. <TIME. 3 time_t is This is a type suitable for storing the calendar time.

clock_t clock(void) 2 Returns the processor clock time used since the beginning of an implementation defined era (normally the beginning of the program).h: S.N.C Standard Library int tm_isdst. char *ctime(const time_t *timer) 3 Returns a string representing the localtime based on the argument timer. Library Functions Following are the functions defined in the header time.N. 2 CLOCKS_PER_SEC This macro represents the number of processor clocks per second. struct tm *gmtime(const time_t *timer) 5 The value of timer is broken up into the structure tm and expressed in Coordinated Universal Time (UTC). also known as Greenwich Mean 251 . Function & Description char *asctime(const struct tm *timeptr) 1 Returns a pointer to a string which represents the day and time of the structure timeptr. double difftime(time_t time1. Library Macros Following are the macros defined in the header time. /* daylight saving time */ }. Macro & Description 1 NULL This macro is the value of a null pointer constant. time_t time2) 4 Returns the difference of seconds between time1 and time2 (time1time2).h: S.

/* month. range 0 to 59 */ int tm_min. size_t strftime(char *str. range 0 to 11 */ int tm_year. time_t mktime(struct tm *timeptr) 7 8 9 Converts the structure pointed to by timeptr into a time_t value according to the local time zone. char *asctime(const struct tm *timeptr) Parameters The timeptr is a pointer to tm structure that contains a calendar time broken down into its components as shown below: struct tm { int tm_sec. Declaration Following is the declaration for asctime() function. size_t maxsize. char *asctime(const struct tm *timeptr) Description The C library function char *asctime(const struct tm *timeptr) returns a pointer to a string which represents the day and time of the structure struct timeptr. const struct tm *timeptr) Formats the time represented in the structure timeptr according to the formatting rules defined in format and stored into str. /* day of the month. /* minutes. struct tm *localtime(const time_t *timer) 6 The value of timer is broken up into the structure tm and expressed in the local time zone. /* hours. const char *format.C Standard Library Time (GMT). /* The number of years since 1900 */ 252 . /* seconds. time_t time(time_t *timer) Calculates the current calender time and encodes it into time_t format. range 0 to 23 */ int tm_mday. range 0 to 59 */ int tm_hour. range 1 to 31 */ int tm_mon.

t. /* day in the year.h> #include <time.tm_wday = 6. #include <stdio. Mmm the month in letters.tm_min = 10. return(0).C Standard Library int tm_wday. and yyyy the year. puts(asctime(&t)). where Www is the weekday.tm_mon = 2. range 0 to 6 */ int tm_yday. t.h> int main() { struct tm t. Return Value This function returns a C string containing the date and time information in a human-readable format Www Mmm dd hh:mm:ss yyyy. t. t. t. } Let us compile and run the above program that will produce the following result: Sat Mar 25 06:10:10 1989 253 . t.tm_mday = 25. t. Example The following example shows the usage of asctime() function.tm_hour = 6.tm_sec = 10.h> #include <string. hh:mm:ss the time.tm_year = 89. range 0 to 365 */ int tm_isdst. /* day of the week. dd the day of the month. /* daylight saving time */ }.

To get the number of seconds used by the CPU. #include <time. for(i=0. On a 32 bit system where CLOCKS_PER_SEC equals 1000000 this function will return the same value approximately every 72 minutes.h> int main() { clock_t start_t. Example The following example shows the usage of clock() function. printf("End of the big loop. end_t = %ld\n". On failure. end_t).C Standard Library clock_t clock(void) Description The C library function clock_t clock(void) returns the number of clock ticks elapsed since the program was launched. end_t. start_t). the function returns a value of -1. start_t = %ld\n". clock_t clock(void) Parameters  NA Return Value This function returns the number of clock ticks elapsed since the start of the program. you will need to divide by CLOCKS_PER_SEC. i< 10000000.h> #include <stdio. printf("Starting of the program. start_t = %ld\n". printf("Going to scan a big loop. int i. start_t). 254 . start_t = clock(). i++) { } end_t = clock(). Declaration Following is the declaration for clock() function. total_t.

end_t = 20000 Total time taken by CPU: 0. start_t = 0 End of the big loop. char *ctime(const time_t *timer) Parameters  timer -.h> 255 .C Standard Library total_t = (double)(end_t . total_t ).. and yyyy the year. return(0). The returned string has the following format: Www Mmm dd hh:mm:ss yyyy..This is the pointer to a time_t object that contains a calendar time. Mmm the month in letters.. Return Value This function returns a C string containing the date and time information in a human-readable format.. } Let us compile and run the above program that will produce the following result: Starting of the program.start_t) / CLOCKS_PER_SEC. dd the day of the month. printf("Total time taken by CPU: %f\n".\n"). Declaration Following is the declaration for ctime() function.where Www is the weekday. #include <stdio. start_t = 0 Going to scan a big loop.000000 Exiting of the program. Example The following example shows the usage of ctime() function. char *ctime(const time_t *timer) Description The C library function char *ctime(const time_t *timer) returns a string representing the localtime based on the argument timer. hh:mm:ss the time. printf("Exiting of the program.

C Standard Library

#include <time.h>

int main ()
{
time_t curtime;

time(&curtime);

printf("Current time = %s", ctime(&curtime));

return(0);
}
Let us compile and run the above program that will produce the following result:
Current time = Mon Aug 13 08:23:14 2012

double difftime(time_t time1, time_t time2)
Description
The C library function double difftime(time_t time1, time_t time2) returns
the difference of seconds between time1 and time2 i.e. (time1 - time2). The
two times are specified in calendar time, which represents the time elapsed
since the Epoch (00:00:00 on January 1, 1970, Coordinated Universal Time
(UTC)).

Declaration
Following is the declaration for difftime() function.
double difftime(time_t time1, time_t time2)

Parameters

time1 -- This is the time_t object for end time.

time2 -- This is the time_t object for start time.

Return Value
This function returns the difference of two times (time2 - time1) as a double
value.

Example
The following example shows the usage of difftime() function.
256

C Standard Library

#include <stdio.h>
#include <time.h>

int main ()
{
time_t start_t, end_t;
double diff_t;

printf("Starting of the program...\n");
time(&start_t);

printf("Sleeping for 5 seconds...\n");
sleep(5);

time(&end_t);
diff_t = difftime(end_t, start_t);

printf("Execution time = %f\n", diff_t);
printf("Exiting of the program...\n");

return(0);
}
Let us compile and run the above program that will produce the following result:
Starting of the program...
Sleeping for 5 seconds...
Execution time = 5.000000
Exiting of the program...

struct tm *gmtime(const time_t *timer)
Description
The C library function struct tm *gmtime(const time_t *timer) uses the
value pointed by timer to fill a tm structure with the values that represent the
corresponding time, expressed in Coordinated Universal Time (UTC) or GMT
timezone.
257

C Standard Library

Declaration
Following is the declaration for gmtime() function.
struct tm *gmtime(const time_t *timer)

Parameters

timeptr -- This is the pointer to a time_t value representing a calendar
time.

Return Value
This function returns pointer to a tm structure with the time information filled in.
Below is the detail of timeptr structure:
struct tm {
int tm_sec;

/* seconds,

range 0 to 59

*/

int tm_min;

/* minutes, range 0 to 59

*/

int tm_hour;

/* hours, range 0 to 23

*/

int tm_mday;

/* day of the month, range 1 to 31

*/

int tm_mon;

/* month, range 0 to 11

*/

int tm_year;

/* The number of years since 1900

*/

int tm_wday;

/* day of the week, range 0 to 6

*/

int tm_yday;

/* day in the year, range 0 to 365

*/

int tm_isdst;

/* daylight saving time

*/

};

Example
The following example shows the usage of gmtime() function.
#include <stdio.h>
#include <time.h>

#define BST (+1)
#define CCT (+8)

int main ()
{

time_t rawtime;
struct tm *info;
258

C Standard Library

time(&rawtime);
/* Get GMT time */
info = gmtime(&rawtime );

printf("Current world clock:\n");
printf("London : %2d:%02d\n", (info->tm_hour+BST)%24, info->tm_min);
printf("China

: %2d:%02d\n", (info->tm_hour+CCT)%24, info->tm_min);

return(0);
}
Let us compile and run the above program that will produce the following result:
Current world clock:
London : 14:10
China : 21:10

struct tm *localtime(const time_t *timer)
Description
The C library function struct tm *localtime(const time_t *timer) uses the
time pointed by timer to fill a tm structure with the values that represent the
corresponding local time. The value of timer is broken up into the
structure tm and expressed in the local time zone.

Declaration
Following is the declaration for localtime() function.
struct tm *localtime(const time_t *timer)

Parameters

timer -- This is the pointer to a time_t value representing a calendar
time.

Return Value
This function returns a pointer to a tm structure with the time information filled
in. Following is the tm structure information:
struct tm {
int tm_sec;

/* seconds,

range 0 to 59

*/
259

C Standard Library

int tm_min;

/* minutes, range 0 to 59

*/

int tm_hour;

/* hours, range 0 to 23

*/

int tm_mday;

/* day of the month, range 1 to 31

*/

int tm_mon;

/* month, range 0 to 11

*/

int tm_year;

/* The number of years since 1900

*/

int tm_wday;

/* day of the week, range 0 to 6

*/

int tm_yday;

/* day in the year, range 0 to 365

*/

int tm_isdst;

/* daylight saving time

*/

};

Example
The following example shows the usage of localtime() function.
#include <stdio.h>
#include <time.h>

int main ()
{
time_t rawtime;
struct tm *info;
char buffer[80];

time( &rawtime );

info = localtime( &rawtime );
printf("Current local time and date: %s", asctime(info));

return(0);
}
Let us compile and run the above program that will produce the following result:
Current local time and date: Thu Aug 23 09:12:05 2012

time_t mktime(struct tm *timeptr)
Description
260

On error.h> int main () { int ret. struct tm info. range 0 to 59 */ int tm_hour. 261 . /* day in the year. /* month. broken down into its components.h> #include <time. range 0 to 11 */ int tm_year. /* daylight saving time */ }. /* hours. Below is the detail of timeptr structure struct tm { int tm_sec. time_t mktime(struct tm *timeptr) Parameters  timeptr -. /* seconds. range 0 to 59 */ int tm_min. /* day of the month. /* minutes. Declaration Following is the declaration for mktime() function. range 1 to 31 */ int tm_mon.C Standard Library The C library function time_t mktime(struct tm *timeptr) converts the structure pointed to by timeptr into a time_t value according to the local time zone. Return Value This function returns a time_t value corresponding to the calendar time passed as argument. /* day of the week. range 0 to 365 */ int tm_isdst. char buffer[80]. range 0 to 23 */ int tm_mday. Example The following example shows the usage of mktime() function. range 0 to 6 */ int tm_yday. /* The number of years since 1900 */ int tm_wday. #include <stdio.This is the pointer to a time_t value representing a calendar time. a -1 value is returned.

printf(buffer). info.tm_year = 2001 .tm_sec = 1. info. } else { strftime(buffer. const char *format. 262 . size_t maxsize.tm_min = 0.C Standard Library info. &info ). ret = mktime(&info).1. info. } Let us compile and run the above program that will produce the following result: Wed Jul 4 00:00:01 2001 size_t strftime(char *str.1900. size_t maxsize.tm_hour = 0. const struct tm *timeptr) Description The C library function size_t strftime(char *str.tm_isdst = -1. const char *format. "%c". info.tm_mon = 7 . Declaration Following is the declaration for strftime() function. info.tm_mday = 4. const struct tm *timeptr) formats the time represented in the structure timeptr according to the formatting rules defined in format and stored into str. } return(0). sizeof(buffer). info. if( ret == -1 ) { printf("Error: unable to make time using mktime\n").

C Standard Library size_t strftime(char *str.  format -.This is the maximum number of characters to be copied to str.  maxsize -. The format specifiers are: Specifier Replaced By Example %a Abbreviated weekday name Sun %A Full weekday name Sunday %b Abbreviated month name Mar %B Full month name March %c Date and time representation Sun Aug 19 02:56:02 2012 %d Day of the month (01-31) 19 %H Hour in 24h format (00-23) 14 %I Hour in 12h format (01-12) 05 %j Day of the year (001-366) 231 %m Month as a decimal number (01-12) 08 %M Minute (00-59) 55 %p AM or PM designation PM 263 . const struct tm *timeptr) Parameters  str -.This is the C string containing any combination of regular characters and special format specifiers. const char *format. These format specifiers are replaced by the function to the corresponding values to represent the time specified in tm.This is the pointer to the destination array where the resulting C string is copied. size_t maxsize.

/* The number of years since 1900 */ int tm_wday. range 1 to 31 */ int tm_mon. range 0 to 6 */ int tm_yday. range 0 to 365 */ int tm_isdst. /* day of the month.This is the pointer to a tm structure that contains a calendar time broken down into its components as shown below: struct tm { int tm_sec. /* day in the year. /* daylight saving time */ }. /* minutes. range 0 to 23 */ int tm_mday. /* hours. /* month. /* seconds. Return Value 264 .C Standard Library %S Second (00-61) 02 %U Week number with the first Sunday as the first day of week one (00-53) 33 %w Weekday as a decimal number with Sunday as 0 (0-6) 4 %W Week number with the first Monday as the first day of week one (00-53) 34 %x Date representation 08/19/12 %X Time representation 02:50:06 %y Year. /* day of the week. last two digits (00-99) 01 %Y Year 2012 %Z Timezone name or abbreviation CDT %% A % sign %  timeptr -. range 0 to 59 */ int tm_hour. range 0 to 59 */ int tm_min. range 0 to 11 */ int tm_year.

"%x . #include <stdio. struct tm *info. 265 . } Let us compile and run the above program that will produce the following result: Formatted date & time : |08/23/12 .h> #include <time. info). the return value is also stored in variable seconds.12:40AM| time_t time(time_t *timer) Description The C library function time_t time(time_t *seconds) returns the time since the Epoch (00:00:00 UTC. Example The following example shows the usage of strftime() function. char buffer[80]. measured in seconds. info = localtime( &rawtime ). 1970). time( &rawtime ). buffer ). return(0).h> int main () { time_t rawtime.%I:%M%p". printf("Formatted date & time : |%s|\n". January 1.80. the total number of characters copied to str (not including the terminating null-character) is returned otherwise. strftime(buffer.C Standard Library If the resulting C string fits in less than size characters (which includes the terminating null-character). If seconds is not NULL. Declaration Following is the declaration for time() function. it returns zero.

Example The following example shows the usage of time() function. 1970 = %ld\n". where the seconds value will be stored. seconds = time(NULL). seconds/3600).This is the pointer to an object of type time_t.h> int main () { time_t seconds. #include <stdio. } Let us compile and run the above program that will produce the following result: Hours since January 1.C Standard Library time_t time(time_t *t) Parameters  seconds -.h> #include <time. 1970 = 393923 266 . Return Value The current calendar time as a time_t object. return(0). printf("Hours since January 1.