I'm having a strange issue using the dup2 system call to redirect STDOUT to a file.
I'm using 2 functions which i found here: In C how do you redirect stdin/stdout/stderr to files when making an execvp() or similar call?
Below is a simple program i wrote to test the functions after i had errors. The program works as expected and writes the input to the file.
int fd;
fpos_t pos;
int main(){
while(1){
char input[100];
printf("Please enter text: ");
gets(input);
printf("\nString = %s\n", input);
switchStdout("test.txt");
puts("THIS TEXT SHOULD REDIRECT\n");
printf("String(file) = %s\n", input);
revertStdout();
puts("This should come before the gets() ??\n");
}
return 0;
}
void switchStdout(const char *newStream)
{
fflush(stdout);
fgetpos(stdout, &pos);
fd = dup(fileno(stdout));
freopen(newStream, "w", stdout);
return;
}
void revertStdout()
{
fflush(stdout);
dup2(fd, fileno(stdout));
close(fd);
clearerr(stdout);
fsetpos(stdout, &pos);
}
After the revertStdout() function is called, the program appears to hang.
I realized that, in fact, the program has called gets() before printing "This should come before the gets() ??"
After I enter text, the program prints the skipped lines.
Here is the terminal output with what I enter in bold:
Please enter text: Hello!!!!
String = Hello!!!!
Why am i able to type here ??
This should come before the gets() ??Please enter text:
String = Why am i able to type here ??
Sorry about the long post. The program writes as expected to the file.
Thanks for any help anyone can provide.