Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

what do i need to do to get this popen code to run : #include<iostream> #include

ID: 3801918 • Letter: W

Question

what do i need to do to get this popen code to run :

#include<iostream>

#include<stdio.h>

#include<string.h>

using namespace std;

int main(){

    char s[100];

    cout << "please enter a command";

    cin >> s

    FILE *fp = popen(s,"r");

    const int BUFFER_SIZE = 100;

    char buff[BUFFER_SIZE];

    //cout << "Enter your command: ";

    //cin >> buff;

   while(fgets(buf, BUFFER_SIZE, fp)){

       cout << buf

   }

   pclose(fp);

}

    do{

    char s[100];

    cout << "please enter a command";

    cin >> s

    FILE *fp = popen(s,"r");

    const int BUFFER_SIZE = 100;

    char buff[BUFFER_SIZE];

    //cout << "Enter your command: ";

    //cin >> buff;

   while(fgets(buf, BUFFER_SIZE,fp)){

       cout << buf

       3while(strcmp(s,"exit"))

   }

}

Explanation / Answer

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
FILE *in;
char buff[512];
char s[100];
cout << "please enter a command";
cin >> s;
if(!(in = popen(s, "r"))) // for handling error
{
return 1;
}
while(fgets(buff, sizeof(buff), in)!=NULL)
{
cout << buff;
}
pclose(in);
do
{
FILE *in;
char buff[512];
char s[100];
cout << "please enter a command";
cin >> s;
if(!(in = popen(s, "r")))
{
return 1;
}
while(fgets(buff, sizeof(buff), in)!=NULL)
{
cout << buff;
}
}while(strcmp(s,"exit")!=0);
pclose(in);
return 0;
}

output

sh-4.2$ g++ -main *.cpp                                                                                                                                                       

sh-4.2$ main                                                                                                                                                                    

please enter a commandls                                                                                                                                                        

main                                                                                                                                                                            

main.cpp                                                                                                                                                                        

please enter a commandexit

popen() function executes the command and pipes the command to the calling program, returning a pointer which can be used by calling program to read/write to the pipe.