Writing a Log file in c/c++

前端 未结 5 1756
无人共我
无人共我 2020-12-13 20:49

I want to write a log file in c++. I am processing certain things and thus i need to maintain a log of the properties of the things that i process so that i could revert bac

5条回答
  •  有刺的猬
    2020-12-13 20:58

    The standard method of logging (in my experience) is to use either the stdout or stderr streams. In C++ to use these you would need to include iostream, and use as below:

    #include 
    
    int main(int argc, char* argv[])
    {
      using std::cout;
      using std::cerr;
      using std::endl;
    
      cout << "Output message" << endl;
      cerr << "Error message" << endl;
    }
    

    This, however, only achieves printing to those outputs, which usually end up at a terminal. If you want to use these standard stream methods (which are quite readable) to output to a file, then you have to redirect your output somehow. One way of doing this is by using the freopen function, provided by cstdio. What this does is open a file, and moves a given stream to that file. See here for documentation. An example would be:

    #include 
    #include 
    
    int main(int argc, char* argv[])
    {
      using namespace std;
      freopen( "output.txt", "w", stdout );
      freopen( "error.txt", "w", stderr );
    
      cout << "Output message" << endl;
      cerr << "Error message" << endl;
    }
    

    (I've changed to using namespace std; there just for conciseness.)

    You're moving the standard output stream stdout (which is used by cout) to output.txt (in write mode), and you're moving stderr (which is used by cerr) to error.txt also in write mode.

    Hopefully this does the trick.

提交回复
热议问题