C 函数内的文件指针更改 [英] File pointer change inside a C function

查看:52
本文介绍了C 函数内的文件指针更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一下为什么可以在C函数中改变file的指针值而不传递引用,我的意思是:

I'd like to ask why is it possible to change the pointer value of file in C function without passing reference to it, what I mean is:

void fun(FILE *f)
{
    fclose(f);
    f = fopen("newfile", "r");
}

int main(void)
{
    FILE *old = fopen("file", "r");
    char *msg = (char*)malloc(sizeof(char) * 100);
    fun(old);
    fscanf(old, "%s", msg);
    printf("%s", msg);
    free(msg);
    return 0;
}

谁能给我解释一下?我认为正在复制指针,所以我预计会收到有关关闭文件的错误.令人惊讶的是我没有得到它.

Can anyone explain it to me? I was thought that pointers are being copied so I expected to get an error about closed file. Surprisingly I didn't get it.

推荐答案

C 中的参数按值传递,这意味着它们被复制.所以函数永远不会有原始值,只是复制,修改副本当然不会修改原始值.

Arguments in C is passed by value, and that means they are copied. So the functions never have the original values, just copies, and modifying a copy will of course not modify the original.

您可以使用指针模拟通过引用传递,并且在通过引用传递指针的情况下,您当然必须将指针传递给该指针(通过使用地址运算符<代码>&).

You can emulate pass by reference by using pointers, and in the case of passing a pointer by reference you of course have to pass a pointer to the pointer (by using the address-of operator &).

void fun(FILE **f)
{
    fclose(*f);
    *f = fopen("newfile", "r");
}

...

fun(&old);

这篇关于C 函数内的文件指针更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