Back to C++
2025-12-128 min read

file time (C++)

Learn file time (C++) step by step with clear examples and exercises.

Why This Matters

File time is an essential concept in C++ programming that allows developers to work with the time associated with files. This lesson aims to provide a comprehensive understanding of file time, its importance, and how to handle it using the std::filesystem library introduced in C++17.

Importance of File Time

File time is crucial for various purposes such as tracking changes to files, implementing backup systems, debugging issues related to file access, monitoring system performance, and maintaining data integrity. By understanding file times, developers can create more robust and efficient applications that handle files effectively.

Prerequisites

To fully appreciate this topic, you should have a good grasp of:

  1. Basic C++ programming concepts
  2. Understanding of the C++ Standard Template Library (STL)
  3. Familiarity with file I/O operations in C++
  4. Knowledge of the `` library for handling time-related operations
  5. Adequate understanding of exception handling and error management
  6. Basic understanding of directories and paths in C++
  7. Familiarity with the concepts of regular files, symbolic links, and directories
  8. Understanding of the differences between last write, creation, modification, and last access times

Core Concept

The std::filesystem library offers a unified interface to manipulate files and directories on various systems. It provides several classes, functions, and types to work with file system entities, one of which is the file_time_type.

File Time Type

In C++17, file_time_type is defined as:

using file_time_type = std::chrono::time_point< /*trivial-clock*/ >;

The /*trivial-clock*/ is an implementation-defined type that satisfies the TrivialClock concept and can represent the resolution and range of file time values offered by the filesystem. In C++20, it was updated as:

using file_time_type = std::chrono::time_point< std::chrono::file_clock >;

This change allows for better precision and compatibility with various platforms.

File Time Operations

The std::filesystem library offers several functions to work with file times:

  1. last_write_time(const path& p) – Returns the last write time of the file or directory at the given path.
  2. create_time(const path& p) – Returns the creation time of the file or directory at the given path.
  3. modification_time(const path& p) – Returns the last modification time of the file or directory at the given path.
  4. last_access_time(const path& p) – Returns the last access time of the file or directory at the given path.
  5. exists(const path& p) – Checks if a file or directory exists at the given path.
  6. is_regular_file(const path& p) – Checks if the entity at the given path is a regular file (not a directory, symbolic link, etc.).
  7. status(const path& p) – Returns the status of the file or directory at the given path, including its time properties.
  8. file_status(const path& p) – Returns the status of the entity at the given path, including its type (regular file, directory, symbolic link, etc.) and time properties.
  9. revert(const path& p) – Changes the last access time of a regular file or directory to the current time.
  10. permissions(const path& p, perms new_perms = perms::all) – Sets the permissions of a file or directory at the given path to the specified value.

Worked Example

Let's create a simple example that demonstrates working with file times using C++20.

#include <iostream>
#include <filesystem>
#include <chrono>
#include <vector>

int main() {
std::filesystem::path currentPath("."); // Define the current directory path
std::vector<std::filesystem::path> files; // Create a vector to store file paths

for (const auto & entry : std::filesystem::directory_iterator(currentPath)) {
if (std::filesystem::is_regular_file(entry)) { // Check if the entity is a regular file
files.push_back(entry); // Add the file path to the vector
}
}

for (const auto & file : files) { // Iterate through the files in the current directory
std::filesystem::file_time_type lastWriteTime = std::filesystem::last_write_time(file); // Get the last write time
std::filesystem::file_time_type creationTime = std::filesystem::create_time(file); // Get the creation time
std::filesystem::file_time_type modificationTime = std::filesystem::modification_time(file); // Get the modification time
std::filesystem::file_time_type lastAccessTime = std::filesystem::last_access_time(file); // Get the last access time

std::cout << "File: " << file.filename() << "\n";
std::cout << "Last Write Time: " << std::chrono::system_clock::to_time_t(lastWriteTime) << std::endl;
std::cout << "Creation Time: " << std::chrono::system_clock::to_time_t(creationTime) << std::endl;
std::cout << "Modification Time: " << std::chrono::system_clock::to_time_t(modificationTime) << std::endl;
std::cout << "Last Access Time: " << std::chrono::system_clock::to_time_t(lastAccessTime) << std::endl;
std::cout << "\n";
}

return 0;
}

