Essential Standard Library Functions in C Programming with Examples

In this post, I'll list and describe all of the most important and frequently used library functions in the C programming language. The library functions make programming simple. So, without further ado, let's begin with a quick overview of "library functions in C."

What are library functions in C programming?

In the C programming language, library functions are pre-defined or inbuilt functions that have already been defined by the C developer and are included in multiple header files. To use any library function in your C program, you must include the header file or the location where the function is defined.

As a result, in this post, I will only list the most important and frequently used library functions in the C programming language. Understanding or having knowledge of these library functions simplifies your C programming career.

How does the library function help you save time?

When coding in the C programming language, using the library function instead of self-code can save you a lot of time. The "strlen" library function, for example, can be used to determine the length of a string or the number of characters available in a string. Consider the following program as an example:

#include <stdio.h>
#include <string.h>

int main()
{
   char str[20] = "Hello there";
   int x = strlen(str);

   printf("Length = %d", x);
   return 0;
}

This program generated the following output.

Length = 11

However, you can accomplish the same task using self-defined code as follows:

#include <stdio.h>

int main()
{
   char str[20] = "Hello there";
   int x=0, i;

   for(i=0; str[i] != '\0'; i++)
      x++;

   printf("Length = %d", x);
   return 0;
}

Another thing to keep in mind is that in some cases, such as when we need to write data to the output console, we must use the "printf()" function; or when we need to read data from the user, we must use the "scanf()" function; and so on.

Please keep in mind that in order to use a library function in your C program, you must include the associated header file. The function definition is contained in the header file. Like in the previous program, I included the "string.h" header file to use the "strlen()" library function.

List of essential library functions in C

The C programming language includes more than 260 library functions. The majority of them are rarely used. As a result, for your convenience, I'll list only the most important and frequently used library functions.

printf()

The printf() function writes the arguments that make up the argument list to the standard output, as specified by the format string.

The string pointed to by format consists of the two types of items. The first type is made up of the characters that will be printed on screen. And the second type contains format specifiers that define the way the arguments can be displayed. A format specifier begins with a percent sign (%) and ends with the format code, such as:

printf("Hello %c %d %s", 'c', 100, "there!");

The following table lists the possible codes for format:

Code Format
%a Hexadecimal output in the form of 0xh.hhhp+d
%A Hexadecimal output in the form of 0Xh.hhhP+d
%c Character
%d Signed decimal integers
%i Signed decimal integers
%e Scientific notation (lowercase e)
%E Scientific notation (uppercase E)
%f Decimal floating point
%F Decimal floating point (produces uppercase INF, INFINITY, or NAN only when applied to infinity or a value that is not a number. The %f specifier produces the lowercase equivalents)
%g Uses %e or %f, whichever is shorter
%G Uses %E or %F, whichever is shorter
%o Unsigned octal
%s Strings of characters
%u Unsigned decimal integers
%x Unsigned hexadecimal (lowercase letters)
%X Unsigned hexadecimal (uppercase letters)
%P Displays a pointer
%n The associated argument must be a pointer to an integer. This specifier causes the number of the characters written (up to the point at which %n is encountered) to be stored in that integer
%% Prints a percent sign

printf() Syntax

int printf(const char *format, arg-list);

Header file: stdio.h

printf() Example

C Code
#include<stdio.h>
int main()
{
   int i = 10;
   printf("The value of 'i' is %d", i);
   return 0;
}
Output
The value of 'i' is 10

scanf()

The scanf() function is a general-purpose input routine that reads the stdin stream and stores data in the variables specified in its arguments list. It can read all of the built-in data types and convert them to the correct internal format automatically.

The following table lists the scanf() format specifiers:

Code Meaning
%a Read a floating-point value
%A Same as %a
%c Read a single character
%d Read a decimal integer
%i Read an integer in either decimal, octal, or hexadecimal format
%e Read a floating-point number
%E Same as %e
%f Read a floating-point number
%F Same as %f
%g Read a floating-point number
%G Same as %g
%o Read an octal number
%s Read a string
%x Read a hexadecimal number
%X Same as %x
%P Read a pointer
%n Receive an integer value equal to the number of characters read so far
%u Read an unsigned decimal integer
%[] Scan for a set of characters
%% Read a percent sign

scanf() Syntax

int scanf(const char *format, arg-list);

Header file: stdio.h

scanf() Example

C Code
#include <stdio.h>

int main()
{
   char str[80];
   int num;

   printf("Enter the string: ");
   scanf("%s", str);

   printf("Enter a number: ");
   scanf("%d", &num);

   printf("\n\nThe given string: %s", str);
   printf("\nThe given number: %d", num);

   return 0;
}
Output
Enter the string: fresherearth
Enter a number: 10


The given string: fresherearth
The given number: 10

The program first asks the user to enter the string, so the user needs to type a string, say "fresherearth," and hit the ENTER key. Now the program again asks the user to enter a number; therefore, the user needs to type a number, say 10, and hit the ENTER key to get the exact same output as the above one.

sqrt()

The "sqrt()" method is used when we need to find the square root of a number.

sqrt() Syntax

double sqrt(double arg);

Header file: math.h

sqrt() Example

C Code
#include <stdio.h>
#include <math.h>

int main()
{
   float x, sr;
   
   printf("Enter a number: ");
   scanf("%f", &x);

   sr = sqrt(x);
   printf("\nSquare root of %f = %f", x, sr);

   return 0;
}
Output
Enter a number: 36

Square root of 36.000000 = 6.000000

You can use ".2" before the format "f" code to display only the two digits after the decimal.

pow()

The "pow()" method returns the power of a given number.

pow() Syntax

double pow(double x, double y)

Header file: math.h

pow() Example

C Code
#include <stdio.h>
#include <math.h>
int main()
{
   double base = 10, power = 3;
   printf("%.2lf", pow(base, power));
   return 0;
}
Output
1000.00

islower()

The "islower()" function is used to check if the specified character is in lowercase. It returns non-zero if the specified character is in lowercase.

islower() Syntax

int islower(int ch);

Header file: ctype.h

islower() Example

C Code
#include <stdio.h>
#include <ctype.h>
int main()
{
   char a = 'X', b = 'x';
   
   if(islower(a))
      printf("'a' contains lowercase letter.\n");
   if(islower(b))
      printf("'b' contains lowercase letter.\n");
      
   return 0;
}
Output
'b' contains lowercase letter.

isupper()

The "isupper()" function is used to check if the specified character is in uppercase. It returns non-zero if the specified character is in uppercase.

isupper() Syntax

int isupper(int ch);

Header file: ctype.h

isupper() Example

C Code
#include <stdio.h>
#include <ctype.h>
int main()
{
   char a = 'X', b = 'x';
   
   if(isupper(a))
      printf("'a' contains uppercase letter.\n");
   if(isupper(b))
      printf("'b' contains uppercase letter.\n");
      
   return 0;
}
Output
'a' contains uppercase letter.

tolower()

The tolower() function returns the lowercase equivalent of the given character.

tolower() Syntax

int tolower(int ch);

Header file: ctype.h

tolower() Example

C Code
#include <stdio.h>
#include <ctype.h>
int main()
{
   char a = 'X', b = 'x';

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

   return 0;
}
Output
x
x

toupper()

The toupper() function returns the uppercase equivalent of the given character. The syntax and example are similar to the "tolower()" function.

isalnum()

The "isalnum()" function determines whether a given character is an alphanumeric character.

isalnum() Syntax

int isalnum(int ch);

Header file: ctype.h

isalnum() Example

