C Programming

40 C programming examples

C programming language is one of the popular programming languages for novice programmers. It is a structured programming language that was mainly developed for UNIX operating system. It supports different types of operating systems, and it is very easy to learn. 40 useful C programming examples have been shown in this tutorial for the users who want to learn C programming from the beginning.

  1. Print output using printf()
  2. Basic variable types
  3. If-else statement
  4. Switch-case statement
  5. For loop
  6. While loop
  7. Logical operators
  8. Bit-wise operator
  9. Change data type by typecasting
  10. Use of simple function
  11. Use of function with argument
  12. Enumeration
  13. Array
  14. Pointer
  15. Use of function pointer
  16. Memory allocation using malloc()
  17. Memory allocation using calloc()
  18. Use of const char*
  19. Copy string using strcpy()
  20. Compare string using strcmp()
  21. Substring using strstr()
  22. Split string using strtok()
  23. Structure
  24. Count length using sizeof()
  25. Create a file
  26. Write into the file
  27. Read from the file
  28. Set seek position into the file
  29. Read directory list using readdir()
  30. Read file information using stat function
  31. Use of pipe
  32. Create a symbolic link
  33. Use of command-line arguments
  34. Use of fork and exec
  35. Use of signals
  36. Read date and time gettimeofday()
  37. Use of macros
  38. Use of typedef
  39. Use of constant
  40. Error handling using errno and perror

Print output using printf():

The printf() is a built-in function of C used to print the output into the console. Every built-in function of the C language has been implemented inside a particular header file. The <stdio.h> header file is required to include in the source code to use printf() function and many other built-in functions. The following code will print a simple text message.

//Include necessary header file
#include <stdio.h>

//Main function
int main()
{
    //Print a text message in the console
    printf("Welcome to LinuxHint.\n");
    return 0;
}

The following output will appear after executing the above code.

Go to top

Basic variable types:

C Programming language’s commonly used data types are bool, int, float, double, and char. The bool data type is used to store true or false values. The int data type is used to store integer numbers. The float data type is used to store small fractional numbers. The double data type is used to store large fractional numbers. The char data type is used to store a single character. %d is used to print the Boolean and integer data. %f is used to print the float data. %lf is used to print double data. %c is used to print character data. The uses of these five data types have shown in the following example. Here, five types of data have initialized and printed the values in the console.

//Include necessary header file
#include <stdio.h>

//Main function
int main()
{
    //Define different types of variables
    bool flag = true;
    int n = 25;
    float fVar = 50.78;
    double dVar = 4590.786;
    char ch = 'A';

    //Print the values of the variables
    printf("The boolean value is %d\n", flag);
    printf("The integer value is %d\n", n);
    printf("The float value is %f\n", fVar);
    printf("The double value is %lf\n", dVar);
    printf("The char value is %c\n", ch);
    return 0;
}

The following output will appear after executing the above code.

Go to top

If-else statement:

The conditional statement is implemented by using the ‘if-else’ statement. If the condition returns true, then the statement of the ‘if’ block executes; otherwise, the statement of ‘else’ block executes. Single or multiple conditions can be used in the ‘if’ condition by using logical operators. The use of a simple ‘if-else’ statement has shown in the following example. The condition of the ‘if’ will check the input number is less than 100 or not. If the input value is less than 100, then a message will be printed. If the input value is greater than or equal to 100, then another ‘if-else’ statement will check the input value is even or odd.

//Include necessary header file
#include <stdio.h>

//Main function
int main()
{

    //Declare integer variable
    int n;
    //Take number value from the user
    printf("Enter a number: ");
    scanf("%d", &n);

    //Check the number is less than or equal to 100
    if(n < 100)
        printf("%d is less than 100.\n", n);
    else
    {
        //Check the number is even or odd
        if(n % 2 == 0)
            printf("%d is even and greater than or equal to 100.\n", n);
        else
            printf("%d is odd and greater than or equal to 100.\n", n);
    }

    return 0;
}

The following output will appear after executing the above code if the input value is 67.

The following output will appear after executing the above code if the input value is 456.

The following output will appear after executing the above code if the input value is 567.

Go to top

Switch-case statement:

The ‘switch-case’ statement can be used as an alternative to the ‘if-elseif-else’ statement. But all types of comparison can’t be done using the ‘switch-case’ statement. The simple use of the ‘switch-case’ statement has shown in the following example. The ‘switch-case’ statement of this code will print the CGPA value based on the matching ID value taken from the console. The message of the default section will be printed if the input ID value does not match any ‘case’ statement.

//Include necessary header file
#include <stdio.h>

//Main function
int main()
{
    //Declare integer variable
    int ID;
    //Take ID value from the console
    printf("Enter the ID:");
    scanf("%d", &ID);

    //Print message based on ID
    switch(ID)
    {
        case 1100:
            printf("The CGPA of %d is 3.79\n", ID);
            break;
        case 1203:
            printf("The CGPA of %d is 3.37\n", ID);
            break;
        case 1570:
            printf("The CGPA of %d is 3.06\n", ID);
            break;
        default:
            printf("ID does not exist.\n");
    }
    return 0;
}

The following output will appear after executing the above code for the ID value 1203.

Go to top

For loop:

