Advertisement
PIBogdanov

Creating a text file and adding a timestamp

Feb 21st, 2023
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <chrono>
  5.  
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10.     // create a time stamp string
  11.     auto now = chrono::system_clock::now();
  12.  
  13.     time_t time = chrono::system_clock::to_time_t(now);
  14.  
  15.     string timestamp = to_string(time);
  16.  
  17.     // create a file stream object and open a file with a timestamp in its name
  18.     ofstream outfile("x64/example_" + timestamp + ".txt");
  19.  
  20.     // check if the file was opened successfully
  21.     if ( !(outfile.is_open()) )
  22.     {
  23.         cout << "Failed to open the file." << "\n";
  24.  
  25.         return 1;
  26.     }
  27.  
  28.     // write some text to the file
  29.     outfile << "This is an example text file created with C++." << "\n";
  30.  
  31.     // close the file stream
  32.     outfile.close();
  33.  
  34.     return 0;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement