1

I am suppose to pass stream, which is a pointer, by reference. So I am passing this as a pointer to a pointer. Can someone please verify my code?

    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;
}

No output received.

4

3 回答 3

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 回答
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 回答
1

代替

stream = fopen("names.txt", "r");

*stream = fopen("names.txt", "r");

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

printf("LINES: %d\n",scan(&stream));
于 2015-03-02T07:11:13.703 回答