Detailed Summary of the System Cleaner Project

System Cleaner Project Detailed Summary

This project is a system junk file cleaning tool based on the Windows platform, supporting the cleaning of various types of junk files such as temporary files, browser caches, and the recycle bin. It features core capabilities such as security checks, log recording, and permission assessments, and is designed using C++ object-oriented principles, integrating Windows API for system-level file operations.

1. Core Functions and Architecture

1. Core Positioning

  • Target Scenario: Cleaning redundant files in the Windows system (temporary files, browser caches, prefetch files, etc.) to free up disk space.
  • Core Features:
  • Supports Safe Mode (only cleans low-risk files) and Full Mode (full cleaning, requires administrator privileges).
  • Automatically generates a unique log file to record details of deleted/skipped files for troubleshooting.
  • Breaks through the Windows 260 character path limit, supporting long path file operations.
  • Intelligent error classification (locked files, insufficient permissions, etc.) to avoid mistakenly deleting critical system directories.

2. Overall Architecture

The project adopts a single-class core design, encapsulating all cleaning logic through the SystemCleaner class, along with two core structures to store data, resulting in a clear structure:

Component

Function

CleanStats Structure

Records statistical data during the cleaning process (number of files deleted, space freed, skipped items, etc.)

CleanRule Structure

Defines cleaning rules (path, matching patterns, whether to recurse, permission requirements, etc.)

SystemCleaner Class

The core business class, containing all logic for initializing rules, executing cleaning, logging, and security checks

Main Function

Program entry point, creates a SystemCleaner instance and starts the cleaning process

2. Key Data Structure Analysis

1. CleanStats: Cleaning Statistics Structure

Stores quantitative data and details during the cleaning process, used for final result display and log export:

struct CleanStats {
size_t totalFilesDeleted = 0;      // Total number of files deleted
size_t totalDirsDeleted = 0;       // Total number of directories deleted
size_t totalBytesFreed = 0;        // Total bytes freed (displayed in MB)
size_t failedOperations = 0;       // Number of failed operations
size_t skippedLockedFiles = 0;     // Number of skipped locked files (unable to delete)
size_t skippedAccessDenied = 0;    // Number of files with access denied (insufficient permissions)
std::vector skippedItems;  // Paths of all skipped items (including error reasons)
std::vector deletedFiles;  // Paths of deleted files (for logging)
std::vector deletedDirs;   // Paths of deleted directories (for logging)
};

2. CleanRule: Cleaning Rule Structure

Defines the “behavior rules” for each cleaning item, determining the scope and method of cleaning. During initialization, more than 10 rules are preset (covering system/browser/user temporary files):

struct CleanRule {
std::string path;                   // Cleaning path (supports environment variables, e.g., %TEMP%)
std::vector patterns;  // File matching patterns (e.g., *.tmp, *.*)
bool recursive;                     // Whether to recurse into subdirectories
bool removeDirectory;               // Whether to delete the directory itself (e.g., recycle bin)
bool recreateDirectory;             // Whether to recreate the directory (e.g., browser cache directory)
std::string description;            // Rule description (displayed in the user interface)
bool requiresAdmin;                 // Whether administrator privileges are required (e.g., system temporary files)
bool safeModeOnly;                  // Whether to execute only in safe mode (low-risk items)
};

3. Core Functions of the SystemCleaner Class

The SystemCleaner is the core of the project, containing private utility functions (path handling, permission checks, log recording) and public business functions (rule initialization, cleaning execution). The following sections analyze key functions by functionality.

1. Path and String Handling (Private Utility Functions)

These functions address the peculiarities of Windows paths (environment variables, long paths, case insensitivity), forming the basis for file operations.

(1) ExpandEnvironmentVars: Expand Environment Variables

  • Function: Converts environment variables such as %TEMP%, %LOCALAPPDATA%, etc., into actual paths (e.g., C:\Users\XXX\AppData\Local\Temp).
  • Key Code:
std::string ExpandEnvironmentVars(const std::string& path) {
char expanded[MAX_PATH_LENGTH];
DWORD result = ExpandEnvironmentStringsA(path.c_str(), expanded, MAX_PATH_LENGTH);
return (result > 0 && result < MAX_PATH_LENGTH) ? std::string(expanded) : path;
}
  • Functionality: Supports dynamic path configuration, avoiding compatibility issues caused by hard-coded paths.

(2) ToLongPath: Convert to Long Path Format

  • Function: Breaks through the Windows default 260 character path limit, adding the \?\ prefix for long paths (supported by Windows API).
  • Key Code:
std::string ToLongPath(const std::string& path) {
if (path.length() > 260) {
return "\\?\" + path;  // Long path prefix
}
return path;
}
  • Functionality: Prevents failures in API calls like FindFirstFileA, DeleteFileA due to overly long paths.

(3) MatchPattern: Filename Wildcard Matching

  • Function: Supports wildcard patterns such as *.tmp, *.*, to determine if a filename matches the cleaning rules.
  • Core Logic:
    1. If the pattern is * or *.*, match all files directly;
    1. If the pattern contains * (e.g., *.log), split the prefix (empty) and suffix (.log), matching the file name’s suffix separately;
    1. Case insensitive (compared after converting to lowercase using ToLower).
  • Functionality: Implements flexible file filtering, ensuring only target types of junk files are deleted.

2. Security and Permission Checks (Private Utility Functions)

These functions act as the tool’s “safety barrier,” preventing the accidental deletion of critical system files or crashes due to insufficient permissions.

(1) IsUserAdmin: Check for Administrator Privileges

  • Function: Checks whether the current program is running with administrator privileges, determining if high-privilege cleaning items (e.g., system temporary files, recycle bin) can be executed.
  • Key Logic:
    1. Creates an administrator group SID using AllocateAndInitializeSid (DOMAIN_ALIAS_RID_ADMINS);
    1. Calls CheckTokenMembership to verify if the current process token belongs to the administrator group.
  • Functionality: Performs permission checks for rules requiring administrator privileges (e.g., cleaning %windir%\prefetch), skipping if no permissions are available and prompting the user.

(2) IsSafePath: Safe Path Check

  • Function: Filters critical system directories (e.g., C:\Windows\System32, C:\Program Files) to prevent accidental deletions that could lead to system crashes.
  • Core Logic:
    1. Defines a list of dangerous paths (system core directories);
    1. Converts the path to lowercase and checks if it starts with any dangerous path.
  • Functionality: Even if the rule configuration is incorrect, this function intercepts dangerous operations, serving as a core safety guarantee.

(3) ConfirmOperation: User Confirmation for Operations

  • Function: Pops up a confirmation interface before executing the cleaning, allowing the user to choose the cleaning mode (safe/full/cancel).
  • Key Logic:
    1. If SAFETY_CONFIRMATION_REQUIRED is enabled (default), displays operation description and mode options;
    1. Reads user input to set safeMode (safe mode flag) and userCancelled (cancel flag).
  • Functionality: Prevents accidental operations, providing users with the opportunity to choose, aligning with the design principles of safety tools.

3. Log Recording (Private Utility Functions)

Logs are key for troubleshooting; the project supports dual log output to both “console + file,” with unique log files.

(1) GetCurrentTimestamp: Generate Timestamp

  • Function: Generates a timestamp in the format YYYYMMDD_HHMMSS for log file names (e.g., cleanup_log_20240520_153045.txt).
  • Functionality: Ensures that each cleaning log file does not overwrite previous ones, facilitating the tracing of historical cleaning records.

(2) LogToConsoleAndFile: Dual Log Output

  • Function: Outputs log messages to both the console (visible to the user) and the log file (persistent record).
  • Key Code:
void LogToConsoleAndFile(const std::string& message, bool includeTimestamp = false) {
printf("%s\n", message.c_str());  // Console output
LogToFile(message, includeTimestamp);  // File output
}
  • Functionality: Balances real-time user viewing and subsequent troubleshooting, with logs containing timestamps, operation descriptions, error reasons, and more.

(3) ExportLogToFile: Export Detailed Logs

  • Function: After cleaning is complete, writes details from CleanStats (deleted file list, skipped item list) to the log file.
  • Functionality: Provides complete operational traceability; if a user questions “why a file was deleted,” they can verify the deleted file paths through the logs.

4. Core Cleaning Logic (Private Business Functions)

DeleteDirectoryContents is the most critical cleaning function, responsible for traversing directories, matching files, and executing deletions, serving as the “execution engine” of the entire tool.

