Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

stdout 1

Status
Not open for further replies.

maschwa

Programmer
Mar 8, 2002
9
0
0
AT
Hi all!

This is my problem:

void getfiles(char *f){
freopen(f,"a",stdout);
fprintf(f,"%s",system("dir /b c:\\bcn\\data\\*.*"));
fclose(f);
}

It works correctly, but the rest of the programm also is written in 'f'. I want to write the rest of output in normal stdout. How can I disconnect f and stdout to handle that?

Thanks for help in advance!

Br maschwa
 
The freopen() will close the orginal stream(in our case it is stdout; passed as an argument to this function), but we are having some other way to achive our aim.

Use the following code this will solve the problem.

#include <stdio.h>
int main()
{
int iNewStdout;
FILE *fpStdout;
char text[100];
/* creation of duplicate file descriptor for stdout */
iNewStdout = dup(1);
fpStdout = freopen(&quot;dup.data&quot;, &quot;w&quot;, stdout);
/* Do whatever you want, the stdout is redirected to the file dup.dat */
...
...
...
fclose(fpStdout);
/* Creation of new file pointer from the backup fd*/
stdout = fdopen(iNewStdout, &quot;w&quot;);
/* Now this will go to the screen */
printf(&quot;Haiiiiiii \n&quot;);

return 0;
}

--Maniraja S
 
now is there a way to fork off a subprocess and have it's output redirected to the same place without editing the code for the subprocess? Mike
~~~~
simanek@uiuc.edu
&quot;It's a Swingline!&quot;
~~~~
 
Hi Smaniraja!

Nice code, but it doesn´t work! I always get a lvalue error if I compile with Borland-16bit compiler. Can you tell me why?

Thanks
 
Hi Maschwa,

I have posted the code for Unix OS. If your using the Turboc C/C++ IDE for DOS, then do the following changes.

1. Declare one more pointer variable of the type FILE,
ie FILE *tStdout;

2. Instead of the statement
stdout = fdopen(iNewStdout, &quot;w&quot;); put the following statements

tStdout = fdopen(iNewStdout, &quot;w&quot;);
memcpy(tStdout, stdout, sizof(FILE));

Now it will work.

---Maniraja S
 
Thanks Maniraja, it works correct, but I had to cancel the line: /*memcpy(tStdout, stdout, sizof(FILE));*/ because I got an error. I tried to execute without this line, and it seems to work well!

Maschwa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top