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