|
|
|
What is it?
|
|
|
|
--------
|
|
|
|
[I/O Redirection](http://www.tldp.org/LDP/abs/html/io-redirection.html) is a powerful tool that allows the shell to either simulate keyboard input from a file (input redirection), capture all output in a file (output redirection), or both. Using redirection allows programs to use files for input and output using only `cin`, `cout`, and/or `cerr`, eliminating the need to explicitly handle files (`fopen()`) or input streams (`istream` or `ostream`).
|
|
|
|
|
|
|
|
### Examples
|
|
|
|
```
|
|
|
|
% ./program < redirected-to-cin.txt
|
|
|
|
% ./program > redirected-from-cout.txt
|
|
|
|
% ./program > redirected-from-cout.txt 2> redirected-from-cerr.txt
|
|
|
|
% ./program < redirected-to-cin.txt > redirected-from-cout.txt
|
|
|
|
etc...
|
|
|
|
```
|
|
|
|
|
|
|
|
How to do it
|
|
|
|
--------
|
|
|
|
|
|
|
|
### Command-line Arguments (options, arguments and filenames)
|
|
|
|
|
|
|
|
To specify command-line arguments in Xcode select from the menu Product -> Scheme -> Edit Scheme. Savvy users will use the keyboard shortcut Command+<. The arguments specified this way will be read and passed to your program in `argv[]`, which will allow you use `getopt()`, `getopt_long()`, or simply parse the arguments manually.
|
|
|
|
|
|
|
|
### File Redirection
|
|
|
|
|
|
|
|
Xcode will allow you specify command-line parameters, but no longer directly supports command-line style redirection. To provide your own support, you can use [`freopen()`](https://linux.die.net/man/3/freopen). This will let you open a file using a filename and associate it with a stream.
|
|
|
|
|
|
|
|
#### Examples
|
|
|
|
|
|
|
|
```C++
|
|
|
|
int main() {
|
|
|
|
freopen("redirected-to-cin.txt", "r", stdin); // Redirected input
|
|
|
|
freopen("redirected-from-cout.txt", "w", stdout); // Redirected output
|
|
|
|
freopen("redirected-from-cerr.txt", "w", stderr); // Redirected output
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
How to do it well
|
|
|
|
--------
|
|
|
|
|
|
|
|
### Conditional compilation
|
|
|
|
|
|
|
|
### Using environment variables |
|
|
\ No newline at end of file |