C Code
#include <stdio.h>
#include <ctype.h>
int main()
{
   char a = 'x', b = '2', c = '$';

   if(isalnum(a))
      printf("'a' contains the alphanumeric character.\n");
   if(isalnum(b))
      printf("'b' contains the alphanumeric character.\n");
   if(isalnum(c))
      printf("'c' contains the alphanumeric character.\n");

   return 0;
}
Output
'a' contains the alphanumeric character.
'b' contains the alphanumeric character.

isalpha()

The "isalpha()" function is used to check if the specified character is an alphabet.

isalpha() Syntax

int isalpha(int ch);

Header file: ctype.h

isalpha() Example

C Code
#include <stdio.h>
#include <ctype.h>
int main()
{
   char a = 'x', b = '2';

   if(isalpha(a))
      printf("'a' contains the alphabetic character.\n");
   if(isalpha(b))
      printf("'b' contains the alphabetic character.\n");

   return 0;
}
Output
'a' contains the alphabetic character.

isdigit()

The "isdigit()" function is used to check if the specified character is a digit.

isdigit() Syntax

int isdigit(int ch);

Header file: ctype.h

isdigit() Example

C Code
#include <stdio.h>
#include <ctype.h>
int main()
{
   char a = 'x', b = '2';

   if(isdigit(a))
      printf("'a' contains the digit.\n");
   if(isdigit(b))
      printf("'b' contains the digit.\n");

   return 0;
}
Output
'b' contains the digit.

strlen()

The "strlen()" function returns the length of the specified string. The following is its general form.

size_t strlen(const char *str);

Header file: string.h

For example, the following code fragment returns the length of the string "fresherearth" and initializes the variable "len."

len = strlen("fresherearth");

strcpy()

The "strcpy()" function is used to copy a string. The following is its general form:

char *strcpy(char *str1, const char *str2);

Header file: string.h

For example, the following code fragment copies the text "cracker" into the string mystr.

strcpy(mystr, "cracker");

strcmp()

The strcmp() function lexicographically compares two strings and returns an integer based on the outcome, as shown here in the following table:

Value Meaning
Less than zero str1 is less than str2
0 str1 is equal to str2
Greater than zero str1 is greater than str2

The following is the general form of the "strcmp()" function.

int strcmp(const char *str1, const char *str2);

Header file: string.h

For example:

C Code
#include <stdio.h>
#include <string.h>
int main()
{
   printf("%d \n", strcmp("codes", "cracker"));
   printf("%d \n", strcmp("cracker", "codes"));
   printf("%d \n", strcmp("fresherearth", "fresherearth"));

   return 0;
}
Output
-1
1
0

strcat()

The "strcat()" function is used to concatenate a copy of the second string to the first string and terminate the first string with a null. The following is its general form:

char *strcat(char *str1, const char *str2);

Header file: string.h

For example:

C Code
#include <stdio.h>
#include <string.h>
int main()
{
   char a[] = "codes", b[] = "cracker";

   strcat(a, b);
   printf("%s", a);

   return 0;
}
Output
fresherearth

strchr()

The "strchr()" function is used to find the first occurrence of the specified character in a specified string. The following is its general form:

char *strchr(const char *str, int ch);

Header file: string.h

For example:

C Code
#include <stdio.h>
#include <string.h>
int main()
{
   char a[] = "Hello there", *p;
   p = strchr(a, 'e');

   printf(p);
   printf("\n");
   printf("%d", *p);
   printf("\n");
   printf("%c", *p);

   return 0;
}
Output
ello there
101
e

101 is the ASCII value of the letter "e."

strstr()

The "strstr()" function is similar to "strchr()," except that it is used to find the first occurrence of the specified sub-string in a specified string. The following is its general form:

char *strstr(const char *str1, const char *str2);

Header file: string.h

putc()

The putc() function writes the character contained in the least significant byte of ch to the output stream pointed to by stream. The following is its general form:

int putc(int ch, FILE *stream);

Header file: stdio.h

To learn about file handling in C, refer to its separate post.

putchar()

