ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Batch Script for Recursive Directory Traversal and File Processing

Batch

Goal -- WPM

Ready
Exercise Algorithm Area
1@echo off
2
3REM Advanced Batch Script: Recursive Directory Traversal and File Processing
4REM This script demonstrates a simulated recursive approach using CALL and GOTO
5REM to traverse a directory tree and perform an action on each file.
6
7setlocal enabledelayedexpansion
8
9REM --- Configuration ---
10set "START_DIR=C:\ProjectRoot"
11set "TARGET_EXTENSION=log"
12set "ACTION_TO_PERFORM=echo Processing file:"
13
14REM --- Global Variables (simulating state passed implicitly) ---
15echo Initializing traversal...
16set /a total_files_processed=0
17set /a total_directories_visited=0
18
19REM --- Pre-checks ---
20if not exist "%START_DIR%" (
21echo Error: Starting directory "%START_DIR%" not found.
22goto :eof
23)
24
25REM --- Main Entry Point ---
26call :TraverseDirectory "%START_DIR%"
27
28REM --- Post-Traversal Summary ---
29echo.
30echo Traversal complete.
31echo Total directories visited: !total_directories_visited!
32echo Total files processed (with extension .%TARGET_EXTENSION%): !total_files_processed!
33
34endlocal
35exit /b 0
36
37REM --- Recursive Function: TraverseDirectory ---
38REM Parameters:
39REM %1: The current directory path to traverse.
40REM Usage: call :TraverseDirectory "C:\Some\Path"
41
42:TraverseDirectory
43set "current_dir=%~1"
44
45REM Increment directory visit count
46set /a total_directories_visited+=1
47
48REM Process files in the current directory
49for %%F in ("%current_dir%\*.*") do (
50REM Check if it's a file (and not a directory itself if the pattern is too broad)
51if not exist "%%F\" (
52set "filename=%%~nxF"
53set "fileext=%%~xF"
54
55REM Check for the target extension (case-insensitive comparison simulated)
56set "lower_fileext=!fileext:~1!"
57set "lower_target_ext=%TARGET_EXTENSION%"
58if /i "!lower_fileext!" == "!lower_target_ext!" (
59REM Perform the action on the file
60%ACTION_TO_PERFORM% "!filename!" in directory "%current_dir%"
61REM Increment file processed count
62set /a total_files_processed+=1
63)
64)
65)
66
67REM Recursively call for subdirectories
68for /d %%D in ("%current_dir%\*") do (
69REM Avoid infinite loops with junctions/symlinks by not re-visiting parent or known paths
70REM This is a simplified check; true cycle detection is complex in Batch.
71REM For this example, we assume a standard tree structure.
72
73set "subdir=%%~fD"
74REM Basic check to prevent immediate parent traversal if structure is unusual
75REM A more robust solution would involve tracking visited paths.
76if not "%subdir%" == "%current_dir%\.." (
77call :TraverseDirectory "%subdir%"
78)
79)
80
81REM Base case: If no more subdirectories or files to process in this branch, the CALL returns.
82
83exit /b
Algorithm description viewbox

Batch Script for Recursive Directory Traversal and File Processing

Algorithm description:

This Batch script simulates a recursive directory traversal. It starts from a given directory and recursively explores all subdirectories. For each file encountered that matches a specific extension, it performs a predefined action, such as echoing a message. This pattern is useful for batch file operations like finding specific configuration files, archiving old logs, or performing bulk updates across a project's directory structure.

Algorithm explanation:

The script simulates recursion using Batch's `call` command to invoke the `:TraverseDirectory` subroutine. The `call` command effectively pushes the return address onto an implicit stack, allowing the script to return to the correct point after the subroutine finishes. The `:TraverseDirectory` subroutine first processes files in the current directory, checking for a target extension. It then iterates through subdirectories using `for /d` and recursively calls itself for each subdirectory. The base case for the recursion is when a directory has no more subdirectories to explore, at which point the `call` returns. Edge cases handled include the starting directory not existing and the target extension comparison being case-insensitive. A simplified check is included to avoid immediate parent traversal, though true cycle detection in Batch is very complex. The time complexity is roughly O(N*M) where N is the number of files and M is the average time to process a file, plus the overhead of directory enumeration, as each file and directory is visited once. Space complexity is O(D) in the worst case, where D is the maximum depth of the directory tree, due to the implicit call stack managed by `call`.

Pseudocode:

1. Define starting directory, target file extension, and action command.
2. Initialize global counters: total_files_processed, total_directories_visited.
3. Check if starting directory exists; exit if not.
4. Call :TraverseDirectory with the starting directory.
5. After traversal, display summary of visited directories and processed files.

Subroutine :TraverseDirectory(current_directory):
  Increment total_directories_visited.
  For each item in current_directory:
    If item is a file:
      Get file name and extension.
      If file extension matches target extension (case-insensitive):
        Execute action command on the file.
        Increment total_files_processed.
  For each subdirectory in current_directory:
    Perform a basic check to avoid immediate parent traversal.
    If check passes:
      Call :TraverseDirectory(subdirectory).
  Return (implicit via CALL return).