Hi, how would I make a program that gets input from a user, sends it to a program with popen(), gets the output, and repeats this until the program ends? I have tried, but I only get part of the output, and when I type "exit", it won't end the program.

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;

int main()
{
   
FILE *fp = popen("cmd.exe", "r+" );
char buff[50];
char command[50];

while (fp != NULL)
{
while ( fgets( buff, sizeof buff, fp ) != NULL ) 
{
  cout << buff;
}
cin.getline(command, sizeof command);
fputs(command, fp);
}
pclose( fp );

getch();  
   
}

From this, I only get "Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp." when it starts, while I should also be getting the "C:\documents and settings\...." after it.

Recommended Answers

All 5 Replies

Better check your popen() manual, because most implementations are uni-directional.
Either read-only, or write-only.

That's weird, because if you type help, you will get the help message.

I modified it a little:

strcat(command, "\n");
fputs(command, fp);

It's better, but I still can't get the ouput correctly.

Hi, how would I make a program that gets input from a user, sends it to a program with popen(), gets the output, and repeats this until the program ends? I have tried, but I only get part of the output, and when I type "exit", it won't end the program.

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;

int main()
{
   
FILE *fp = popen("cmd.exe", "r+" );
char buff[50];
char command[50];

while (fp != NULL)
{
while ( fgets( buff, sizeof buff, fp ) != NULL ) 
{
  cout << buff;
}
cin.getline(command, sizeof command);
fputs(command, fp);
}
pclose( fp );

getch();  
   
}

From this, I only get "Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp." when it starts, while I should also be getting the "C:\documents and settings\...." after it.

I don't think you're supposed to get "C:\documents and settings\...." when you run this. That's the command line prompt, not part of the program. The output I got from the program was the same as when I type "cmd" in at the command prompt. Same thing when I wrote a little "Hello World" program and replaced "cmd.exe" with "HelloWorld.exe". It just displayed "Hello World". Is it supposed to display the command prompt before the program exits? Maybe I'm confused about the goal of the program.

I think you're right. I changed the command to help. That displayed the entire thing. Thanks for the help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.