The putchar() function writes the character contained in the least significant byte of ch to stdout. The following is its general form:

int putchar(int ch);

Header file: stdio.h

puts()

The puts() function writes the string pointed to by str to the standard output device. The following is its general form:

int puts(const char *str);

Header file: stdio.h

For example:

C Code
#include <stdio.h>
#include <string.h>
int main()
{
   char str[] = "Hello there";
   puts(str);
   return 0;
}
Output
Hello there

getc()

The getc() function reads the specified input stream and returns the next character from that stream while also incrementing the file position indicator. The following is its general form:

int getc(FILE *stream);

Header file: stdio.h

For example:

C Code
#include <stdio.h>
#include <stdlib.h>
int main()
{
   FILE *fp;
   char fname[20], ch;

   printf("Enter filename: ");
   gets(fname);

   fp = fopen(fname, "r");
   if (fp == NULL)
   {
      printf("Error opening the file.\n");
      return 0;
   }

   printf("\nThe file '%s' contains:\n", fname);
   while ((ch = getc(fp)) != EOF)
      printf("%c", ch);

   fclose(fp);
   return 0;
}
Output
Enter filename: fresherearth.txt

The file 'fresherearth.txt' contains:
Hello there,

The above program receives the name of the file from the user at program runtime. When the user types the file name and hits the ENTER key, then the program reads that file and prints its content back on the output console. The file must be available inside the current directory, which is the directory where the above C source code is saved.

Before running the above C source code, I created a file named "fresherearth.txt" in my current directory and wrote the text "Hello there" in it.

getchar()

The getchar() function returns the next character from stdin. The following is its general form:

int getchar(void);

Header file: stdio.h

gets()

The gets() function reads the characters from stdin and places them into the character array pointed to by str. The general form of this function is as follows:

char *gets(char *str);

Header file: stdio.h

For example:

C Code
#include <stdio.h>
int main()
{
   char str[120];
   printf("Enter the string: ");
   gets(str);
   printf("\nYou entered: %s", str);
   return 0;
}
Output
Enter the string: Hey, what's up?

You entered: Hey, what's up?

abs()

The "abs()" function is used when we need to find the absolute value (positive value) of a number. The following is its general form:

int abs (int x);

Header file: stdlib.h

exit()

The "exit()" function is used to terminate the program. The following is its general form:

void exit(int status)

Header file: stdlib.h

rand()

The "rand()" function is used to generate random numbers. The following is its general form:

int rand(void)

Header file: stdlib.h

srand()

The "srand()" function is used to seed the random number generator using "rand()." The following is its general form:

void srand(unsigned int seed)

Header file: stdlib.h

calloc()

The calloc() function allocates memory, the size of which is equal to num * size. That is, calloc() allocates sufficient memory for an array of num objects of size size. The following is its general form:

void *calloc(size_t num, size_t size);

Header file: stdlib.h

malloc()

malloc() returns a pointer to the first byte of a heap-allocated memory region of size bytes. If there is not enough heap memory to satisfy the request, malloc() returns a null pointer. Before attempting to use a return value, it is always essential to confirm that it is not null. Typically, attempting to use a null pointer will cause a system crash. The following is its general form:

void *malloc(size_t size);

Header file: stdlib.h

free()

The free() function returns the memory pointed to by ptr to the heap. This makes the memory available for future allocation. The following is its general form:

void free(void *ptr);

Header file: stdlib.h

fopen()

The fopen() function is used to open the file and returns the associated stream. The value of "mode" specifies the types of operations that can be performed on a file. Here is a list of valid mode values that can be given when the "fopen()" function is used to open a file.

The following is its general form:

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

Header file: stdio.h

fclose()

The fclose() function is used to close the file associated with the stream and then flush its buffer. The following is its general form:

int fclose(FILE *stream);

Header file: stdio.h

fgetc()

Similar to "getc()," except that it works with files. The following is its general form:

int fgetc(FILE *stream);

