bug-gawk
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [bug-gawk] in-place edit request


From: Andrew J. Schorr
Subject: Re: [bug-gawk] in-place edit request
Date: Sun, 23 Dec 2012 20:30:14 -0500
User-agent: Mutt/1.5.21 (2010-09-15)

Perhaps this recipe may work:
http://stackoverflow.com/questions/4832603/how-could-i-temporary-redirect-stdout-to-a-file-in-a-c-program

It is also discussed here:
http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/redirecting-standard-io.html

Here's a test harness for that approach.  It seems to work on Linux
and on Cygwin:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int
main(int argc, char **argv)
{
   int bak, new;
   char instr[1024];

   puts("output on regular stdout");

   /* switch stdout to argument file */
   fflush(stdout);
   bak = dup(1);
   new = open(argv[1], O_WRONLY|O_CREAT, 0666);
   dup2(new, 1);
   close(new);

   while (fgets(instr, sizeof(instr), stdin))
      fputs(instr, stdout);

   /* restore stdout */
   fflush(stdout);
   dup2(bak, 1);
   close(bak);

   puts("after returning to regular stdout");
   return 0;
}

This obviously needs more error checking, but it seems to work.
So perhaps this can be packaged into an extension function after all.
Is this approach likely to work on all supported platforms?

Regards,
Andy



reply via email to

[Prev in Thread] Current Thread [Next in Thread]