Define a new handle (Similar to STDOUT)

回眸只為那壹抹淺笑 提交于 2019-12-01 04:58:24

问题


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



来源:https://stackoverflow.com/questions/19920517/define-a-new-handle-similar-to-stdout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!