Header file: stdio.h

fgets()

Similar to "gets()," except that it works with files. The following is its general form:

char *fgets(char *str, int num, FILE *stream);

Header file: stdio.h

fputc()

Similar to "putc()," except that it works with files. The following is its general form:

int fputc(int ch, FILE *stream);

Header file: stdio.h

fputs()

Similar to "puts()," except that it works with files. The following is its general form:

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

Header file: stdio.h

fprintf()

Similar to "printf()," except that it works with files. The following is its general form:

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

Header file: stdio.h

fscanf()

Similar to "scanf()," except that it works with files. The following is its general form:

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

Header file: stdio.h

feof()

The feof() function is used to determine whether the end of the file associated with the stream has been reached. The following is its general form:

int feof(FILE *stream);

Header file: stdio.h

fgetpos()

The fgetpos function is used to store the current value of the file position indicator in the object pointed to by position. The object pointed to by the position must be of type fpos_t. The general form of this function is as follows:

int fgetpos(FILE *stream, fpos_t *position);

Header file: stdio.h

fsetpos()

The fsetpos() function moves the file position indicator to the location specified by the object pointed to by position. This value must have been previously obtained through a call to fgetpos(). After the fsetpos() is executed, the end-of-file indicator is reset. Also, any previous call to ungetc() is nullified. The following is its general form:

int fsetpos(FILE *stream, const fpos_t *position);

Header file: stdio.h

fread()

The fread() function reads count objects, each of which is size bytes in length, from the stream pointed to by stream and stores them in the array pointed to by buf. The following is its general form:

size_t fread(void *buf, size_t size, size_t count, FILE *stream);

Header file: stdio.h

fwrite()

The fwrite() function writes count objects, each of which is size bytes in length, to the stream pointed to by stream from the character array pointed to by buf. The following is its general form:

size_t fwrite(const void *buf, size_t size, size_t count, File *stream);

Header file: stdio.h

ferror()

The ferror() function is used to check for file errors on a given stream. The following is its general form.

int ferror(FILE *stream);

Header file: stdio.h

fseek()

The fseek() function is used to set the file position indicator associated with the stream according to the values of offset and origin. The following is its general form:

int fseek(FILE *stream, long int offset, int origin);

Header file: stdio.h

The "SEEK_SET" seeks from the start of the file, the "SEEK_CUR" seeks from the current position, and the "SEEK_END" seeks from the end of the file.

ftell()

The ftell() function returns the current value of the file position indicator for the specified stream. The following is its general form:

long int ftell(FILE *stream);

Header file: stdio.h

rewind()

The rewind() function moves the file position indicator to the beginning of the stream that was given as an argument. The following is its general form:

void rewind(FILE *stream);

Header file: stdio.h

remove()

The remove() function deletes the file. The following is its general form:

int remove(const char *fname);

Header file: stdio.h

rename()

The rename() function is used to rename the file. The following is its general form:

int rename(const char *oldname, const char *newname);

Header file: stdio.h

time()

The time() function returns the current calendar time of the system.

The time() function can be called either with a null pointer or with a pointer to a variable of type time_t. The following is its general form:

time_t time(time_t *time);

Header file: time.h

asctime()

The asctime() function returns a pointer to a string that contains the information stored in the structure pointed to by ptr, converted into the following form:

day month date hours:minutes:seconds year

The following is its general form:

char *asctime(const struct tm *timeptr)

Header file: time.h

For example:

#include <time.h>
#include <stdio.h>
int main()
{
   struct tm *ptr;
   time_t lt;
   lt = time(NULL);
   ptr = localtime(&lt);
   printf(asctime(ptr));
   return 0;
}

The following snapshot shows the sample output produced by this program.

c library function asctime example

The current date is February 14, 2023. As a result, I got this output. However, depending on the date and time you run the above program, you may get different results.

C Quiz


« Previous Tutorial Next Tutorial »