Define a new handle (Similar to STDOUT)

2019-02-18 11:18发布

问题:

I was looking at redirecting handles in batch, when I noticed this:

Here is the link

It mentions that handles 3-9 are undefined and can be defined by a program. Now I've read about doing this in C#, but I wondered if this was possible in cmd/batch - and if it is, what are its limitations/use.

If it is not possible in cmd, how would I go about using this, and could it be a solution to outputting data to the screen and redirecting it to a file at the same time (a problem which has not been able to be done legitimately at the same time).

Thanks, Mona.

回答1:

A Batch file is limited to manage just two files: STDIN for input (SET /P) operations, and STDOUT for output (ECHO, etc.) operations; however, we could have access to more than one input and output files in a Batch file. How to do that? In a relatively easy way: just connect the additional files to unused handles (3-9) and use the appropiate handle in the input (SET /P <&#) or output (ECHO >&#) commands.

The Batch file below merge the lines of 3 input files into one output file with larger lines:

@echo off
setlocal EnableDelayedExpansion
3<input2.txt 4<input3.txt (
for /F "delims=" %%a in (input1.txt) do (
   set line=
   rem Read from input2.txt (and write line from input1 to output.txt):
   set /P line=%%a <&3
   rem Read from input3.txt (and write line from input2 to output.txt):
   set /P line=!line! <&4
   rem Write line from input3 to output.txt:
   echo(!line!
)
) >output.txt

The same method may be used to generate several output files.

See: Access to SEVERAL files via Standard Handles

And a more technical explanation here