I have a C++ program which has the prototype of the main function as follows:
int main(int argc, char * argv[])
The code hasn’t been written by me, but this is a single C file available here.
When I compile this code, and through the command line run it as:
someexe in.txt > out.txt
This gives me an output out.txt which is generated in the same directory by operating on some input from in.txt.
someexe in.txt out.txt
This gives me an output on the command line itself. (without using > operator)
However, instead of passing the command line argument and without using the output redirection > operator, I have been trying to call the main function from another function and passing the parameters myself. If I pass an array of char* {fileDirName, in.txt}, I am not sure how to go about generating an out.txt (since I think > output redirection is an operating system level function available in command line).
Any suggestions would be greatly appreciated
The program in the link is readily available as copy paste and can be tried (main function is written at the last in the above program)
Assuming the aim is to mimic the output redirection feature (
> out.txt) of the shell you can do something like:You can do similar for stdin also, to mimic the input redirection (
< in.txt). These will be preserved across calls toexec()too.Of course it would be simpler to modify the program to write to the place you wanted given you have the source available.
Note though that
dup2(), which “swap” the stdout fd for the one we just opened is non-portable. IIRCopen()(as opposed tofopen()) is UNIX specific also)