ifstream and ofstream or fstream using in and out

前端 未结 2 909
野的像风
野的像风 2021-02-20 04:02

When dealing with files, which of the two examples below is preferred? Does one provide better performance than the other? Is there any difference at all?

ifstr         


        
相关标签:
2条回答
  • 2021-02-20 04:46

    Performance-wise, there are probably only negligible differences in this case. At best you're saving a little memory.

    What matters is that the first case helps with the semantics: a std::fstream could be opened in input, output or both. Because of this you need to check the declaration to be sure while using std::ifstream and std::ofstream will make it clear what you're doing. The second case has more room for human error which is why it should be avoided.

    My own rule of thumb is to use a std::fstream when you need both read and write access to the file and only in this case.

    0 讨论(0)
  • 2021-02-20 04:56

    Just use the more concise form unless you need different behaviour... to do otherwise is just to create room for more errors. FWIW, when possible I prefer to scope the stream and check the open worked like this:

    if (std::ifstream input{"input_file.txt"})
        ...use input...
    else
        ...log and/or throw...
    
    0 讨论(0)
提交回复
热议问题