2011-05-04 141 views
0

我有兩個文件:p1.c和p2.c.使用結構將一個文件導入另一個文件?

我需要使用存儲在p1.c結構中的值到p2.c中。請幫我弄清楚如何做到這一點。我應該使用extern嗎?

p1.c

typedef struct What_if 
{ 
    char price[2]; 
} what_if ; 

int main() 
{ 
    what_if what_if_var[100]; 

    file * infile; 
    infile=fopen("filepath"); 

    format_input_records(); 
} 

int format_input_records() 
{ 
    if (infile != NULL) 
    { 
     char mem_buf [500]; 

     while (fgets (mem_buf, sizeof mem_buf, infile) != NULL) 
     { 
      item = strtok(mem_buf,delims);  
      strcpy(what_if_var[line_count].price,item) ; 
      printf("\ntrans_Indicator  ==== : : %s",what_if_var[0].price); 
     } 
    } 
} 

p2.c

"what_if.h" // here i include the structure 

int main() 

{ 
    process_input_records(what_if_var); 
} 

int process_input_records(what_if *what_if_var) 
{ 
    printf("\nfund_price process_input_records ==== : : %s",what_if_var[0]->price); 

    return 0; 
} 
+1

它們都鏈接在一起,例如你想2'main's?爲什麼? – pmg 2011-05-04 17:26:20

+0

我需要從文件中讀取值並將其存儲在p1.c中的一個結構中。然後,我想從p1.c中得到這個結果結構,並存儲在另一個文件中,例如p2.c和p3.c等 – jcrshankar 2011-05-04 17:33:36

+0

嗯...... do你希望能夠將p1.c結果值保存在「某處」,然後(下週)在p2.c中使用它們?或者你更喜歡p1.c來獲得結果,並立即將它們提供給p2.c而無需保存它們?如果是第二種選擇,則不需要2個'main';你想編譯並鏈接所有的p1.c,p2.c,p3.c,...在一起。 – pmg 2011-05-04 17:55:15

回答

1

試試這個:

whatif.h:

#ifndef H_WHATIF_INCLUDED 
#define H_WHATIF_INCLUDED 

struct whatif { 
    char price[2]; 
}; 
int wi_process(struct whatif *); 

#endif 

p1.c

#include "whatif.h" 

int main(void) { 
    struct whatif whatif[100]; 
    whatif[0].price[0] = 0; 
    whatif[0].price[1] = 1; 
    whatif[1].price[0] = 42; 
    whatif[1].price[1] = 74; 
    whatif[99].price[0] = 99; 
    whatif[99].price[1] = 100; 
    wi_process(whatif); 
    return 0; 
} 

p2.c

#include <stdio.h> 
#include "whatif.h" 

int wi_process(struct whatif *arr) { 
    printf("%d => %d\n", arr[0].price[0], arr[0].price[1]); 
    printf("%d => %d\n", arr[1].price[0], arr[1].price[1]); 
    printf("%d => %d\n", arr[99].price[0], arr[99].price[1]); 
    return 3; 
} 

然後編譯和gcc

 
gcc -ansi -pedantic -Wall p1.c p2.c 
+0

謝謝pmg,我檢查了這個... – jcrshankar 2011-05-04 18:35:07

相關問題