-
Redirecting stdout
Hello!
I'm trying to write a program able to execute the "date" command, retrieve the date printed on the standard output and then pass it to a variable in the program. Unfortunately my program doesn't work, so can you help me to find a way to create a working program, please?
The code I've written is the following:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(){
int fd[2];
pipe(fd);
if(!fork()){
close(fd[0]);
dup2(fd[1], STDOUT_FILENO);
execlp("date", "date", NULL);
} else {
FILE* stream;
char* res;
close(fd[1]);
stream = fdopen(fd[0], "r");
fscanf(stream, "%s", res);
printf("The result is %s\n", res);
}
return 0;
}
Thanks in advance for any help!
-
C has standard functions for getting the date. I suggest you use one of them.
Put your fork, back down with the spoon! :D
-
freopen - C++ Reference
Note: I agree with prior post use the C built in time functions to get date.
Tim S.
-
Obviously you want to use standard functions to get the date. But for reference...
Your program isn't working because you're not allocating memory for “res”. You can just make it an array in this case. But if you need to read the output of a program on a POSIX system, you probably just want to use popen().
With real code, you'd also want to check the return values of functions to make sure they ran successfully.