0

I'm currently writing on a File_Handler, a class that simplifys operations on files which I need for my program.

My question is which way would be best to save the file in my class. Would it be best to save the path of my file as a std::string and reopen it in every function that uses the file, or would it be best if I'd save the actual std::fstream variable. Since it's a File_Handler it'll perfom a lot of operations on the same file in a lot of different functions. Down below is a quick demonstration of both ways:

Opt. 1 would look like this:

class File_Handler
{
public:
    void foo() 
    {
        std::fstream f(m_path);
        //operations with 'f'..
    }
private:
    std::string m_path; //save path of file here
}

and Opt. 2 would look like this:

class File_Handler
{
public:
    void foo()
    {
        //operations on already opened 'm_file'
    }
private:
    std::fstream m_file; //save actual file
}

Which version is quicker, saver and over all better?

Or is there even a better way? (For example copy the whole file into a vector and after every operation on the vector copy vector to file?..)

I'd appreciate you help.

Aemmel
  • 122
  • 2
  • 6
  • The second version may make your compiler choke if a copy is made of `File_Handler`. For example: `File_Handler f; File_Handler f2 = f;` Try that with the second version. – PaulMcKenzie Jul 29 '15 at 22:46
  • @PaulMcKenzie He could `delete` the copy constructor to alleviate that. – Colin Basnett Jul 29 '15 at 22:52
  • @PaulMcKenzie, ok, but as cmbasnett stated, I could get rid of that problem. So what would be the best decision here? – Aemmel Jul 30 '15 at 00:11

0 Answers0