Advertisement
PIBogdanov

Create a text file with timestamp

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