开发者

Changing the value a file pointer points to inside a C function

Is it possible to change the value being pointed to by a FILE pointer inside a function in C by passing by 开发者_运维问答reference?

Here is an example to try and illustrate what I'm trying to do, I can modify the integer but not the file pointer, any ideas?

int main (void)
{
    FILE* stream;
    int a = 1;
    configure_stream(rand() % 100, &a, &stream);
    return 0;
}

void configure_stream(int value, int* modifyMe, FILE* stream)
{
    *modifyMe = rand() % 100;
    if (value > 50)
    {
        *stream = stderr;
    }
    else
    {
        *stream = stdout;
    }
}


I think you want to declare your configure_stream as follows

void configure_stream(int value, int* modifyMe, FILE** stream)
{
    *modifyMe = rand() % 100;
    if (value > 50)
    {
        *stream = stderr;
    }
    else
    {
        *stream = stdout;
    }
}

and use it with

configure_stream(rand() % 100, &a, &stream)

This gets a pointer pointing to a FILE pointer. With the pointer to the pointer you can modify the FILE pointer and without loosing it in the big jungle of memory


Try

void configure_stream(int value, int* modifyMe, FILE **stream)
                                                      ^
    *stream = stderr;

What you were trying wasn't correct:

void configure_stream(int value, int* modifyMe, FILE* stream)
    *stream  = stderr; /* Assign FILE * to FILE. */

EDIT

You should call it: configure_stream(..., &stream);


You are passing configure_stream a pointer to a FILE pointer. So the parameter should be declared as FILE **

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