基本上我希望echo "test" >> file.txt
直到file.txt达到2MB这样的特定大小,这可能吗?
答案 0 :(得分:0)
脚本将回显“test”到file.txt,直到它大于2 MB。虽然批次对于这样的事情来说很慢......你可以在一个块中回显更多的文本。像echo.test测试测试测试测试一样
@echo off
setlocal enabledelayedexpansion
set filename="file.txt"
rem 2097152 bytes=2 MB
set maxbytesize=2097152
:lop
for /F %%a IN (%filename%) do set size=%%~za
if !size! LSS %maxbytesize% (
echo.test>>%filename%
goto :lop
)
答案 1 :(得分:0)
不幸的是,批处理算法是有限的,因此使用此方法的最大文件长度限制为2 ^ 31-1个字节的文件(2GB)。无论如何,这应该足够快以便可用(对于2MB文件不到一秒钟)。
@echo off
setlocal enableextensions enabledelayedexpansion
set /a "size=1024*1024*2"
set "file=grow.txt"
set "tempFile=%temp%\%~nx0.%random%.tmp"
<nul set /p "x=." > "%tempFile%"
break > "%file%"
set "cmd=type"
for /l %%n in (1 1 31) do if defined size (
if %%n equ 22 (set "cmd=findstr ""^"" " )
set /a "first=size & 1" & if !first! equ 1 !cmd! "%tempFile%" >> "%file%"
set /a "size>>=1" & if !size! gtr 0 ( !cmd! "%tempFile%" >> "%tempFile%" ) else set "size="
)
del "%tempFile%" >nul 2>nul
endlocal
与评论相同
@echo off
setlocal enableextensions enabledelayedexpansion
:: Configure size and file to generate
set /a "size=1024*1024*2"
set "file=grow.txt"
:: Prepare a 1 byte temporary file
set "tempFile=%temp%\%~nx0.%random%.tmp"
<nul set /p "x=." > "%tempFile%"
:: Initialize the output file
break > "%file%"
:: To move data, type command is used for the 21 first
:: rounds, as it is more "efficient" for small sizes as
:: it does not have the overhead of creating a new process.
:: From this point, findstr replaces type command. The
:: overhead of creating the process is negligible vs the
:: speed on data transfer.
set "cmd=type"
:: Generate the final file, checking the bits in the
:: indicated size to determine how and when to add
:: data to the file.
echo %time%
for /l %%n in (1 1 31) do if defined size (
if %%n equ 22 (set "cmd=findstr ""^"" " )
set /a "first=size & 1" & if !first! equ 1 !cmd! "%tempFile%" >> "%file%"
set /a "size>>=1" & if !size! gtr 0 ( !cmd! "%tempFile%" >> "%tempFile%" ) else set "size="
)
echo %time%
:: Show generated file information
echo.
dir "%file%" | findstr /r /c:"^[0-9]"
echo.
:: cleanup
del "%tempFile%" >nul 2>nul
endlocal
有关此概念的解释,请参阅Ancient Egyptian Multiplication