4

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

Table from wikipedia page

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.

Wolf
  • 9,679
  • 7
  • 62
  • 108
Monacraft
  • 6,510
  • 2
  • 17
  • 29
  • Somewhat related: http://stackoverflow.com/questions/9878007/how-to-permanently-redirect-standard-error-back-to-the-console-again – Taylor Hx Nov 12 '13 at 04:26

1 Answers1

6

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

Aacini
  • 65,180
  • 12
  • 72
  • 108
  • Actually, could I use this to output data to the console while accepting input? – Monacraft Nov 12 '13 at 08:56
  • Yes. Just use redirection to/from `CON`: `echo This always go to console > CON` – Aacini Nov 12 '13 at 16:43
  • ...just in case "here" moves sometimes: [foolproof counting of arguments - Page 3 - DosTips.com](http://www.dostips.com/forum/viewtopic.php?f=3&t=2836&p=29634#p29634) – Wolf Feb 13 '17 at 15:51
  • @Wolf: I am afraid I don't follow you... The posts at DosTips.com site are numbered and such numbers _never change_! In the case of the "here" link, the topic&reply numbers are `t=2836&p=29634#p29634` in both my answer and your comment, so your comment is totally unnecessary... – Aacini Feb 13 '17 at 16:35