tags:

views:

76

answers:

4

I'm building a program that has several functions that need to read data from a file. Since the functions are used fairly frequently, opening and closing the file for each call would be too time consuming, so my plan was to make the FILE* object global, and have the file open the whole duration of the program. Apparently, though, it's not possible, since this:

#include <fstream>
FILE * yhtit;
yhtit = fopen("thefile.txt","r");
int main() {
return 0; }

gives error: main.cpp|54|error: expected constructor, destructor, or type conversion before ‘=’ token|

What's the best way to keep a file open the whole duration of the program, without having to separately pass the FILE* object to every function that needs it?

+2  A: 

You almost got it right. Try this:

#include <fstream>

FILE * yhtit;

int main() {
    yhtit = fopen("thefile.txt","r");

    //Do your thing here.

    fclose(yhtit);
    return 0;
}
Spidey
-1 for global variable solution.
Dacav
To be fair, a global variable solution was what the question was asking for.
wrosecrans
+1  A: 
#include <fstream>
FILE * yhtit = fopen("thefile.txt","r");
int main() {
  return 0; }
SCFrench
-1 for global variable solution.
Dacav
@Dacav: The global variable is part of the question. SCFrench didn't introduce it in his solution, he just fixed its initialization.
Charles Bailey
+3  A: 
John Kugelman
Yes I agree that it's a questionable practice and fixing that is on my todo-list, but at the moment I'm just trying to make this thing work.
tsiki
@tziki: it's not a big deal passing one more argument into your parameter list. Placing global variable is really a bad idea and will give you a hard time when you'll need to modify the source code in the future (expecially with multithreading, also global variables are difficult to trace when you analyze a program!)
Dacav
A: 

You can maintain the File * variable in a structure and make that structure accessible from any function.

typedef struct 
{
FILE *fp;
//other members can also be part of this structure.
}myData;

appInit(myData *ptr)
{
ptr->fp = fopen(<>,<>);
//Initialise other variables also

return;
}

appDeInit(myData *ptr)
{

 fclose(ptr->fp);
}


main()
{
myData *ptr= malloc(sizeof(myData));
appInit(ptr);
//Play with ptr in all your function calls
foo(ptr);


appDeInit(myData);
}
Praveen S