2012-01-26 38 views
1

我需要這樣做:重定向輸入和輸出文件的stdio

$ ./compiledprog.x <inputValues> outputFile 

,讓我從文件inputValues讀這對於我們的情況可能只是\n分離int值或什麼的。然後任何printf()'d進入outputFile。但是從技術角度講,這叫做什麼?我在哪裏可以找到這樣做的演示。

+0

這是由shell完成的,而不是正在執行的程序。該程序完全不瞭解這種行爲。 – 2012-01-26 23:52:55

+0

好的,這是項目的規格,它應該像shell那樣運行,但是wutdo – user1139252 2012-01-26 23:54:57

+0

當你執行'./compiledprog.x outputFile',它會自動將你的程序的'stdout'重定向到'outputFile'。你不必在你的程序中做任何事情。我誤解了什麼嗎? – 2012-01-26 23:56:06

回答

1

正如其他人所指出的那樣,它是輸入/輸出重定向。

下面是一個將標準輸入複製到標準輸出的示例程序,在您的示例中將內容從inputValues複製到outputFile。在程序中實現你想要的任何邏輯。

#include <unistd.h> 
#include <iostream> 
using std::cin; 
using std::cout; 
using std::endl; 
using std::cerr; 

#include <string> 
using std::string; 

int main(int argc, char** argv) { 
     string str; 

     // If cin is a terminal, print program usage 
     if (isatty(fileno(stdin))) { 
       cerr << "Usage: " << argv[0] << " <inputValues> outputFile" << endl; 
       return 1; 
     } 

     while(getline(cin, str)) // As noted by Seth Carnegie, could also use cin >> str; 
       cout << str << endl; 

     return 0; 
} 

注:這是快速和骯髒的代碼,它需要一個很乖的文件作爲輸入。可以添加更詳細的錯誤檢查。

+0

用法消息應該轉到'cerr',以免它們與常規輸出混淆。這就是'cerr'(和C中的'stderr')的總和。 – 2012-01-27 00:14:02

+0

@JonathanLeffler:是的,你是對的。感謝您糾正我的懶惰:)回答編輯。 – Karolos 2012-01-27 00:16:47