Xcodeで入出力ファイルのリダイレクトを行いたい場面に遭遇し,試行錯誤しているうちにできるようになったので,ここに手順を書き留めておきます.
どなたかのお役に立てれば幸いです.
1. 作業用ディレクトリと入出力ファイルの準備
今回は/Users/ashipan/Redirection のディレクトリ内にmain.cpp, input.txt, output.txtファイルがあるとして作業を進めていきます.
ディレクトリ構成やファイル名は自分の環境に合わせて読み替えて進んでください.
今回行いたいリダイレクトは以下のようなものです.(a.outは実行ファイル)
./a.out < input.txt > output.txt
2. Working Directory の設定
Xcodeのメニューバーから Product > Scheme > Edit Scheme を選択します.左のRunと右のOptionsを選択してUse custom working directoryを選択し, working directoryに入出力ファイルがある場所(Users/ashipan/Redirection)を指定します.
3. プログラムの実行
input.txtに入力される値,main.cppにその入力から所望の出力を得るプログラムを書きプログラムを実行します.
input.txtから入力を得るにはmain関数の冒頭に以下の記述を行ってください.
freopen("input.txt", "r", stdin);
また,output.txtに出力したい場合は同様に以下の記述を行ってください.
freopen("output.txt", "w", stdout);
macOSでコンパイルを行う場合は以下のように書くこともできます.
#ifdef __APPLE__
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
以下にinput.txtとmain.cppのサンプルプログラムを置いておきます.
3
1 2 3
#include <bits/stdc++.h>
using namespace std;
int main()
{
freopen("input.txt", "r", stdin); // Input Redirection
freopen("output.txt", "w", stdout); // Output Redirection
/* if you are compiling on macOS, you can instead write as follows
#ifdef __APPLE__
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
*/
// n個の整数を読み取りその合計を出力
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
cout << accumulate(a.begin(), a.end(), 0) << endl;
return 0;
}
4. 実行結果の確認
プログラムの出力内容はoutput.txtに記録されます.
以下のoutput.txtは入力ファイルであるinput.txtに対してmain.cppを実行した結果です.
6
5. 終わりに
これでXcodeでリダイレクトができるようになったと思います.
また,main.cpp内のbits/stdc++.hが気になった方はこちらの記事を参考にしてください.
Xcodeでbits/stdc++.hをインクルード
