Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

c - Why FILE * does not store the address of an open 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
", fp);
    FILE *newfp = Openfile(filename, openmode, fp);
    printf("FP(after call function): %p
NEWFP: %p
", fp, newfp);                  

    return 0;
}

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

}

Result:

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...