在很多时候,我们需要在CMD窗口中手动输入文件名来创建文件,比如本人曾经做过的
文件备份器 ,这个时候,往往需要对输入的字符串做非法字符的检测。但是,不能做文件名的字符是如此之多:有各种控制符号、/、\、>、<、"、系统设备保留字符(如nul、com1等)……若用穷举法的话,姑且不论CMD特殊字符的处理是何等地让人绞尽脑汁,光是那一大堆非法字符,恐怕没人能轻易地全部罗列出来,基于对特殊字符的头痛及挂一漏万的担忧,以前一直没找到一个合适的方案,现在得以有闲,写了段代码,
用于演示检测被当作文件名输入的字符串是否含有非法字符,发出来让大家讨论一下:
@echo off
:: 思路:在系统临时目录下创建随机文件,把检测非法字符的任务交给操作系统来完成
:: Thanks to qzwqzw
:main
cls
set input=
set /p input= 请输入文件名:
call :check
pause
goto main
:check
set "str1=%input:"=%"
set "str2=%input:"= %"
if not "%str1%"=="%str2%" goto main
:loop
set rnd=%random%
if exist "%tmp%\%input%%rnd%" goto loop
cd.>"%tmp%\%input%%rnd%" 2>nul || goto main
del /q "%tmp%\%input%%rnd%"
echo "%input%" 是合法的文件名
goto :eof
Last edited by namejm on 2007-5-29 at 11:28 PM ]
In many cases, we need to manually enter a file name in the CMD window to create a file. For example, the
File Backup Tool I once made. At this time, it is often necessary to detect illegal characters in the input string. However, there are so many characters that cannot be used as file names: various control symbols, /, \, >, <, ", system device reserved characters (such as nul, com1, etc.)... If we use the exhaustive method, regardless of how painstaking the processing of CMD special characters is, just the large number of illegal characters, I'm afraid no one can easily list them all. Due to the headache of special characters and the worry of missing something, I haven't found a suitable solution before. Now I have time, I wrote a piece of code,
used to demonstrate whether the string entered as a file name contains illegal characters, and post it for everyone to discuss:
@echo off
:: Idea: Create a random file in the system temporary directory and leave the task of detecting illegal characters to the operating system
:: Thanks to qzwqzw
:main
cls
set input=
set /p input= Please enter the file name:
call :check
pause
goto main
:check
set "str1=%input:"=%"
set "str2=%input:"= %"
if not "%str1%"=="%str2%" goto main
:loop
set rnd=%random%
if exist "%tmp%\%input%%rnd%" goto loop
cd.>"%tmp%\%input%%rnd%" 2>nul || goto main
del /q "%tmp%\%input%%rnd%"
echo "%input%" is a legal file name
goto :eof
Last edited by namejm on 2007-5-29 at 11:28 PM ]