简体   繁体   中英

sharing opened text file in different functions in C

Pointers are not my strong ability in C lang. so I might need a little help from you guys :). I want to work with my text file in different functions but i can open it in only my A() function.

#include<stdio.h>
#include<stdlib.h>

void B(){
    // I want to work with FILE.TXT in this function without openining it here.

}

void A() {
    FILE *fr;
    fr = fopen("FILE.TXT","r");

    fclose(fr);
}

int main() {
char c;
while(c!='*') {
        c = getchar();
        if(c=='A') A(); 
        if(c=='B') B();
    }
    return 0;
}

thank you guys

Just pass the FILE* around as an argument to whichever function needs to do I/O.

int main()
{
    FILE *fp = fopen("FILE.TXT", "r");
    // don't forget error checking

    A(fp);

    fclose(fp);
}

void A(FILE *fp)
{
    // whatever
}

You simply pass it on as a FILE pointer parameter to function B, like so:

void B(FILE* const f){
//do stuff with f
}

To USE a file in a function, you will need to have the FILE* object in that function. There are a few different choices, these are the most obvious ones:

  1. Open fr in main, and pass it to A() and B()
  2. Make fr a global variable, open it in A() (make sure you don't close it!), use it in B().

I would prefer option 1. Using global variables makes code less readable in general.

Note also that your code allows B() to be called before A, which would attempt to use the file before it has been opened. Assuming you don't implement option 1, your code will need to ensure that this doesn't happen (or that it is somehow handled).

There is absolutely no way the file can be opened AND CLOSED in A, and then used in B.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM