KinoDerToten
KinoDerToten

Reputation: 31

How to use _popen() with string input?

I try to use _popen() to view files. When I write one word command like ipconfig or dir it works fine. However when I try something with space in it like cd .. or cd C:\, it won't work(it won't change the directory), the program just does nothing. I don't get a error. I'm on a Windows machine. I don't know if it has anything to do with the spaces. I tried something like this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Windows.h>

int main()
{
    while (1)
    {
        char buff[500];
        char input[100];
    
        printf("Command: ");
        fgets(input, 100, stdin);
    
        FILE* f = _popen(input, "r");
    
        while (fgets(buff, 200, f) != NULL)
        {
            printf("%s", buff);
        }
    
        _pclose(f);
    }
}

Upvotes: 2

Views: 437

Answers (1)

Serve Laurijssen
Serve Laurijssen

Reputation: 9733

Thats because cd does not produce any output. In other words, does not write to stdout

Try "dir c:" and see if you can read from the pipe

Command: cd ..
Command: dir c:
 Volume in drive C has no label.
 Volume Serial Number is F4DC-394E

 Directory of popen

15-03-2022  15:28    <DIR>          .
15-03-2022  15:28    <DIR>          ..
15-03-2022  15:28    <DIR>          Debug
15-03-2022  15:28               520 popen.cpp

Upvotes: 1

Related Questions