The loop is used to execute some statements multiple times. The ‘for’ loop is one of the useful loops of any Programming that contains three parts. The first part contains an initialization statement, the second part contains termination conditions, and the third contains an increment or decrement statement. The use of a simple ‘for’ loop in C has shown in the following example. The loop will iterate 50 times and print those numbers within 1 to 50, which are divisible by 3 but not divisible by 5. ‘if’ statement has been used to find out the numbers.

//Include necessary header file
#include <stdio.h>

//Main function
int main()
{
    //Declare an integer
    int n;
    //Print the specific numbers
    printf("The numbers divisible by 3 and not divisible by 5 within 1 to 50:\n");
    for(n=1; n <= 50; n++)
    {
        if((n % 3) == 0 && (n % 5) != 5)
        {
            printf("%d ",n);
        }
    }
    //Add newline
    printf("\n");
    return 0;
}

The following output will appear after executing the above code.

Go to top

While loop:

Another useful loop of any programming language is the ‘while loop. The counter variable of this loop is initialized before the loop. The termination condition is defined at the beginning of the loop. The increment or decrement statement is defined inside the loop. The use of a while loop in C has shown in the following example. The loop is used to generate 10 random numbers within the range of 1 to 50.

//Include necessary header files
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

//Main function
int main()
{
    //Declare integer variables
    int n = 1, random;

    //Initialization to generate random number.
    srand(time(NULL));
    printf("Generated 10 random numbers are: \n");
    while(n <= 10)
    {
        //Generate a random integer within 1 to 50
        random = rand() % 50;
        printf("%d ", random);
        n++;
    }
    //Add newline
    printf("\n");
    return 0;
}

The following output will appear after executing the above code.

Go to top

Logical operators:

The logical operators are used to define multiple conditions in the conditional statement. Three types of logical operators are mainly used in any programming language. These are logical OR, logical AND, and logical NOT. The logical OR returns true when any of the conditions are true. The logical AND returns true when all of the conditions are true. The logical NOT returns true if the condition is false and returns false if the condition is true. The uses of logical OR and AND have shown in the following example. The logical OR is used in the ‘if’ statement to determine the selected person based on the ID value. The logical AND is used in the ‘if’ statement to determine the group based on age value.

//Include necessary header file
#include <stdio.h>

//Main function
int main()
{

    //Declare integer variables
    int id, age;

    //Take the id and age values
    printf("Enter your ID: ");
    scanf("%d", &id);
    printf("Enter your age: ");
    scanf("%d", &age);

    //Display message based on logical OR operator
    if( id == 56 || id == 69 || id == 92)
        printf("You are selected.\n");
    else
        printf("You are in waiting list.\n");

    //Display message based on logical AND operator
    if (id == 56 && age == 25)
        printf("You are in Group-1\n");
    return 0;
}

The following output will appear after executing the above code for the ID value, 56, and the age value, 25.

The following output will appear after executing the above code for the ID value, 69, and the age value, 36.

Go to top

Bit-wise operator:

The bit-wise operators are used to perform binary operations. Five types of bit-wise operators have shown in the following example. These are bit-wise OR, bit-wise AND, bit-wise XOR, right shift, and left shift. The output will be generated based on the two numbers, 5 and 8.

//Include necessary header file
#include <stdio.h>

//Main function
int main()
{
//Initialize two numbers
int number1 = 5, number2 = 8;
//Perform different types of bit-wise operations
printf("The reusult of bit-wise OR = %d\n", number1|number2);
printf("The reusult of bit-wise AND = %d\n", number1&number2);
printf("The reusult of bit-wise XOR = %d\n", number1^number2);
printf("The reusult of right shift by 1 = %d\n", number1>>1);
printf("The reusult of left shift by 2 = %d\n", number1<<2);
return 0;
}

The following output will appear after executing the above code. The binary value of 5 is 0101, and the binary value of 8 is 1000. The bit-wise OR of 0101 and 1000 is 1101. The decimal value of 1101 is 13. The bit-wise AND of 0101 and 1000 is 0000. The decimal value of 0000 is 0. The bit-wise XOR of 0101 and 1000 is 1101. The decimal value of 1101 is 13. The right shift value of 0101 is 0010 that is 2 in decimal. The left shift value of 1000 is 10000 that is 20 in decimal.

Go to top

Change data type by typecasting:

The data type of the variable can be changed by using typecasting. The data type that requires change will need to define within the first brackets for typecasting. The way of typecasting in C has shown in the following language. Two integer numbers have been defined in the code. The division of these numbers is an integer converted into a float using type casting and stored in a float variable.

//Include necessary header file
#include <stdio.h>

//Main function
int main()
{
//Initialize two integer variables
int a = 25, b = 2;
//Declare a float variable
float result;

//Store the result of division after type casting
result = (float) a/b;
printf("The result of division after type casting : %0.2f\n", result );

return 0;
}

The following output will appear after executing the above code.

Go to top

Use of simple function:

Sometimes, the same block of statements is required to execute multiple times from different program parts. The way to declare a block of code with a name is called a user-defined function. A function can be defined without any argument or with one or more arguments. A simple function without any argument has shown in the following example. If the user-defined function is defined below the main() function, then the function name will be required to declare at the top of the main() function; otherwise, there is no need to declare the function. The message() function without any argument is called before taking the input and the second time after taking input.

