2012-04-06 3 views
-2

私はいくつかの "フレーバーテキスト"を使って同じ方法で3つのファイルを開く必要があるので、宿題に取り組んでおり、関数としてFILE * 。関数内からファイルを開く

enum {IN, STAT, REPRINT} FNAMES; 
#define FNAME_MAX 256 

int main(void) 
{ 
    FILE *in, *stat, *reprint; 
    char fnames[3][FNAME_MAX]; // store actual file names input by user 
    char format[11];   // format identifier used in scanf for file names 


    in = stat = reprint = NULL; // TODO: Check necessity 

    buildFormat(format); // this translates FNAME_MAX into the string "%256s[^\n]" 

    // TODO: Find out why this cannot be put into a function! 
    // open the input file 
    while (in == NULL) 
    { 
    // get input file name 
    getFileName(format, fnames[IN]); // simply prompts for a file name/path 

    // open the input file for reading 
    in = fopen(fnames[IN], "r"); 

    // make sure it opened 
    if (in == NULL) 
     printf("%s did not open, please check spelling/path.\n\n", fnames[IN]); 
    else 
     printf("%s was opened successfully.\n\n", fnames[IN]); 
    } 
    return 0; 
} 

はどう機能しませんが、このです:私はそれがこのように正常に動作するようになった私がメインに戻った場合、私はそれが正常に動作機能で操作を読んでファイルを置くが、場合

void openFile(FILE *in, char *format, char *fname, char *openFor) 
{ 
    // TODO: Find out why this cannot be put into a function! 
    // open the input file 
    while (in == NULL) 
    { 
    // get input file name 
    getFileName(format, fname); // simply prompts for a file name/path 

    // open the input file for reading 
    in = fopen(fname, openFor); 

    // make sure it opened 
    if (in == NULL) 
     printf("%s did not open, please check spelling/path.\n\n", fname); 
    else 
     printf("%s was opened successfully.\n\n", fname); 
    } 
} 

私が送信したファイルポインタを使用しようとすると動作しません。

+0

http://c-faq.com/ptrs/passptrinit.html – cnicutar

+0

ポインタへのポインタ、あなたはなぜ*値を返すのですか?ティvoidを返すと宣言した関数ですか? – tbert

答えて

2

openFileFILE *を返すようにします。あなたの入力引数からFILE *inを取り除く。 FILE *inをローカル変数として宣言し、完了したらその値を返します。

openFileが返された後に使用する必要がない限り、fnameをローカルで宣言したいと思うかもしれません。

+0

ありがとうございました。私は、後で使うためにファイル名を保持する必要がありますが、チップのおかげで。 –

0

C関数は引数を変更しないので、関数にFILE *を変更させたい場合は、openFile(FILE ** in ...)のようにレベルをindirectionに追加し、&で呼び出します。醜いですが、もっと一般的な習慣は、他の答えが言っているように、ポインタを返すことです。

私の誤りのあるメモリ回路が正しい言葉を使用していることを確認しながらユーモラスな引用が見つかりました。別のレベルのインダイレクションによって解決されました」--David Wheeler

+0

もう一度ありがとうございます。私は、FILE型のchar *、int *などのように動作するポインタを送信していたので、明らかにそうではありませんでした。 私はファイルを返すことによって正常に動作するようになった* –

関連する問題