Skip to content
Tutorials Center
My learning

Topics

Lesson 169 of 171 ยท Practice and Review

C++ Programs: Files and Dates

C++ file and date programs with output: temp file, rename, copy, append, list a folder, print a month calendar and convert local time to UTC.

File and calendar tasks look different, but they share a trait: the standard library already does the hard part. <filesystem> handles paths, copies and directory walks on every platform, and <chrono> knows the calendar and the time-zone database, so you almost never need to write leap-year logic or parse paths by hand. The programs on this page show six practical recipes: a temporary file, rename and copy, append, a directory listing, a printed month calendar and a local-time-to-UTC conversion.

Our editor runs each program in a fresh, empty working directory and throws it away afterwards, so every file program creates its own files first. That also makes them safe to experiment with. For background, read Reading and Writing Text Files, the filesystem lesson and the chrono lesson.

Several filesystem calls have two forms: one that throws std::filesystem::filesystem_error and one that takes a std::error_code& and never throws. These programs use the throwing form for brevity. In production code that touches user-supplied paths, prefer the error_code form where failure is expected.

Files

1. Create and remove a temporary file

fs::temp_directory_path() returns the system's temp folder. Build a file name inside it, write something, check it exists, read it back, and remove it when done. Production code usually adds a random or process-specific part to the name to avoid collisions.

C++ 1. Temporary file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The { ... } block closes the ofstream (and flushes it) before the size is measured. A file that is still open for writing may report a smaller size than you expect.

2. Rename and copy a file

fs::rename moves a file within a file system (it is an atomic rename on most platforms), and fs::copy_file duplicates content. By default copy_file fails if the target exists; pass fs::copy_options::overwrite_existing to replace it.

C++ 2. Rename and copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

3. Append to a file

Open with std::ios::app and every write goes to the end, no matter where the position was. A plain std::ofstream would truncate the file instead. This is how simple log files are written.

C++ 3. Append to a file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

4. List the files in a directory

fs::directory_iterator visits the entries of one folder in an unspecified order; fs::recursive_directory_iterator also descends into subfolders. Collect names first and sort them if you need a stable output, as the program does.

C++ 4. List files

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Dates and times

5. Print a month calendar

C++20 <chrono> has calendar types. year_month_day is a date, weekday tells you which day of the week a date falls on, and year_month_day_last gives the last day of the month, so no leap-year code is needed. The program pads the first week with spaces according to the weekday of the 1st (with Sunday as column 0) and then prints the days, starting a new line after every Saturday.

C++ 5. Month calendar

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The two calls show that February 2024 has 29 days and February 2025 has 28: std::chrono::last knows the leap-year rule, so the program does not.

6. Convert local time to UTC

A zoned_time pairs a moment with a time zone from the IANA database. To go from a local wall-clock time to UTC, construct the zoned time from a local_time plus the zone name, then read get_sys_time(), which is the same instant expressed in UTC. The zone handles daylight saving automatically: the same wall-clock hour maps to different UTC hours in winter and summer.

C++ 6. Local time to UTC

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Winter time in New York is UTC minus five hours and summer time is UTC minus four, so the same 09:30 becomes 14:30 UTC in January and 13:30 UTC in July. Time-zone lookups need the IANA database; the editor's runner has one, and on your own machine the standard library may need an up-to-date tz database installed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to a file's old content when you open it with a plain std::ofstream(name)?

    The default mode for ofstream is out, which truncates. Add std::ios::app to append instead.
  2. 2. Which call replaces an existing target file when copying?

    By default copy_file reports an error if the target exists. The overwrite_existing option makes it replace the file.
  3. 3. Why does the calendar program not contain any leap-year logic?

    chrono's calendar types encode the leap-year rule, so y/m/last yields 29 for February 2024 and 28 for February 2025.
  4. 4. Why can the same local time map to different UTC times at different times of year?

    A time zone is more than a fixed offset: its rules shift the offset with daylight saving, and zoned_time applies those rules for the date given.

Summary

  • fs::temp_directory_path() / "name" builds a path in the system temp folder; remove what you create.
  • fs::rename moves or renames; fs::copy_file copies and needs overwrite_existing to replace.
  • Open with std::ios::app to append; a plain ofstream truncates.
  • directory_iterator and recursive_directory_iterator list entries in unspecified order, so sort when you need stable output.
  • year_month_day, weekday and y/m/last give calendar facts without hand-written leap-year code.
  • zoned_time converts between a zone's local time and UTC and applies daylight saving automatically.

Next: Practice exercises, or back to 40 classic C++ programs.