C++ File Status | 'File Status' Guide
이 글의 핵심
C++17 std::filesystem file_status·perms, status and symlink_status, file_type·permission checks, backup·log cleanup practice, Windows and POSIX differences organized with code.
What is File Status?
In C++17 filesystem, to distinguish not just file existence but regular file, directory, symbolic link type and permissions, understanding file_status is helpful. Following this guide naturally connects metadata query flow with type-specific APIs in later sections.
File Metadata Query (C++17)
Below is an implementation example using C++. Import necessary modules, perform branching with conditionals. Understand the role of each part while examining the code.
#include <filesystem>
// Package declaration
namespace fs = std::filesystem;
fs::path p = "file.txt";
auto status = fs::status(p);
if (status.type() == fs::file_type::regular) {
std::cout << "Regular file" << std::endl;
}
File Type
Below is an implementation example using C++. Understand the role of each part while examining the code.
fs::file_type type = fs::status(p).type();
// Type check
fs::is_regular_file(p);
fs::is_directory(p);
fs::is_symlink(p);
fs::is_block_file(p);
fs::is_character_file(p);
fs::is_fifo(p);
fs::is_socket(p);
Practical Examples
Example 1: File Information
Here is detailed implementation code using C++. Perform branching with conditionals. Understand the role of each part while examining the code.
void printFileInfo(const fs::path& p) {
if (!fs::exists(p)) {
std::cout << "File not found" << std::endl;
return;
}
auto status = fs::status(p);
std::cout << "Path: " << p << std::endl;
std::cout << "Type: ";
if (fs::is_regular_file(status)) {
std::cout << "Regular file" << std::endl;
std::cout << "Size: " << fs::file_size(p) << " bytes" << std::endl;
} else if (fs::is_directory(status)) {
std::cout << "Directory" << std::endl;
} else if (fs::is_symlink(status)) {
std::cout << "Symbolic link" << std::endl;
}
}
Example 2: Modified Time
Below is an implementation example using C++. Understand the role of each part while examining the code.
void printModifiedTime(const fs::path& p) {
auto ftime = fs::last_write_time(p);
// C++20: system_clock conversion
auto sctp = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
ftime - fs::file_time_type::clock::now() +
std::chrono::system_clock::now()
);
std::time_t cftime = std::chrono::system_clock::to_time_t(sctp);
std::cout << "Modified: " << std::ctime(&cftime);
}
Example 3: Permission Check
Here is detailed implementation code using C++. Perform branching with conditionals. Understand the role of each part while examining the code.
void checkPermissions(const fs::path& p) {
auto perms = fs::status(p).permissions();
std::cout << "Permissions: ";
if ((perms & fs::perms::owner_read) != fs::perms::none) {
std::cout << "r";
}
if ((perms & fs::perms::owner_write) != fs::perms::none) {
std::cout << "w";
}
if ((perms & fs::perms::owner_exec) != fs::perms::none) {
std::cout << "x";
}
std::cout << std::endl;
}
Example 4: Space Information
Below is an implementation example using C++. Try running the code directly to check its operation.
void printSpaceInfo(const fs::path& p) {
auto space = fs::space(p);
std::cout << "Capacity: " << space.capacity << " bytes" << std::endl;
std::cout << "Free: " << space.free << " bytes" << std::endl;
std::cout << "Available: " << space.available << " bytes" << std::endl;
}
Permission Setting
Below is an implementation example using C++. Understand the role of each part while examining the code.
fs::path p = "file.txt";
// Add permission
fs::permissions(p, fs::perms::owner_write,
fs::perm_options::add);
// Remove permission
fs::permissions(p, fs::perms::owner_write,
fs::perm_options::remove);
// Set permission
fs::permissions(p, fs::perms::owner_all);
file_status and perms
std::filesystem::file_status is a value containing single query result. Mainly bundles two things:
type()→file_type:regular,directory,symlink,not_found, etc. State not following symbolic link is obtained withsymlink_status, followed result withstatuspattern is frequently used.permissions()→perms: Read/write/execute bits for owner, group, others. Check “set or not” withnoneand bit AND.
Below is an implementation example using C++. Perform branching with conditionals. Try running the code directly to check its operation.
fs::file_status st = fs::status(p, ec);
if (!ec && st.type() != fs::file_type::not_found) {
auto pm = st.permissions();
bool owner_read = (pm & fs::perms::owner_read) != fs::perms::none;
}
status(p) queries symbolic link’s final target, use symlink_status(p) if link type itself is needed. Broken link can make status not_found, so distinguishing link first with symlink_status is advantageous for debugging.
File Type Check (Summary)
file_type also distinguishes “lack of information” states like unknown, none, not_found. In practice, usually use convenience functions together.
| Purpose | Recommended API |
|---|---|
| Regular file check | fs::is_regular_file(st) or is_regular_file(p) |
| Directory check | fs::is_directory(st) |
| Symbolic link check | fs::is_symlink(st) — based on symlink_status |
| Block/character device etc | is_block_file, is_character_file, is_fifo, is_socket |
Below is an implementation example using C++. Perform branching with conditionals. Try running the code directly to check its operation.
auto st = fs::status(path);
if (fs::is_regular_file(st)) { /* … */ }
else if (fs::is_directory(st)) { /* … */ }
auto lst = fs::symlink_status(path);
if (fs::is_symlink(lst)) {
auto target_st = fs::status(path); // Target following link
}
Note: If path doesn’t exist, type() is not_found and exists(path) is false. is_regular_file returns false if doesn’t exist, so to distinguish “missing file” from “exists but directory”, safer to see status and file_type together.
Permission Check
perms is as much as possible abstraction of POSIX-style bit mask. OS meaning like execute permission on regular file, directory execute bit (allow search) should be confirmed in documentation and actual environment.
Below is an implementation example using C++. Ensure stability through error handling, perform branching with conditionals. Understand the role of each part while examining the code.
bool can_owner_write(const fs::path& p, std::error_code& ec) {
auto st = fs::status(p, ec);
if (ec) return false;
auto pm = st.permissions();
return (pm & fs::perms::owner_write) != fs::perms::none;
}
// Print owner rwx in one line (POSIX style)
void print_owner_rwx(fs::perms pm) {
char r = (pm & fs::perms::owner_read) != fs::perms::none ? 'r' : '-';
char w = (pm & fs::perms::owner_write) != fs::perms::none ? 'w' : '-';
char x = (pm & fs::perms::owner_exec) != fs::perms::none ? 'x' : '-';
std::cout << r << w << x;
}
Check before write example:
Below is an implementation example using C++. Ensure stability through error handling, perform branching with conditionals. Try running the code directly to check its operation.
// Example
std::error_code ec;
if (can_owner_write(path, ec)) {
// Overwrite etc
}
Windows: Read-only attribute and ACL may not correspond 1:1 with filesystem’s perms. For cross-platform tools, handling actual open/ofstream failure is often more reliable than “retry permissions on failure”.
Practice: Backup Script (Concept)
Backup like “copy only files modified in recent N days” selects targets with last_write_time and file_status. Large trees combine with recursive_directory_iterator.
Below is an implementation example using C++. Import necessary modules, ensure stability through error handling, perform branching with conditionals. Understand the role of each part while examining the code.
// Package declaration
namespace fs = std::filesystem;
using clock = fs::file_time_type::clock;
bool needs_backup(const fs::path& p,
fs::file_time_type cutoff,
std::error_code& ec) {
auto st = fs::status(p, ec);
if (ec || !fs::is_regular_file(st)) return false;
auto mtime = fs::last_write_time(p, ec);
if (ec) return false;
return mtime >= cutoff;
}
cutoff is value like “now − 7 days” converted to file_time_type. In C++20, easier to compare with difference from clock::now(). When copying, can reduce duplicate copies by checking same inode (hard link) with equivalent.
Practice: Log Management (Rotation·Cleanup)
Old log deletion is decided by regular file + modified time. In C++17, file_time_type and clock conversion differ by implementation, so safer to make one reference time as file_time_type and compare last_write_time for each item.
Here is detailed implementation code using C++. Ensure stability through error handling, process data with loops, perform branching with conditionals. Understand the role of each part while examining the code.
// Example
void prune_old_logs(const fs::path& log_dir,
fs::file_time_type cutoff,
std::error_code& ec) {
for (const auto& e : fs::directory_iterator(log_dir, ec)) {
if (ec) break;
if (!e.is_regular_file()) continue;
auto mt = fs::last_write_time(e.path(), ec);
if (ec) continue;
if (mt < cutoff) {
fs::remove(e.path(), ec);
}
}
}
// cutoff must be value made with same clock aligned to "7 days ago from now" etc.
// With C++20 `std::chrono::file_clock`, conversion and comparison become clearer.
Disk threshold is safer to duplicate policy by checking volume space with fs::space seen earlier, then deleting oldest logs first.
Platform Differences
| Topic | POSIX (Linux, macOS) | Windows |
|---|---|---|
| Permission bits | Traditional rwx, model similar to chmod | perms is simplified·emulated; ACL·attributes separate |
| Path separator | / | Both \ and / allowed but display often \ |
| Symbolic link | Widely used | Environment dependent like admin rights·developer mode |
| Case sensitivity | Usually sensitive | Basically case-insensitive in path comparison |
Practice recommendation: Cross-platform code uses fs::path operations, gets hint from perms for permissions but supplements with final I/O failure handling. Deployment scripts can branch permissions call by OS or limit to documentation.
Common Issues
Issue 1: Existence Check
Below is an implementation example using C++. Perform branching with conditionals. Try running the code directly to check its operation.
// ❌ Without existence check
auto size = fs::file_size("file.txt"); // Exception
// ✅ With existence check
if (fs::exists("file.txt")) {
auto size = fs::file_size("file.txt");
}
Issue 2: Directory Size
Below is an implementation example using C++. Ensure stability through error handling, process data with loops, perform branching with conditionals. Understand the role of each part while examining the code.
// ❌ file_size on directory
// auto size = fs::file_size("dir"); // Exception
// ✅ Recursive calculation
uintmax_t size = 0;
for (const auto& entry : fs::recursive_directory_iterator("dir")) {
if (entry.is_regular_file()) {
size += entry.file_size();
}
}
Issue 3: Symbolic Link
Below is an implementation example using C++. Try running the code directly to check its operation.
fs::path link = "symlink";
// Link itself status
auto linkStatus = fs::symlink_status(link);
// Link target status
auto targetStatus = fs::status(link);
Issue 4: Permission Error
Below is an implementation example using C++. Ensure stability through error handling, process data with loops. Understand the role of each part while examining the code.
// ❌ Exception if no permission
for (const auto& entry : fs::recursive_directory_iterator("/")) {
// Permission error
}
// ✅ Ignore error
for (const auto& entry : fs::recursive_directory_iterator("/",
fs::directory_options::skip_permission_denied)) {
std::cout << entry.path() << std::endl;
}
File Comparison
Below is an implementation example using C++. Perform branching with conditionals. Understand the role of each part while examining the code.
fs::path p1 = "file1.txt";
fs::path p2 = "file2.txt";
// Same file?
if (fs::equivalent(p1, p2)) {
std::cout << "Same file" << std::endl;
}
// Compare modified time
if (fs::last_write_time(p1) > fs::last_write_time(p2)) {
std::cout << "p1 is newer" << std::endl;
}
FAQ
Q1: What is directory_iterator?
A: C++17. Directory traversal.
Q2: Recursive traversal?
A: recursive_directory_iterator.
Q3: Permission error?
A: skip_permission_denied option.
Q4: File size?
A: file_size() or entry.file_size().
Q5: Modified time?
A: last_write_time().
Q6: directory_iterator learning resources?
A:
- “C++17 The Complete Guide”
- “C++ Primer”
- cppreference.com
Related Articles
- C++ Filesystem | “Filesystem” C++17 Library Guide
- C++ Directory Iterator | “Directory Traversal” Guide
- C++ Filesystem | “Filesystem Library” Guide
Master C++17 file status! 🚀