dbenham wrote:I disagree - it has everything to do with FOR vs. FOR /F. I've done a fair bit of testing on this in the past, and I have never seen a DO clause modify the iterations of a FOR /F. I just ran a FOR /F test on a 12.5 mb file with many thousands of lines. The very first iteration I overwrite the entire file with a single line of text. Never-the-less, my FOR /F printed out all the original lines, and the newly created line was not read.
It does not matter which flavor of FOR /F is used: string, file, or command - the entire result set is static and cached somehow before any iteration takes place. The DO clause cannot affect the content of the iterations. I've never seen documentation that states, this. It is only what I have observed. I'd be very interested to hear of any reproducible example that contradicts this theory.
Dave Benham
I tried to find such an example, so I ran next program with a file every time larger:
Code: Select all
@echo off
setlocal EnableDelayedExpansion
for /F %%a in ('find /V /C "" ^< largeFile.txt') do set lines=%%a
echo Total lines: %lines%
set /A line=0, last10=lines-10
for /F "delims=" %%a in (largeFile.txt) do (
set /A line+=1
if !line! leq 10 (
echo Copy of line !line!: %%a >> largeFile.txt
echo Line !line! copied
)
if !line! geq %last10% echo Line !line!: %%a
)
I ran previous program with a file up to 60 MB size with no success: FOR /F command always read just the original file lines. There is no way that FOR /F load the file into a buffer that large, so the only explanation is that the file handle that FOR /F use to read the file
is not the same used in ">> largeFile.txt" append operations inside FOR-body, although both handles refer to the same physicall file. This way, the file handle used by FOR /F command is not modified by any other access to the same file, until FOR terminate and its handle is closed.
A way to prove this idea is trying to force that both handles be the same, that is, to open the handle used by our append operations at the same time FOR /F command open the file. I wrote this program to test that:
Code: Select all
@echo off
setlocal EnableDelayedExpansion
> Days.txt (for %%a in (Monday Tuesday Wednesday Thursday Friday Saturday Sunday) do echo %%a)
type Days.txt
>> Days.txt (for /F "delims=" %%a in (Days.txt) do (
set /A line+=1
echo Copy of line !line!: %%a
))
However, when I ran this program something unexpected happen:
Code: Select all
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
The system cannot find the file Days.txt.
After this result I am pretty sure that FOR /F command open the file for Reading only and Exclusive access. This way, if the file is already opened when FOR is executed, the file just can't be opened by FOR /F command. This mechanism assure that
there is no way to modify the content of the file being read by FOR /F command.
Antonio