看板 C_and_CPP 關於我們 聯絡資訊
問題(Question): 我的問題是這樣的 如果今天我在 a.out後面餵了多個參數及檔案 ex: ./a.out p1, p2, p3, txt1, txt2, txt3 .... 因為我在input進來之前並沒有辦法知道會餵了多少個參數及檔案 所以我想請問 是否可以宣告一個檔案指摽的陣列 如: FILE *stream [512] , 這樣子來做 ...... *stream[id] = fopen("argv[id]", "r"); 不過我在fopen的時候卻會發生complier不過的情形 想請問大家問題是出在哪裡 還是說有別的做法也請指教~ 謝謝! 以下是code #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <math.h> FILE *stream [512] ; void *runner(void* id); int main(int argc, char *argv[]){ pthread_t pro[512]; pthread_attr_t attr[512]; int i; for (i=5; i<=7; i++){ pthread_attr_init(&attr[i]); pthread_create(&pro[i], &attr[i], runner, (void*) i); } for (i=5; i<=7; i++){ pthread_join(pro[i], NULL); } } void *runner(void* id){ (int*)id; printf ("%d ", id); stream[id] = fopen("argv[id]", "r"); ; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.243.144.23
james732:compiler不過?請貼上你的錯誤訊息 01/02 17:31
neville123:39 C:\Documents and Settings\christian\桌面\test 01/02 17:34
neville123:.cpp invalid types `FILE*[512][void*]' for array 01/02 17:34
neville123:subscript 01/02 17:35
wawi:改成 stream[id] = fopen(argv[id], "r"); 01/02 21:34
neville123:錯誤訊息還是相同耶..@@ 01/03 00:35
wawi:貼一下code 01/03 00:39
VictorTom:既然是命令列代參數, argc可以知道參數數量, 雖然這並不 01/03 01:20
VictorTom:能明確知道檔案數, 但你可以先跑迴圈把參數parse一遍算 01/03 01:20
VictorTom:完, 最後用malloc動態要FILE*出來; 當然如果可以賭一個 01/03 01:21
VictorTom:上限, 像你那樣開固定的array也可以, 有錯應該單純是你 01/03 01:22
VictorTom:code寫錯了, 比如你 *stream[id] 那行看起來就是錯的, 01/03 01:23
VictorTom:應該不要 * 才對; 進一步修正就像1F j大說的貼code吧:) 01/03 01:23
neville123:好的!! 晚點貼上來, 謝謝大家 :) 01/03 13:23
※ 編輯: neville123 來自: 111.243.144.218 (01/03 22:56) ※ 編輯: neville123 來自: 111.243.144.218 (01/03 22:56)
VictorTom:main裡用pthread小弟不熟, 只是loop都只有5~7, 為什麼 01/03 23:11
VictorTom:array要開到512個這麼多啊?_? 01/03 23:11
VictorTom:runner() function裡錯的滿嚴重的, 比如第一行 01/03 23:12
VictorTom:(int*)id; <- 你知道這一行最後會發生什麼事嗎?? 01/03 23:12
VictorTom:想從argv[]拿出檔名那邊的fopen(), 請再仔細想想這樣寫 01/03 23:13
VictorTom:fopen到底會嘗試開啟哪一個檔名; 仔細想想需不需要"". 01/03 23:14
VictorTom:最後, runner()好像應該回傳個void*出去喔....:) 01/03 23:16
VictorTom:er~~仔細想想, 你這樣子永遠只會以argv[5~7]嘗試當作檔 01/03 23:17
VictorTom:名來開檔, 好像沒辦法如你所想的依照參數數量開啟任意檔 01/03 23:18
VictorTom:案數說; 至於fopen檔案不過, 純粹是id的型態不對. 01/03 23:19
neville123:因為我自己在try就先把範圍寫死了 01/03 23:48
neville123:謝謝 我自己在試試看好了 :) 01/03 23:48
tropical72:#1D8UdSCG 有回文了,可以參考一下 01/03 23:50
neville123:(int*)id 不是強制轉型成int的嗎?? 01/03 23:52
neville123:謝謝 01/03 23:54
VictorTom:它是強制轉型, 但是是轉型成int*, 還有, 只在那個地方轉 01/04 00:25
VictorTom:並不是你 (int*)id; 寫一行, 後面id就自動變成新型態了, 01/04 00:26
VictorTom:是你每次要把id以新型態解讀時, 都要再做強轉型一次; 不 01/04 00:26
VictorTom:然就是宣告一個新的變數, 直接儲存轉型後的結果. 01/04 00:27