おいも貴婦人ブログ

生物系博士課程満期退学をしたAIエンジニアのブログ。

構造体内で定義されているファイルポインタ。

ヘッダファイルに構造体を宣言し定義し、以下のソースのように、tmp1.cで読み込んだファイルポインタがtmp2.cでは消えている…。
tmp1.c

#include <stdio.h>
#include <stdlib.h>

#include "t_struct.h"

void tmp2(void);

int main(void){
    if((t_s.infile=fopen("tmp1.c","r"))==NULL){
        fprintf(stderr,"ERROR reading file.\n");
        exit(1);
    }
    tmp2();
    return 0;
}

tmp2.c

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

void tmp2(void){
    char buf[256];
    if(t_s.infile==NULL)
        fprintf(stdout,"t_s.infile is NULL\n");

    while((fgets(buf,256,t_s.infile))!=NULL)
        fprintf(stdout,"%s",buf);
}

s_struct.h

#ifndef _T_STRUCT_H
#define _T_STRUCT_H
struct tmp_struct{
    FILE *infile;
};static struct tmp_struct t_s;
#endif

コンパイル

$gcc tmp1.c tmp2.c -Wall

結果

t_s.infile is NULL
Segmentation fault (core dumped)

解決法

s_struct.h

#ifndef _T_STRUCT_H
#define _T_STRUCT_H
struct tmp_struct{
    FILE *infile;
};extern struct tmp_struct t_s;
struct tmp_struct t_s;
#endif

参考URL:http://homepage2.nifty.com/well/Header.html