2011-05-04 140 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

相关问题