为什么FILE *不存储一个打开的文件的地址 [英] Why FILE * does not store the address of an open file

查看:115
本文介绍了为什么FILE *不存储一个打开的文件的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

FILE * Openfile(char *filename,char *mode, FILE *fp);

int main(){

    FILE *fp=NULL;
    char *filename = "simple_index.file";
    char *openmode = "w";

    printf("FP(before call function):%p\n", fp);
    FILE *newfp = Openfile(filename, openmode, fp);
    printf("FP(after call function): %p\nNEWFP: %p\n", fp, newfp);                  

    return 0;
}

FILE * Openfile(char *filename,char *mode, FILE *fp){
    printf((fp = fopen(filename, mode)) ? "Good opening %s file\n": "Error open %s file\n", filename);          
    return fp;

}

结果:

FP(before call function):0x0
Good opening simple_index.file file
FP(after call function): 0x0
NEWFP: 0x800bc7140

一个指针文件结构不使用函数打开呼叫 OPENFILE()功能的文件后,打开文件的地址保存。

A pointer to the file structure does not store the address of an open file after using a function to open a file in the call Openfile() function.

为什么 FP 不保存在功能使用后的状态?为什么需要备份的保存?

Why does FP not save the state after use in function? Why need back for save?

推荐答案

这是因为 C 通过使用按值的函数参数传递。

This happens because C uses pass-by-value for function argument passing.

如果你想修改作为参数传递给从函数本身的函数传递一个变量,你会需要一个指针变量传递给函数和函数里,你可以修改值由指针指向和在呼叫者,它会持续

If you want to make changes to a variable passed as an argument to a function from that function itself, you'll be needing a pointer to that variable to be passed to the function and inside the function, you can modify the value pointed by the pointer and in the caller, it will persist.

否则,得到的值从被调用函数后面,通常我们收益值,并将其分配给在调用函数的变量。

Otherwise, to get the value back from the called function, usually we return the value and assign it to the variable in the caller function.

这篇关于为什么FILE *不存储一个打开的文件的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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