1

ポインタであるストリームを参照渡しするとします。したがって、これをポインターへのポインターとして渡します。誰かが私のコードを確認してもらえますか?

    int main(int argc, char** argv)
{
    FILE *stream;

    printf("LINES: %d\n",scan(stream));
}

int scan(FILE *(*stream))
{
    stream = fopen("names.txt", "r");

    int ch = 0, lines=0;

    while (!feof(*stream))
    {
        ch = fgetc(*stream);
        if (ch == '\n')
        {
            lines++;
        }
    }
    fclose(*stream);
    return lines;
}

出力がありません。

4

3 に答える 3

2

使用する

int scan(FILE **stream) //no need for brackets
{
    *stream = fopen("names.txt", "r"); //* is for dereferencing

    if(*stream==NULL) // Checking the return value of fopen
    {
        printf("An error occured when opening 'names.txt'");
        return -1;
    }

    int ch = 0, lines=0;

    while ((ch = fgetc(*stream))!=EOF) //while(!feof) is wrong
    {

        if (ch == '\n')
        {
            lines++;
        }
    }
    fclose(*stream); // Close the FILE stream after use
    return lines;
}

int main(void)
{
    FILE *stream;

    printf("LINES: %d\n",scan(&stream)); //Pass address of `stream`. The address is of type `FILE**`
}
于 2015-03-02T07:13:08.707 に答える
2

コードに設計上の問題があります。正確に何を達成したいですか?

行数を数えたいだけの場合はFILE *、関数をローカルにします。

int count_lines(const char *filename)
{
    FILE *stream = fopen(filename, "r");

    int lines = 0;

    while (1) {
        int c = fgetc(stream);

        if (c == EOF) break;
        if (c == '\n') lines++;
    }
    fclose(stream);

    return lines;
}

で既に開いているファイルに対して通常のファイル操作 (読み取り、書き込み、シーク、巻き戻しなど) を実行する場合はfopen、ハンドルをFILE *次のように渡すだけです。

int fget_non_space(FILE *stream)
{
    int c;

    do {
        c = fgetc(stream);
    } while (isspace(c));

    return c;
}

その場合、 と の両方fopenfcloseこの関数の外で呼び出されます。fclose(オペレーティング システムが終了後にファイルを自動的に閉じることを確認したとしても、プログラムで呼び出す必要はありません。)

ファイル ハンドル へのポインターを渡すことはFILE **、たとえば を呼び出して、関数内でそのファイル ハンドル自体を変更する場合にのみ意味がありますfopen

int fopen_to_read(FILE **FILE pstream, const char *fn) 
{
    *pstream = fopen(fn, "r");
    return (*pstream != NULL) ? 0 : -1;        
}

その場合でも、ファイル ハンドルを返す方がよいでしょうfopen

あなたのコード例では、開いているファイルハンドルを でアクセスできるままにしてmainいますが、それを使って何もせず、閉じることさえしません。それはあなたが望むものですか?疑わしい。

于 2015-03-02T07:29:18.370 に答える