ctime() Function Example in C Programming

In this source code example, we will see how to use the ctime() function in C programming with an example.

ctime() Function Overview

The ctime() function in C returns a string representing the local time based on the given time_t value, formatted in a readable way: "Day Mon dd hh:mm:ss yyyy\n". This function offers a convenient way to present time data to users. It's found within the time.h library. 

Key Points: 

- Include the time.h header to access the ctime() function. 

- The function returns the time as a formatted string. 

- It takes a pointer to a time_t value as its argument. 

- The returned string includes a newline character at the end.

Source Code Example

#include <stdio.h>
#include <time.h>  // Required for ctime() and time()

int main() {
    time_t current_time;
    char* c_time_string;

    // Obtain the current calendar time
    current_time = time(NULL);

    // Convert the time to a human-readable string
    c_time_string = ctime(&current_time);

    if (c_time_string == NULL) {
        printf("Failed to convert the current time.\n");
        return 1;
    }

    // Display the current date and time in a human-readable format
    printf("Current time: %s", c_time_string);

    return 0;
}

Output

Current time: Sat Jul  2 14:05:38 2023

Explanation

1. Begin by including the necessary header files: stdio.h for input/output functions and time.h for ctime() and time().

2. In the main() function, call the time() function to get the current calendar time.

3. Pass the obtained time_t value to ctime() to convert it to a human-readable string format.

4. Ensure the conversion is successful by checking if the returned pointer is not NULL.

5. Display the converted time string to the console.

The ctime() function provides a quick and straightforward way to fetch and display time. However, for more control over time formatting, one might consider using functions like strftime().


Comments