//Include necessary header file
#include <stdio.h>

//Declare the function
void message();
//Intialize a global variable
char text[50] = "";

//Main function
int main () {

    printf("The output of the function before input:\n");
    message();

    //Take string input from the console
    printf("Enter a text: ");
    fgets(text, 50, stdin);
    printf("The output of the function after input:\n");
    message();
    return 0;
}

//Define a function without any argument
void message() {

    //Check the value of the character array
    if(text[0] == 0)
        printf("Hello\n");
    else
        printf("%s\n", text);
}

The following output will appear after executing the above code. The message() function has printed, ‘Hello’ when text[0] contains an empty string, and the value of the text variable has printed when the message() function has been called a second time.

Go to top

Use of function with the argument:

The use of function with the argument has shown in the following example. A function named sum() with two integer arguments has been declared here. Two integer numbers will be taken from the console, and the sum() function will be called with the input values. The sum() function will calculate the sum of all numbers starting from the first argument value to the second argument value.

//Include necessary header file
#include <stdio.h>

//Declare the function
int sum(int start, int end);

//Main function
int main () {

    //Declare integer variables
    int st, ed, result;

    printf("Enter the starting value: ");
    scanf("%d", &st);

    printf("Enter the ending value: ");
    scanf("%d", &ed);

    //Call the function with arguments to calculate the sum
    result = sum(st, ed);

    printf("The sum of %d to %d is %d\n", st, ed, result);
    return 0;
}

//Define a function to calculate the sum of the specific range
int sum(int start, int end) {

    //Define local variables
    int i, output = 0;
    //Iterate the loop to calculate the sum
    for(i = start; i <= end; i++)
    {
        output = output + i;
    }
    return output;
}

The following output will appear after executing the above code for the input values 1 and 10. The sum of 1 to 10 is 55 that has printed in the output.

Go to top

Enumeration:

The way of declaring user-defined data type in C is called enumeration. It helps to maintain the code easily by defining names for constant values. The ‘enum’ keyword is used to declare enumeration. The use of enumeration in C has shown in the following example. The short form of month names is used as the names of the enumeration variable named monthDays. The ‘switch-case’ statement is used here to print messages based on enum values.

//Include necessary header file
#include<stdio.h>

//Initialize the enum with values
enum monthDays{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
int main()
{
          //Declare an enum variable
          enum monthDays mday;
          //Set an enum value
          mday = Feb;
          //Print message based on enum value
          switch (mday)
{
          case 0:
          printf("Total days in January is 31.\n");
          break;
          case 1:
          printf("Total days in February is 28.\n");
          break;
          case 3:
          printf("Total days in March is 31.\n");
          break;

          /*The case values will be added here for other months */

          default:
          printf("Invalid value.");
}
          return 0;
}

The following output will appear after executing the above code.

Go to top

Array:

The array variable is used in C to declare a list of multiple values of the same data type. An array can be one-dimensional or multi-dimensional. The uses of one-dimensional and two-dimensional arrays have shown in the following example. A one-dimensional array of 3 floating-point numbers has been declared and initialized with values at the beginning of the code. Next, the particular value of the array has been printed. Next, a two-dimensional array of characters has been declared and initialized that contains 5 string values of the maximum of 3 characters. All the values of the two-dimensional array have been printed using the loop.

//Include necessary header file
#include<stdio.h>

int main(){
    //Initialize integer variables
    int i=0, j=0;
    //Declare float variable
    float cgpa[3];

    //Initialize the array values seperately
    cgpa[0] = 3.56;
    cgpa[1] = 3.78;
    cgpa[2] = 3.89;

    //Print the specific array value
    printf("The CGPA of third student is %0.2f\n", cgpa[2]);

    //Inilialize the array values
    char grades[5][3] = {"B+", "A-", "C", "A+", "C+"};

    //Display all array values using loop
    printf("All values of the second array:\n");
        for(i = 0; i < 5; i++)
        {
            for(j = 0; j < 3; j++)
            {
                printf("%c",grades[i][j]);
            }
            printf("\n");
    }
    return 0;
}

The following output will appear after executing the above code.

Go to top

Pointer:

The pointer variable is used to store the address of another variable. A pointer points to a particular memory location. The previous or next memory location can be accessed by decrementing or incrementing the pointer value. The code executes faster by using a pointer because it saves memory space. The simple use of the pointer variable has shown in the following example. A float-type pointer has been declared in the code, and the address of a float variable has been stored in it later. The value of the pointer has been printed before and after the initialization.

//Include necessary header file
#include <stdio.h>

int main () {

//Initialize float variable
float num = 5.78;
//Declare float pointer
float *ptrVar;

printf("The value of pointer before initialization : %p\n", ptrVar);

//Initialize the address of the float variable into the pointer variable
ptrVar = &num;

printf("The address of the float variable: %p\n", &num );
printf("The value of the pointer after initialization : %p\n", ptrVar );
printf("The value of the variable pointed by the pointer: %0.2f\n", *ptrVar );

return 0;
}

The following output will appear after executing the above code. In the output, the value of the pointer and the address of the float variable are the same. The value of the variable pointed by the pointer is equal to the value of the float variable.

Go to top

Use of function pointer:

The code of any function is stored in the memory, and every function can be accessed by memory address. A function pointer is used to store the address of a function, and the function can be called by using the function pointer. The use function pointer in C has shown in the following example. A user-defined function has been declared and called by the function pointer in two different ways in the code. The function pointer name is used to call the function when the function’s name has been assigned to the function pointer. The function pointer has used to call the function when the function’s address has been assigned to the function pointer.

//Include necessary header file
#include <stdio.h>

//Define the first function
void check(int n)
{
if(n % 2 == 0)
printf("%d is even number.\n", n);
else
printf("%d is odd number.\n", n);
}

int main()
{
int num;
//Take a number
printf("Enter a number: ");
scanf("%d", &num);

//The pointer point to the function
void (*function_ptr1)(int) = check;

//Call the function using function pointer name
function_ptr1(num);

//The pointer point to the function address
void (*function_ptr2)(int) = &check;

//Call the finction using function pointer
(*function_ptr2)(num+1);
return 0;
}

The following output will appear after executing the above code for the input value, 8.

Go to top

Memory allocation using malloc():

The particular block of memory can be allocated dynamically in C by using the malloc() function. It returns a pointer of the void type that can be converted into any type of pointer. The block of memory allocated by this function is initialized by garbage value by default. The use of the malloc() function has shown in the following example. The integer pointer has been declared in the code that has been used later to store the integer values. The malloc() function has been used in the code to allocate memory by multiplying the input value by the size of the integer. The first ‘for’ loop has been used to store values in the pointer array, and the second ‘for’ loop has been used to print the values of the pointer array.

//Include necessary header files
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *intptr;
//Take the total number of elements from the console
printf("Enter the total number of elements:");
scanf("%d",&n);
//Allocate memory dynamically using malloc() function
intptr = (int*)malloc(n * sizeof(int));

//Initialize the first element
intptr[0] = 5;

//Initilize the elements of the pointer array
for (i = 1; i < n; i++)
{
intptr[i] = intptr[i-1] + 5;
}
//Display the values of the pointer array
printf("The elements of the array are: ");
for (i = 0; i < n; i++)
{
printf("%d ", intptr[i]);
}
printf("\n");
return 0;
}

