Advertisement
PIBogdanov

Creating a text file with a timestamp

Feb 21st, 2023
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 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.     string fileName;
  18.     getline(cin >> ws, fileName);
  19.  
  20.     // create a file stream object and open a file with a timestamp in its name
  21.     ofstream outfile("x64/" + fileName + "_" + timestamp + ".txt");
  22.  
  23.     // check if the file was opened successfully
  24.     if ( !(outfile.is_open()) )
  25.     {
  26.         cout << "Failed to open the file." << "\n";
  27.  
  28.         return 1;
  29.     }
  30.  
  31.     // write some text to the file
  32.     outfile << "This is an example text file created with C++." << "\n";
  33.  
  34.     // close the file stream
  35.     outfile.close();
  36.  
  37.     return 0;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement