[C++] 利用 cin 和 cout 導向檔案輸入輸出

C++ 讀寫檔,可能會使用命令列引數給予檔名,也就是 argv 變數:
int main(int argc, char **argv)
{
     ifstream inputFile(argv[1]);
     ofstream outputFile(argv[2]);
     // processing ...
   
     outputFile.close();
     inputFile.close();
     return 0;
}
而我認為良好的習慣是:採用 cin 和 cout 來做檔案輸出入導向,命令列引數 argv 則用來給予設定。
什麼意思呢?
以下舉個例子。

假設我們要寫一個程式,讀入檔案並將檔案內容加上行號。
我會這樣寫:
// main.cpp
int main(int argc, char** argv)
{
      if(argc != 2) 
      {
             cerr << " Argument error." << endl;
             exit(-1);
      }     

     string line;
     int lineNum = 0;
     while(getline(cin, line))
     {
           if(strcmp(argv[1], "hex") == 0)
                     cout << std::hex << lineNum << " " << line << endl;
           else if(strcmp(argv[1], "dec") == 0)
                     cout << std::dec << lineNum << " " << line << endl;
          else   cout << line << endl;

          lineNum++;
    }

    return 0;
}

執行方法:
將 input.txt 當作輸入,直接輸出結果在螢幕上:(假設主程式名稱為 main )
./main hex < input.txt
將 input.txt 當作輸入,將結果輸出在 output.txt 內:
./main hex < input.txt > output.txt

上述程式碼,argv 用來設定行數格式(16進位或10進位),檔案 IO 採用資料流重導向。
這種 coding style 的優點是,可用其他程式的輸出,當作我們設計的程式輸入,例如用 pipe 管線的執行方法,把程式 A 的執行結果餵給程式 B:

程式 A | 程式 B

Reference
資料流重導向
管線

留言