The following output will appear after executing the above code for the input value, 5.

Go to top

Memory allocation using calloc():

The calloc() function works the malloc() function, but it initializes each block with a default value but the malloc() function initializes the block with the garbage value. Another difference between the calloc() and malloc() function is that the calloc() function contains two arguments and malloc() function contains one argument. The use of the calloc() function has shown in the following example. Like the previous example, the integer pointer has been declared in the code that has been used later to store the integer values. The calloc() function has been used in the code to allocate memory based on the first argument value where the input value has passed and the argument’s size where the integer has passed. The first ‘for’ loop has been used to store values in the pointer array, and the second ‘for’ loop has been used to print the values of the pointer array.

//Include necessary header files
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *intptr;
//Take the total number of elements from the console
printf("Enter the total number of elements:");
scanf("%d",&n);
//Allocate memory dynamically using calloc() function
intptr = (int*)calloc(n, sizeof(int));

//Initilize the elements of the pointer array
for (i = 1; i < n; i++)
{
intptr[i] = intptr[i-1] + 2;
}
//Display the values of the pointer array
printf("The elements of the array are: ");
for (i = 0; i < n; i++)
{
printf("%d ", intptr[i]);
}
printf("\n");
return 0;
}

The following output will appear after executing the above code for the input value, 4.

Go to top

Use of const char*:

The const char* variable is used to define the constant string value. The simple use of this type of variable has shown in the following example. Here, ‘%p’ has been used to print the address of the pointer variable, and ‘%s’ has been used to print the value pointer by the pointer variable.

//Include necessary header file
#include<stdio.h>

int main ()
{
//Initialize the char pointer
const char *charPtr = "hello";

//Display the pointer address
printf("The addresss of the pointer: %p\n", charPtr);
//Display the value of the pointer
printf("The value pointed by the pointer: %s\n", charPtr);
}

The following output will appear after executing the above code.

Copy string using strcpy():

The strcpy() function is used in C to copy a string value into another string variable. This function takes two arguments. The first argument contains the variable name in which the string value will be copied. The second argument contains the string value or the string variable’s name from where the string value will be copied. The use of the strcpy() function has shown in the following example. Two arrays of characters have been declared in the code. A string value will be taken into the character array named strdata1 and copied to the character array named strdarta2. The value of the strdata2 will be printed later.

//Include necessary header files
#include <stdio.h>
#include <string.h>

int main() {

//Declare two arrays of characters
char strdata1[50], strdata2[50];

printf("Enter a string: ");
//Take string input from the console and store into a character array
fgets(strdata1, 50, stdin);

printf("The original string value: %s", strdata1);

//Copy the string value into another character array
strcpy(strdata2, strdata1);

printf("The copied string value: %s", strdata2);

return 0;
}

The following output will appear after executing the above code.

Go to top

Compare string using strcmp():

The strcmp() function is used to compare two string values in C. This function takes two string values in two arguments. It returns 0 if two string values are equal. It returns 1 if the first string value is greater than the second string value. It returns -1 if the first string value is less than the second string value. The use of this function has shown in the following example. Two input values have been compared with this function in the code.