Common Mistakes

  1. Not checking if the file exists or is a regular file: Always check if the entity at the given path is a regular file before trying to get its time properties to avoid undefined behavior.
  2. Forgetting to convert file_time_type to system_clock: The file_time_type returned by functions like last_write_time(), create_time(), modification_time(), and last_access_time() needs to be converted to std::chrono::system_clock::time_point before it can be output as a human-readable time.
  3. Not handling exceptions: The functions that work with file times may throw exceptions if an error occurs. Make sure to handle these exceptions appropriately.
  4. Ignoring the difference between last write, creation, modification, and last access times: These properties represent different aspects of a file's history and can provide valuable information for debugging and monitoring purposes.
  5. Not considering the platform-specific limitations: Different platforms may have varying support for file time resolution and range, so it is essential to consider these factors when working with file times.
  6. Not using file_status or status functions: Always use file_status() or status() to get the status of a file or directory, as they provide more information than individual time functions.
  7. Not handling symbolic links and directories appropriately: When working with symbolic links and directories, make sure to check their type using is_symlink() and is_directory(), respectively, before getting their time properties or performing other operations.
  8. Not considering the effects of file permissions: Be aware that some operations may require certain file permissions to be performed successfully.

Practice Questions

  1. Write a program that prints the creation, last write, modification, and last access times for all files in a given directory, sorted by their last modification time.
  2. Modify the example above to print the time difference between the creation and last write times of each file.
  3. Implement a function that checks if a file has been modified within the last 24 hours.
  4. Write a program that compares the file sizes of two given files and outputs the one with the larger size.
  5. Create a backup system for a specific directory by copying all files to a backup directory when they are modified.
  6. Implement a function that moves a file to a new location if it has not been accessed in over 30 days.
  7. Write a program that finds all files older than a specified age (e.g., one month) and outputs their paths.
  8. Create a function that sets the permissions of a given file or directory to a specific value.
  9. Implement a function that checks if a symbolic link points to an existing file or directory.
  10. Write a program that lists all files in a directory, sorted by their last access time, and outputs only those that have not been accessed within the last week.

FAQ

  1. Why is it important to work with file times in C++? Understanding file times can help you track changes to files, implement backup systems, debug issues related to file access, monitor system performance, and maintain data integrity.
  2. What are some common errors when working with file times in C++? Common errors include not checking if the entity exists or is a regular file, forgetting to convert file_time_type to system_clock, and not handling exceptions properly.
  3. Can I get the current file time using std::filesystem? No, std::filesystem does not provide a function to get the current file time directly. However, you can use std::chrono::system_clock::now() to get the current system time and then call last_write_time(path(".")) to get the last write time of the current directory, which represents the current file time.
  4. What is the difference between last write, creation, modification, and last access times? Last write time refers to the time when a file was last written to; creation time refers to the time when a file was created; modification time refers to the time when a file's metadata (such as its name or attributes) was last modified; last access time refers to the time when the file was last accessed (opened, read from, or written to).
  5. How can I handle exceptions when working with file times in C++? You can use a try-catch block to catch and handle exceptions thrown by functions like last_write_time(), create_time(), modification_time(), and last_access_time(). Make sure to print useful error messages and provide appropriate recovery actions.
  6. How do I check if a file or directory exists using std::filesystem? You can use the exists() function to check if a file or directory exists at the given path. If you want to check for both files and directories, use is_regular_file() or is_directory(), respectively.
  7. How do I check if a symbolic link points to an existing file or directory using std::filesystem? You can use the symlink_status() function to get the status of a symbolic link, and then check if it is a regular file or directory using is_regular_file() or is_directory().
  8. How do I set the permissions of a file or directory using std::filesystem? You can use the permissions() function to set the permissions of a file or directory at the given path to the specified value.
  9. How do I list all files in a directory, sorted by their last access time, and output only those that have not been accessed within the last week? You can use a combination of directory_iterator, recursive_directory_iterator, and lambda functions to iterate through the directory and filter out files based on their last access time.
  10. How do I find all files older than a specified age (e.g., one month) and output their paths? You can use a combination of directory_iterator, recursive_directory_iterator, and lambda functions to iterate through the directory and filter out files based on their last modification time, considering the specified age (e.g., one month).
file time (C++) | C++ | XQA Learn