FILE * _popen() didn't work correctly.

Hi
I'm having a problem with the _popen function on windows.
It usually works properly with me. But when I use it to execute a wrong command, it don't return a pointer to a FILE that contains the resulted output; It prints the output to the console screen instead!

For example, when I use it to execute "DIR F:\" while the drive F: not found,
the output ("The system cannot find the path specified.") is printed on the console screen without using any output function. and I can't get it as an input to the program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
int main( void )
{
   char   line[100];
   FILE   *CommandResult;
   int NumberOfLines=0;

   CommandResult = _popen( "DIR C:\\ ", "rt" );

   while(fgets(line, 100, CommandResult))
   {
      NumberOfLines++;
   }
    printf("The command returned %d line[s] of text.",NumberOfLines);
}


on the above example every thing worked properly. and the text printed on the screen is The command returned 16 line[s] of text. and nothing else.

But when I use the same code, just for another directory like, A:, B:, or any partition that's not in the computer, it prints...
1
2
The system cannot find the path specified.
The command returned 0 line[s] of text.


I have no problem with the returned FILE being empty as a signal that the command is wrong. but I don't want the error message to be printed on the console screen.
or is there a function that could examine the command and return a bool value that could tell if the command could be executed or it'd return an error?
and I'm using Code::Blocks by the way (if that matters)
Redirect error output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>

int main(void)
{
    char   line[100];
    FILE   *CommandResult;
    int NumberOfLines = 0;

    CommandResult = _popen("DIR C:\\ 2> nul", "rt");

    while (fgets(line, 100, CommandResult))
    {
        NumberOfLines++;
    }
    printf("The command returned %d line[s] of text.", NumberOfLines);
}
I almost lost hop about solving this problem. But your answer solved the problem perfectly! Thank you very much sir :)
Topic archived. No new replies allowed.