//Include necessary header files
#include <stdio.h>
#include <string.h>

int main() {

//Declare two arrays of characters
char strdata1[50], strdata2[50];

printf("Enter the first string: ");
//Take string input from the console and store into a character array
fgets(strdata1, 50, stdin);
//Remove the newline from the input
strdata1[strlen(strdata1)-1] = '\0';

printf("Enter the second string: ");
//Take string input from the console and store into a character array
fgets(strdata2, 50, stdin);
//Remove the newline from the input
strdata2[strlen(strdata2)-1] = '\0';

if(strcmp(strdata1, strdata2) == 0)
printf("The %s and %s are equal.\n", strdata1, strdata2);
else if(strcmp(strdata1, strdata2) > 0)
printf("The %s is greater than %s.\n", strdata1, strdata2);
else
printf("The %s is less than %s.\n", strdata1, strdata2);
return 0;
}

The following output will appear after executing the above code for the same string values.

The following output will appear after executing the above code for ‘hello’ and ‘Hello’ for the input values. Here, ‘h’ is greater than ‘H’

Go to top

Substring using strstr():

The strstr() function is used to search a particular string inside another string. It takes two arguments. The first argument contains the main string, and the second argument contains the searching string. This function returns a pointer that points to the first position of the main string where the searching string is found. The use of this function has shown in the following example.

//Include necessary header files
#include <string.h>
#include <stdio.h>
int main()
{
//Declare two arrays of characters
char mainStr[50], srearchStr[50];

printf("Enter the main string: ");
//Take string input from the console and store into a character array
fgets(mainStr, 50, stdin);
//Remove the newline from the input
mainStr[strlen(mainStr)-1] = '\0';

printf("Enter the searching string: ");
//Take string input from the console and store into a character array
fgets(srearchStr, 50, stdin);
//Remove the newline from the input
srearchStr[strlen(srearchStr)-1] = '\0';

//Display the message bases on the output of strstr()
if (strstr(mainStr, srearchStr))
printf("The searching string '%s' is found in the string '%s'.\n", srearchStr, mainStr);
else
printf("The searching string not found.\n");
return 0;
}

After executing the above code for the main string, “C Programming” and the searching string, “gram”, the following output will appear.

After executing the above code for the main string, “C Programming” and the searching string, “C++,” will appear the following output.

Go to top

Split string using strtok():

The strtok() function is used to split a string based on a particular delimiter. It returns a pointer to the first token found in the main string and returns null when no token is lefts. Two uses of the strtok() function have shown in the following example. Here, the first strtok() function will split the string based on the space, and the second strtok() function will split the string based on the colon(‘:’);

//Include necessary header files
#include <stdio.h>
#include <string.h>
int main()
{
//Initialize a character array
char strdata[25] = "Welcome to LinuxHint";
//Set the first token based on space
char* token = strtok(strdata, " ");

//Display splitted data in each line
printf("The splitted data based on space:\n");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, " ");
}

//Take input data from the console
printf("Enter a string with colon: ");
//Take string input from the console and store into a character array
fgets(strdata, 25, stdin);

//Set the first token based on colon
token = strtok(strdata, ":");

//Display splitted data in one line with the space
printf("The splitted data based on colon:\n");
while (token != NULL) {
printf("%s ", token);
token = strtok(NULL, ":");
}
return 0;
}

The following output will appear after executing the above code. “Bash:C:C++:Java:Python” has been taken as input in the output.

Go to top

Structure:

The structure is used to declare a collection of different variables by using a name. The struct keyword is used to declare structure in C. The use of the structure variable has shown in the following example. A structure of three variables has been declared in the code. The values have been assigned to the structure variables and printed later.

//Include necessary header files
#include <stdio.h>
#include <string.h>

//Declare a structure with three variables
struct courses
{
char code[10];
char title[50];
float credit;
};

int main() {

//Declare a stricture type variable
struct courses crs;

//Initialize the variable of the structure
strcpy(crs.code, "CSE 407");
strcpy(crs.title, "Unix Programming");
crs.credit = 2.0;

//Print the values of the structure variables
printf("Course code: %s\n", crs.code);
printf("Course title: %s\n", crs.title);
printf("Credit hour: %0.2f\n", crs.credit);

return 0;
}

The following output will appear after executing the above code.

Go to top

Count length using sizeof():

The sizeof() function counts the number of bytes of a particular data type or variable. Different uses of this function have shown in the following example.

#include <stdio.h>

int main()
{
//Print the size of different data types
printf("The size of boolean data type is %lu byte.\n", sizeof(bool));
printf("The size of char data type is %lu byte.\n", sizeof(char));
printf("The size of integer data type is %lu bytes.\n", sizeof(int));
printf("The size of float data type is %lu bytes.\n", sizeof(float));
printf("The size of double data type is %lu bytes.\n", sizeof(double));

//Initialize an integer number
int n = 35;
//The size of integer variable
printf("\nThe size of integer variable is %lu byte.\n", sizeof(n));
//Initialize a double number
double d = 3.5;
//The size of double variable
printf("The size of double variable is %lu byte.\n", sizeof(d));

return 0;
}

The following output will appear after executing the above code.

Go to top

Create a file:

The fopen() function is used to create, read, write and update a file. It contains two arguments. The first argument contains the filename, and the second argument contains the mode that defines the purpose of opening the file. It returns a file pointer that is used to write into the file or read from the file. The way to create a file in C has shown in the following example. Here, a text file has opened for writing by using the fopen() function.

//Include necessary header file
#include <stdio.h>

int main() {

//Declare a file pointer to open a file
FILE *fp;
//Create or overwrite the file by openning a file in write mode
fp = fopen ("test.txt", "w");
//Check the file is created or not
if(fp)
printf("File is created successfully.\n");
else
printf("Unable to create the file.\n");

//Close the file stream
fclose (fp);

}

The following output will appear after executing the above code.

Go to top

Write into the file:

The ‘w’ or ‘w+’ is used in the second argument of the fopen() function to open a file for writing. Many built-in functions exist in C to write data into a file. The uses of fprintf(), fputs(), and fputc() functions to write into a file have shown in the following example. Three lines have been written in a text file by using these functions.

//Include necessary header file
#include <stdio.h>

int main() {

//Declare a file pointer to open a file
FILE *fp;
//Declare integer variable
int i;

char data[50] = "C Programming is easy to learn.\n";
//Create or overwrite the file by openning a file in write mode
fp = fopen ("test.txt", "w");

//Check the file is created or not
if(fp)
printf("File is created successfully.\n");
else
printf("Unable to create the file.\n");

//Write to the file using fprintf()
fprintf(fp, "Welcome to LinuxHint.\n");

//Write to the file using fputs()
fputs("Learn C Programming from LinuxHint.\n", fp);

for (i = 0; data[i] != '\n'; i++) {
//Write to the file using fputc()
fputc(data[i], fp);
}

//Close the file stream
fclose (fp);

}

The following output will appear after executing the above code.

Go to top

Read from the file:

The ‘r’ or ‘r+’ is used in the second argument of the fopen() function to open the file for reading. The getc() function has been used in the following code to read data from a text file that has been created in the previous example.

//Include necessary header file
#include <stdio.h>

int main() {

//Declare a file pointer to open a file
FILE *fp;
//Declare char variable to store the content of the file
char c;

//Open the the file reading
fp = fopen ("test.txt", "r");
//Read the content of the file
while ((c = getc(fp)) != EOF)
{
printf("%c", c);
}

//Close the file stream
fclose (fp);
}

The following output will appear after executing the above code.

Go to top

Set seek position into the file:

The fseek() function is used to set different types of seeking positions in a file. Three different seek positions are SEEK_CUR, SEEK_SET, and SEEK_END. The uses of these seek positions have shown in the following examples. Here, the fgets() function is used to read data from a text file.

//Include necessary header file
#include <stdio.h>
int main ()
{
//Declare a file pointer to open a file
FILE *fp;
//Declare an array of characters to store each line of the file
char str[50];

//Open file for reading
fp = fopen ("test.txt","r");
//Read 25 bytes from the first line
fgets ( str, 25, fp );
printf("The output before using fseek(): %s", str);

//Set the cursor position using SEEK_CUR

fseek(fp, -5, SEEK_CUR);

//Read 10 bytes from the current seek position
fgets ( str, 10, fp );
printf("The output after using SEEK_CUR: %s", str);
//Set the cursor position using SEEK_SET
fseek(fp, 42, SEEK_SET);

fgets ( str, 30, fp );
printf("The output after using SEEK_SET: %s", str);
//Set the cursor position using SEEK_END
fseek(fp, -6, SEEK_END);

fgets ( str, 10, fp );
printf("The output after using SEEK_END: %s\n", str);
//Close the file stream
fclose(fp);

return 0;
}

The following output will appear after executing the above code.

Go to top

Read directory list using readdir():

The readdir() function is used to read the content of a particular directory. Before using this function, the opendir() function is used to open an existing directory for reading. The closedir() function is used to close the directory stream after completing the directory reading task. The pointer of the dirent structure and DIR are required to read the directory content. The way to read a particular directory in C has shown in the following example.

#include <stdio.h>
#include <dirent.h>
int main(void)
{
//Set the pointer to the directory array
struct dirent *dp;
//Define a DIR type pointer
DIR *dir = opendir("/home/fahmida/bash/");
//Check the directory path exists or not
if (dir == NULL)
printf("Directory does not exist." );
else
{
printf("The content of the directory:\n");
//Print the content of the directory using readir()
while ((dp = readdir(dir)) != NULL)
printf("%s ", dp->d_name);
printf("\n");

//Close the directory stream
closedir(dir);
}
return 0;
}

The following output will appear after executing the above code.

Go to top

Read file information using stat function:

The stat() function is used to read different properties of a particular file. The inode, mode, and UID properties of a file have been retrieved using the stat(() function in the following example. The built-in structure stat contains all property names of the file.

//Include necessary header files
#include<stdio.h>
#include<sys/stat.h>
#include <string.h>

int main()
{
//Declare a character array
char filename[30];
//Declare a pointer of the stat structure
struct stat fileinfo;

printf("Enter the filename: ");
fgets(filename, 30, stdin);
//Remove the newline from the input
filename[strlen(filename)-1] = '\0';
printf("Inode, mode and uid of %s file are given below:\n\n", filename);
//Check the file exists or not
if(fopen(filename, "r"))
{
//Get the file information using stat()
stat(filename, &fileinfo);

//Display the inode number of the file
printf("Inode: %ld\n", fileinfo.st_ino);

//Display the file mode
printf("Mode: %x\n", fileinfo.st_mode);

//Display the user ID of the file
printf("UID: %d\n", fileinfo.st_uid);

}
else
printf("File does not exist.\n");

return 0;
}

The following output will appear after executing the above code.

Go to top

Use of pipe:

The pipe is used to communicate between two related processes where the output of one process is the input of another process. The pipe() function is used in C to find out the available positions in the open file table of the process and assigns the positions for reading and writing ends of the pipe. The uses of the pipe() function have shown in the following example. Here, the data has been written in one end of the pipe, and the data have been read from another end of the pipe.

//Include necessary header files
#include <stdio.h>
#include <unistd.h>

#define SIZE 30

int main()
{

//Initialize two string data
char string1[SIZE] = "First Message";
char string2[SIZE] = "Second Message";

//Declare character array to store data from the pipe
char inputBuffer[SIZE];
//Declare integer array and an integer variable
int pArr[2], i;
if (pipe(pArr) < 0)
_exit(1);

//Write end of the pipe
write(pArr[1], string1, SIZE);
write(pArr[1], string2, SIZE);

for (i = 0; i < 2; i++) {
//Read end of the pipe
read(pArr[0], inputBuffer, SIZE);
printf("%s\n", inputBuffer);
}
return 0;
}

The following output will appear after executing the above code.

Go to top

Create symbolic link:

The symlink() function is used in C to create a soft link of a path. It has two arguments. The first argument contains the pathname, and the second argument contains the soft link file name of the path. It returns 0 if the link generates successfully. The use of the symlink() function has shown in the following example. The list of the directory has been printed before and after creating the soft link.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
// Driver Code
int main()
{
char filename[20] = "test.txt";
char symln[30] = "testLink.txt";

printf("All text files of the current location before link creation:\n");
system("ls -il *.txt");

//Create soft link of a file
int softlink = symlink(filename, symln);
if (softlink == 0) {
printf("The soft Link created succuessfully.\n");
}
else{
printf("Link creation error.\n");
}

printf("All text files of the current location after link creation:\n");
system("ls -il *.txt");

return 0;
}

The following output will appear after executing the above code.

Go to top

Using command-line arguments:

Two arguments are used in the main() function to read the command-line argument in C. The first argument, argc, contains the number of arguments passed by the user with the executing filename. The second argument, argv, is an array of characters that contains all command-line argument values. The way of using the command-line argument in C has shown in the following example. The total number of arguments and the argument values will be printed if the arguments are passed at the time of execution.

//Include necessary header file
#include <stdio.h>
int main(int argc,char* argv[])
{
int i;
//Check the argument is passed or not
if(argc < 2)
printf("\nNo command line argument is passed.");
else
{
//Print the first argument
printf("The executable filename is : %s\n",argv[0]);

//Print the total number of argument
printf("Total number of arguments: %d\n",argc);

//Print the argument values without filename
printf("The argument values are: \n");
for(i = 1; i <argc; i++)
printf("\nargv[%d]: %s",i,argv[i]);
}

printf("\n");
return 0;
}

The following output will appear after executing the above code with the argument values 9, 5, 3, and 8. The total number of arguments is 5 with the filename.

Go to top

Use of fork and exec:

The fork() function is used to create a duplicate process of the caller process. The caller process is called the parent process, and the newly created duplicate process is called the child process. The exec functions are used to run the system command. Many built-in functions exist in C for the system call. The execl() function is one of these that the path of the executable binary file in the first argument, the executable commands followed by the NULL value in the next arguments. The uses of fork() and execl() functions have shown in the following example.

#include <sys/types.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main(int argc, char *argv[]) {

pid_t pid = 0;

//Create a new process
pid = fork();

//Print message for child process
if (pid == 0) {
printf("It is child process.\n");
printf("The output of execl() command:\n");
execl("/bin/ls","ls", "-l", NULL);
}

//Print message for parent process
if (pid > 0) {
printf("It is parent process.\nThe child process id is %d.\n", pid);
}
if (pid < 0) {
perror("fork() error.");
}
   
return 0;
}

The following output will appear after executing the above code.

Go to top

Use of signals:

The signal is used to set a particular bit for the pending signals integer through a process. The blocked and pending signals are checked when the operating system wants to run a process. The process executes normally if no process is pending. The signal() function is used in C to send different types of signals. It has two arguments. The first argument contains the signal type, and the second argument contains the function name to handle the signal. The use of this function has shown in the following example.

//Include necessary header files
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>

//Define function to handle signal
void sighandler(int sigid) {
printf("\nThe signal Id is %d.\n", sigid);
exit(1);
}

int main () {

//Call signal() function with signal handler function
signal(SIGINT, sighandler);

//Print message for inifinite times until the user type Ctrl+C
while(true) {
printf("Waiting for 1 second. Type Ctrl+C to terminate.\n");
sleep(1);
}
return 0;
}

The message, “Waiting for 1 second. Type Ctrl+C to terminate.” It will be printed continuously after executing the above code. The program terminated when Ctrl+C has typed by the user. But the termination message is not printed when the program is executed from the Visual Studio Code.

