Apr 24, 2008

Redirecting standard error output in cmd.exe

Hi. Suppose you have the following C++ program (in a Windows box):
#include "stdafx.h"
#include "string.h"


void write(char *str, FILE *target)
{
fwrite(str, strlen(str), 1, target);
}

void _tmain(int argc, _TCHAR* argv[])
{
write("Test:stderr\r\n", stderr);
write("Test:stdout\r\n", stdout);
}
and you want to redirect its output to a file. We could try something like in Windows console:
test.exe > myfile.txt

Unfortunately the naive approach don't work because there are data being outputted to stderr and we are redirecting only the standard output (stdout). In order to redirect stderr we can use the following syntax:
command handler# > target

let's try a sample:
test.exe 1>myfile.txt

This will redirect stdout (handle 1) to myfile.txt To redirect stderr (handle 2) we can use:
test.exe 2>myfile.txt

Ok. Now we can try:
test.exe > myfile.txt 2>myfile.txt

but, again, this doesn't work; instead we get an error message:
D:\temp\cpp\Test\Debug>Test > myfile.txt 2>myfile.txt
The process cannot access the file because it is being used by another process.
Ok, there's one last trick we can try (duplicate stderr to stdout):
test.exe > myfile.txt 2>&1

Great! Now it works as expected! Last, but not least,
you can find more information here. Hope this can be useful :) Adriano

5 comments:

Anonymous said...

Hi, I was wondering if you could perhaps explain this: http://forum.sysinternals.com/forum_posts.asp?TID=15304&PN=1

Wouter.

Anonymous said...

hmm.. url not pasing ok... here it is again:

http://forum.sysinternals.com/forum_posts.asp?TID=15304&PN=1forum_posts.asp?TID=15304&PN=1

(last part should be: TID=15304&PN=1)

programing-fun said...

Hi.

Indeed it changes the batch from

echo blabla > somefile.txt

to

echo blabla 1>somefile.txt

but it works (at least in my simple test "blabla" gets inserted into somefile.txt)

1>somefile.txt is just a redirection from stdout to somefile.txt.

Adriano

Anonymous said...

Great.. you saved my day!

Unknown said...

Great saved my day too!