0

So I'm trying to redirect standard output to a file using dup().

int save_fd;
save_fd=dup(1); //saves the current stdout
close(1); //closes stdout
dup2(file.txt, 1);//redirect output to file.txt

//output goes to file.txt

dup2(save_fd, 1); restore stdout
close(1);

I know I can open a file using fopen. Since dup2 takes int, how do I specify the file descriptor for file.txt?

2 Answers2

2

Use open which returns an fd instead of fopen.

kaylum
  • 13,833
  • 2
  • 22
  • 31
1

Well, you have two possibilities to get a file descriptor:

  1. open()

  2. fopen() and then call fileno() on the opened stream

So, in the case of open() the return value in case of success is the file descriptor you're looking for:

int fd = open("some_path", ...);

while in the case you want to use fopen(), you can still retrieve the file descriptor associated with the open stream but you need to call the function fileno():

FILE *stream = fopen(some_file, "w");
int fd = fileno(stream);
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
fedepad
  • 4,509
  • 1
  • 13
  • 27
  • Thanks @fedepad. I tried using open but get error saying, "invalid in C99" so I'm using open() for the time being. I used `FILE *out=fopen("file.txt", "a"); fd_new=fileno(out);` and that worked. However now I don't get my terminal back after running. I did `fclose(out)` and I thought `dup2` restored it? – user2217060 Feb 10 '17 at 21:59
  • @user2217060 I gave you the general ways to get fd. Please have a look here http://stackoverflow.com/questions/14543443/in-c-how-do-you-redirect-stdin-stdout-stderr-to-files-when-making-an-execvp-or which I think it's related to what you're trying to achieve. – fedepad Feb 10 '17 at 22:08