Luke Fast
Luke Fast

Reputation: 21

Check length of a filepath with a batch file. #stringlength

This is my first post and I hope someone can help me.

I'm fairly new to .bat files but I have a basic understanding of php and c++.

I need to write a batch file that will do the following: 1. Display all files including full filepath in the current folder. 2. Display length of the displayed files including the filepath for each individual file. 3. Maybe show how many files there are in total.

I've written this so far and it does Job #1 and #3 but I can't get it do display the string lenght.

@echo off
for /r . %%g in (*.*) do (
    echo %%g
)       
set cnt=0
for %%A in (*) do set /a cnt+=1
set /A cnt=cnt-1
echo Dateien im Verzeichnis = %cnt%
PAUSE

I found two other scripts that each identify lenght of a string or a path but I couldn't put them together with my first script.

Here the one for String Lenght:

@echo off
set myvar="some string"
rem compute the length of a string
set #=%myvar%
set length=0
:loop
if defined # (
    rem shorten string by one character
    set #=%#:~1%
    rem increment the string count variable %length%
    set /A length += 1
    rem repeat until string is null
    goto loop
)
echo myvar is %length% characters long!
PAUSE

And here a piece that will display the path length of the current folder:

@echo off
echo %cd%>"%TMP%\Temp.txt"
for %%l in ("%TMP%\Temp.txt") do set /a len=%%~zl
del "%TMP%\Temp.txt"
set /a len-=2
echo Path length = %len% chars.
PAUSE

Upvotes: 2

Views: 2195

Answers (1)

rojo
rojo

Reputation: 24466

Here's a solution based on this :length util function. For more information on batch script functions, see this page. You should also read more about delayed expansion. Even when not using delayed expansion, setlocal ought to be included at the top of all your scripts.

@echo off
setlocal

set "files=0"

for %%I in (*) do (
    set /a files += 1
    call :length len "%%~fI"

    rem // delay expansion of %files% and %len% because of reasons
    setlocal enabledelayedexpansion
    echo !files!: %%~fI is !len! characters long.
    endlocal
)

goto :EOF

:length <return_var> <string>
setlocal enabledelayedexpansion
if "%~2"=="" (set ret=0) else set ret=1
set "tmpstr=%~2"
for %%I in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
    if not "!tmpstr:~%%I,1!"=="" (
        set /a ret += %%I
        set "tmpstr=!tmpstr:~%%I!"
    )
)
endlocal & set "%~1=%ret%"
goto :EOF

Upvotes: 2

Related Questions