2

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);
    }
}
1
  • Welcome to StackOverflow. Generally, we very much value questions that include complete examples, i.e. code that can be copied, pasted, and compiled to reproduce exactly what you are seeing; your example is missing the #include statements and an int main(). Commented Mar 15, 2022 at 14:15

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Sidenote: If you (@KinoDerToten) expected your program to change the directory permanently, i.e. leaving you in a different directory than the one you started the executable from, note that running the executable creates a new process, and that cd would affect that process only, not the calling process. I.e., the cd does happen, but only for (and until the end of) the process executing your programm. The calling process remains in its current directory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.