DeleteDirectoryContents: Delete Directory Contents

  • Function: Recursively traverses directories based on CleanRule rules, deleting matching files and empty directories.
  • Core Process:
    1. Path Preprocessing: Expand environment variables → Check if the path exists / is a directory → Convert to long path;
    1. Directory Traversal: Calls FindFirstFileA/FindNextFileA to traverse directory contents, skipping . and ..;
    1. File Handling:
      • If it is a file: Determine if it matches the rule pattern → Call DeleteFileSimple to delete → Update CleanStats (file count, space freed);
      • If deletion fails: Classify statistics based on error codes (locked files → skippedLockedFiles, insufficient permissions → skippedAccessDenied);
    1. Subdirectory Handling:
      • If the rule allows recursion, collect subdirectories and recursively call itself;
      • After cleaning subdirectories, if empty, call RemoveDirectoryA to delete the empty directory;
    1. Directory Recreation: If the rule enables recreateDirectory (e.g., browser cache directory), delete and then recreate the directory (to avoid program errors).
  • Key Details:
    • Treat “file not found” errors as successes (idempotent design to avoid repeated error messages);
    • When recursively processing subdirectories, delete files first and then delete empty directories, complying with the dependency relationship of Windows directory deletion (content must be deleted before the directory).

5. Public Business Functions

Public functions are called externally (e.g., main) and are responsible for initializing rules and starting the cleaning process.

(1) InitializeRules: Initialize Cleaning Rules

  • Function: Presets more than 10 cleaning rules covering system, browser, and user types of junk files.
  • Typical Rule Examples:

Rule Description

Path

Matching Pattern

Requires Admin

Safe Mode Support

User Temporary Files

%TEMP%

*.tmp, etc.

No

Yes

System Temporary Files

%windir%\Temp

*.tmp, etc.

Yes

Yes

Edge Browser Cache

%LOCALAPPDATA%\Microsoft\Edge\…

*.*

No

Yes

Recycle Bin

%systemdrive%\$Recycle.Bin

*.*

Yes

No

  • Functionality: Defines the cleaning scope, allowing users to use it out of the box without manual configuration.

(2) PerformCleanup: Execute Cleaning Process

  • Function: Coordinates the entire cleaning process, serving as the “entry function” of the SystemCleaner class.
  • Core Process:
    1. Prints tool information and log file name;
    1. Calls ShowPreview to display a preview of the cleaning (users can view items to be cleaned in advance);
    1. Calls ConfirmOperation to get user confirmation (mode selection);
    1. Iterates through all CleanRule, skipping those that do not meet the current mode (e.g., skipping non-safe items in safe mode) or lack permissions;
    1. For rules that meet the conditions, calls DeleteDirectoryContents to execute cleaning;
    1. After cleaning is complete, prints statistical information (number of files deleted, space freed, time taken, etc.);
    1. Calls ExportLogToFile to export detailed logs.
  • Return Value: If the number of failed operations is 0, returns true (in practice, “locked file skipped” is a normal occurrence, so returning true does not imply no skipped items).

4. Main Function: Program Entry

The main function logic is simple, responsible only for initialization and starting the cleaning:

  1. Prints tool version and new features (e.g., Edge cache cleaning, logging features);
  1. Creates a SystemCleaner instance (enabling verbose mode verbose=true);
  1. Calls PerformCleanup to start the cleaning process;
  1. Prints prompt information based on the cleaning results, waiting for user key press to exit.

5. Project Features and Highlights

  1. High Security:
    • Dual security checks (IsSafePath filtering dangerous directories + user confirmation mode);
    • Error classification statistics to avoid program crashes due to normal errors like “locked files.”
  1. Strong Compatibility:
    • Supports long paths (breaking the 260 character limit);
    • Supports environment variable paths, adapting to different Windows accounts and system versions.
  1. Good Maintainability:
    • Separation of rules and logic, allowing new cleaning items to be added simply by adding rules in InitializeRules;
    • Detailed logs facilitate problem localization (e.g., “why a certain file was not deleted” can be verified through error codes in the logs).
  1. User-Friendly:
    • Preview before cleaning, mode selection, real-time console logs;
    • Displays key information such as freed space and time taken after cleaning, providing clear feedback to users.

6. Conclusion

This project is a fully functional and reliable Windows system cleaning tool, with core value in “automated junk cleaning + safety protection + traceability.” Its design philosophy aligns with the development principles of system tools:

  • Low-level Dependencies: Implemented file operations based on Windows API, ensuring compatibility and stability;
  • High-level Design: Uses object-oriented encapsulation, with single responsibilities for functions (e.g., path handling, log recording, cleaning execution separation), facilitating maintenance and expansion;
  • Safety First: Prevents accidental operations through multiple checks, a core design principle for tool software.

If functionality needs to be extended (e.g., support for custom cleaning rules, scheduled cleaning), new public functions (e.g., AddCustomRule) can be added based on the existing architecture or integrated with the Windows Task Scheduler API, providing strong extensibility.

Leave a Comment