Mail Archives: djgpp/2000/11/28/18:21:43
Hans-Bernhard Broeker wrote:
> > I'm trying out with popen function. It says (at help file) that it can
> > open a program for reading and writing
> > handle = popen ("program", "rb+")
>
> In what help file did you find that? It's untrue, for every popen()
> implementation I've seen. The only 'mode' arguments for popen() are
> "r" and ". I.e. the DJGPP docs may have a little flaw, here, where
> they say:
>
> The MODE is the same as for `fopen' (*note fopen::.).
>
> That's not true.
Oh, I think that's it, then.
Just as you said, I've searched for popen, and help says the mode is the
same as for fopen.
So, I'm going to post the problem I was working on, maybe you guys can
give some ideas (I'm counting on you! :).
I was trying to control a "child" program within a "parent" one, sending
to it messages and reading it's output, without the user even noticing
the existence of "child". It worked fine for writing OR reading, but I
couldn't figure it out why it was not working for both (thank you, now I
know !)
Here is the code:
================= child ================
// child.cpp: must be called within parent
#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <stdio.h>
#include <fstream.h> //ifstream, ofstream
int main()
{
clrscr();
char buf[100];
ofstream out ("out.txt");
int a;
cout<<"CHILD: Enter a number: ";
cin >> a;
cout <<"CHILD: Enter some words: ";
gets (buf); // somebody said me I must use fgets -- why?
// Sending results to screen
cout << "\nCHILD: The squared number is: " << a*a << endl;
cout << "CHILD: The words were: "<< buf;
// Sending results to file "out.txt"
out << "\nThe squared number is " << a*a <<endl;
out << "The words were "<< buf;
return 0;
}
=========== parent =====================
// PARENT: Calls child program, send values to it
// and checks for screen output. "Emulates a user"
#include <stdio.h>
#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <fstream.h>
int main()
{
clrscr();
FILE* handle;
char buf[100];
handle = popen("child", "wt+"); // + opens for both write/read.
// Writing test: int & string
int a;
cout <<"PARENT: Enter a number: ";
cin >> a;
fprintf (handle,"%i\n",a); // \n = pushes ENTER into child
cout << "PARENT: Enter some words: ";
gets (buf); // fgets ?
fprintf (handle, "%s\n", buf); // \n = pushes ENTER
rewind (handle); // Prepares to change for reading
// How can I read the output of child?
// Testing reading
while (fgets (buf,100,handle))
cprintf ("line obtained= %s", buf);
getch();
pclose(handle);
return 0;
}
-------------------------------------------
It's possible to solve this problem in a reasonable simple way?
Thank you very much!
Sincerely,
Anderson.
- Raw text -