If the program is executed from the terminal, then the following output will appear.

Go to top

Read date and time gettimeofday():

The gettimeofday() is used to read date and time values from the system. Two arguments of this function are structures that contain detailed information of date and time. The first structure, timeval, contains two members. These are time_t and suseconds_t. The second structure, tzp, also contains two members. These are tz_minuteswest and tz_dsttime. The way to retrieve the current date and time value using the gettimeofday() function has shown in the following example. An array of characters is declared to store the date and time values. The timeval structure has been used in the code to read the current timestamp value. The localtime() function has converted the timestamp value into human-readable date and time value.

//Include necessary header files
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

int main(void)
{
//Declare array of characters
char buf[30];
//Declare variable of timeval structure
struct timeval tm;
//Declare variable of time_t data type
time_t current_time;

//Call gettimeofday() function to read the current date and time
gettimeofday(&tm, NULL);
//Read the timestamp value of the current date and time
current_time=tm.tv_sec;

//Display the current date and time
printf("The current date and time is ");
strftime(buf,30,"%m-%d-%Y %T.",localtime(&current_time));
printf("%s\n",buf);

return 0;

}

The following output will appear after executing the above code.

Go to top

Use of macros:

The macro is a segment of a code with a name. If the macro name is used in the code, it will be replaced by the content of the macro. Two types of macros can be used in C. One is an object-like macro, and another is a function-like macro. #define directive is used to define the macro. C contains some pre-defined macros also to read current date, time, filename, etc. The uses of an object-like macro, a function-like macro, and a pre-defined macro have shown in the following example.

//Include necessary header file
#include <stdio.h>

//Define object macro
#define PI 3.14
//Define function macro
#define Circle_Area(r) (PI * r)
int main()
{
//Define the radius value
int radius = 3;
//Print the area of the circle using macro function
printf("Area of the circle is: %0.2f\n", Circle_Area(radius));

//Print the current date using predefined macro
printf("Today is :%s\n", __DATE__ );
return 0;
}

Use of typedef:

The typedef keyword is used in C to give an alternative name for an existing data type. It helps to manage the code more easily. The simple use of typedef has shown in the following example. A new name has been assigned for the structure using typedef in the code. Next, a variable has been declared using the new data type. The values have initialized to the properties of that variable and printed later.

//include necessary header files
#include<stdio.h>
#include<string.h>

//Declare new type using typedef
typedef struct product
{
char name[50];
float price;
}pro;

int main( )
{
//Declare variable of a new type
pro productInfo;

//Take input for the name variable
printf("Enter the product name: ");
scanf("%s", productInfo.name);
//Take input for the price variable
printf("Enter the product price: ");
scanf("%f", &productInfo.price);

//Print the name and price values
printf("\nProduct Name: %s\n", productInfo.name);
printf("Product Price: %0.2f\n", productInfo.price);

return 0;

}

The following output will appear after executing the above code for the input values, Cake and 23.89.

Go to top

Use of constant:

The constant variable is used to define the fixed data. There are two ways to define constants in C. One way is to use the #define directive, and another way is to use the const keyword. The uses of both ways have shown in the following example. A constant variable named MAXVAL has been declared using the #define directive at the top of the main() function that has been used as the length of the character array. Another constant variable named has been declared using the const keyword. The product price has been calculated, including the vat, and printed later.

//Include necessary header file
#include <stdio.h>

//Define constant using #define directive
#define MAXVAL 50

int main() {

//Define constant using const keyword
const float vat = 0.05;
//Define string value
char item[MAXVAL] = "Flower Vase";
//Define integer value
int price = 45;

//Calculate selling price with VAT
float selling_price = price + price * vat;
//Print the selling price
printf("The price of the %s with VAT is %0.2f", item, selling_price);
return 0;
}

The following output will appear after executing the above code.

Go to top

Error handling using errno and perror:

The error handling facility does not exist in C programming like other programming languages. But most of the C functions return -1 or NULL if any error occurs and set the error code to errno. The value of the errno will be 0 if no error occurs. The perror() function is used in C to print the error message of the corresponding errno. The uses of errno and perror() have shown in the following example. According to the code, a filename will be taken from the user and opened for reading. If the file does not exist, then the value of errno will be more than 0, and an error message will be printed. If the file exists, then the value of errno will be 0, and the success message will be printed.

#include  <stdio.h>
#include  <errno.h>
int main()
{
//Declare the file pointer
FILE * fp;
//Declare the character array to store the filename
char filename[40];

//Take the filename from the console
printf("Enter the filename to open: ");
scanf("%s", filename);
//Open the file for reading
fp = fopen(filename, "r");
//Print error no and error message if the file was unable to open
printf("Error no: %d\n ", errno);
perror("Error message:");
return 0;
}

The following output will appear after executing the above code for the hello.txt file because the file does not exist.

The following output will appear after executing the above code for the test.txt file because the file exists.

Go to top

Conclusion:

I think C is an ideal programming language for learners who didn’t learn any programming language before. 40 C programming examples from the basic to intermediate level have been shown in this tutorial, with detailed explanations for the new programmers. I hope this tutorial will help the reader to learn C programming and develop their programming skill.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.