Ahmad Alibrahim
Ahmad Alibrahim

Reputation: 27

Redirecting pipe from file to screen linux c

I have the following code (found it on internet)

FILE *fp;
fp=fopen("text.txt","w");
int fd=open("text.txt",O_WRONLY,S_IWUSR);
dup2(fd,1);

This code redirect the pipe from screen to a file named text.txt.
Now i need to do the opposite. I want to change the pipe writing from this file to the screen. Does anyone have an idea? Thank you

Upvotes: 0

Views: 468

Answers (2)

Camion
Camion

Reputation: 1374

On Linux, you can write to /dev/tty, but this is not equivalent to restoring writing to stdout, since you probably won't be able to redirect output from the calling program (Not sure - to be tested), and by the way, I'm not sure this is portable to other Unix based systems.

int fd=open("/dev/tty",O_WRONLY);
dup2(fd,1);

Otherwise, you should dup your file descriptor 1 to another one before the first redirection, so that you would be able to restore it later.

/* save fd 1 */
int sav=dup(1);

/* redirect to file */
int fd=open("text.txt",O_WRONLY,S_IWUSR);
dup2(fd,1);

/* done anything you wanted here (redirected to text.txt) */
/* ... */

/* revert redirection */
dup2(sav,1);

/* do anything you want here (having reverted the redirection back to stdout) */
/* ... */

By the way, one should probably avoid using both buffered (fopen) and unbuffered (open) I/O at the same time. This will cause problems since the buffered I/O are not informed of what you do at the same time with the unbuffered I/O.

Upvotes: 0

jwdonahue
jwdonahue

Reputation: 6659

That code only works because something is pushing data into the pipe. That would not be the case if you simply reversed the wiring of guzintas and comzoutas. You'll need to open the text file for reading and then read the file into memory and write it to the screen. There's lots of examples of source code out there for clones of cat.exe, go look on GitHub for the code.

Here's a very simple example:

#include <stdio.h>

void spewfile(FILE *fp)
{
  char buf[BUFSIZ];

  while(fgets(buf, sizeof(buf), fp))
    fputs(buf, stdout);
}

Upvotes: 1

Related Questions