2009-10-29 39 views
2

現在我對每個人都有一個hw問題......我一直在盯着這個幾天的修補和玩耍但即便如此我結束了錯誤的負載...在c中改變一個程序,所以它需要一個可選的命令行參數* infile *

我試圖做的是採取下面的程序,並改變它,以便它有一個可選的命令行參數INFILE。如果infile中給定,然後複製infile中到標準輸出,否則如之前標準輸入複製到標準輸出。

關於這一點的技巧是解決方案必須在兩種情況下都使用原始複製循環(第9-11行)。一個只能插入代碼,而不能更改任何現有的代碼。任何幫助都會很棒。謝謝。

/* $begin cpfile */ 
include "csapp.h" 
int main(int argc, char **argv) 
{ 
    int n; 
    rio_t rio; 
    char buf[MAXLINE]; 

    Rio_readinitb(&rio, STDIN_FILENO);     //line 9 
    while((n = Rio_readlineb(&rio, buf, MAXLINE)) != 0) //line 10 
     Rio_writen(STDOUT_FILENO, buf, n);    //line 11 
     /* $end cpfile */ 
     exit(0); 
     /* $begin cpfile */ 
    } 
/* $end cpfile */ 
+0

聽起來像功課,我 – jitter 2009-10-29 08:11:21

+2

它......像我上面說的... – 2009-10-29 08:18:34

+0

@jitter:..在這種情況下,它顯然功課。這個問題本身帶着響亮的迴響尖叫着。他可能不知道標籤存在。 – 2009-10-29 08:53:55

回答

1

可以插入dup2行前9 - 11,似乎你不需要對線路9變更碼 - 這是一個例子。

#include <unistd.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <stdio.h> 
#include <fcntl.h> 


int main(int argc, char *argv[]) 
{ 

    int file_handle; 
    int dup2_res; 
    if (argc == 2) { 
     file_handle = open(argv[1], O_RDONLY); 
     dup2_res = dup2 (file_handle, STDIN_FILENO); 
    } 

    char buffer[100]; 
    ssize_t read_bytes = 1; 
    while (read_bytes) 
    { 
     read_bytes = read(STDIN_FILENO, &buffer, sizeof(buffer)); 
     buffer[read_bytes] = 0; 
     printf("%s", buffer); 
    } 
    close(file_handle); 

    return 0; 
} 
+0

它在談論使用Dup2 ... – 2009-10-29 08:50:08

+0

我認爲你需要明確dup2()不是ANSI C,並且OP沒有指定平臺,所以它不一定是猶太教。 – qrdl 2009-10-29 08:53:30

+0

正確,但dup2()是POSIX。但是當然,這取決於平臺。 – BobbyShaftoe 2009-10-29 11:22:59

5

C程序打通兩個參數命令行參數main(),傳統上被稱爲argcargv(分別用於參數計數和參數向量,)。

參數不是「命名」的任何東西,它們只是字符串。

一個解決方案,你可以看看這樣的:

#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 

int main(int argc, char *argv[]) 
{ 
    int fileno; 
    /* ... your definitions should remain here, too */ 

    if(argc > 1) 
    { 
     /* Assume first argument is filename, and open it. */ 
     fileno = open(argv[1], O_RDONLY); 
     if(fileno < 0) 
     { 
     printf("Unable to open file, aborting\n"); 
     return 1; 
     } 
    } 
    else 
     fileno = STDIN_FILENO; 

    /* ... your code goes here ... */ 
} 

那麼你當然需要調用改變Rio_readinitb()使用fileno變量的文件描述符。

如果你從字面上無法改變這一行,不管是什麼原因?我想你可以使用預處理,使符號計算爲新的變量名:

#undef STDIN_FILENO 
#define STDIN_FILENO fileno 

這當然不是非常漂亮,但應該工作。

請確保您將之後的fileno = STDIN_FILENO;行預處理器宏

+1

這將需要更改無法更改的行。 – qrdl 2009-10-29 08:23:08

+1

@qrdl:對,謝謝。我添加了預處理器解決方法。 – unwind 2009-10-29 08:29:36

+0

但是,如果您在調用'Rio_readinitb(&rio,STDIN_FILENO)'時不能更改'STDIN_FILENO';''你總是會從標準輸入讀取。同樣,循環中的調用'exit(0);'是虛假的。 這項任務沒有多大意義。 – Wernsey 2009-10-29 08:32:05

1

如果STDIN_FILENO不能被重新分配,這聽起來像freopen()任務:

freopen(argv[1], "r", stdin); 
相關問題