Question

I wanted to make an Attendance system which would take system date and time as file name of the file for ex: this is how normally it is

int main () {
time_t t = time(0);   // get time now
struct tm * now = localtime( & t );
cout << (now->tm_year + 1900) << '-'
     << (now->tm_mon + 1) << '-'
     <<  now->tm_mday
     << endl;
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
} 

but i want system date and time in place of example.txt i have calculated time by including ctime header file in the program above program is just example .

Was it helpful?

Solution

You can use strftime() function to format time to string,It provides much more formatting options as per your need.

int main (int argc, char *argv[])
{
     time_t t = time(0);   // get time now
     struct tm * now = localtime( & t );

     char buffer [80];
     strftime (buffer,80,"%Y-%m-%d.",now);

     std::ofstream myfile;
     myfile.open (buffer);
     if(myfile.is_open())
     {
         std::cout<<"Success"<<std::endl;
     }
     myfile.close();
     return 0;
}

OTHER TIPS

#include <algorithm>
#include <iomanip>
#include <sstream>

std::string GetCurrentTimeForFileName()
{
    auto time = std::time(nullptr);
    std::stringstream ss;
    ss << std::put_time(std::localtime(&time), "%F_%T"); // ISO 8601 without timezone information.
    auto s = ss.str();
    std::replace(s.begin(), s.end(), ':', '-');
    return s;
}

Replace std::localtime* with std::gmtime* if you work together abroad.

Usage e.g.:

#include <filesystem> // C++17
#include <fstream>
#include <string>

namespace fs = std::filesystem;

fs::path AppendTimeToFileName(const fs::path& fileName)
{
    return fileName.stem().string() + "_" + GetCurrentTimeForFileName() + fileName.extension().string();
}

int main()
{
    std::string fileName = "example.txt";
    auto filePath = fs::temp_directory_path() / AppendTimeToFileName(fileName); // e.g. MyPrettyFile_2018-06-09_01-42-00.log
    std::ofstream file(filePath, std::ios::app);
    file << "Writing this to a file.\n";
}

*See here for a thread-safe alternative of those functions.

You could try using ostringstream to create a date string (as you're doing with cout), then use it's str() member function to retrieve the corresponding date string.

You can use stringstream class for this purpose, for example:

int main (int argc, char *argv[])
{
  time_t t = time(0);   // get time now
  struct tm * now = localtime( & t );
  stringstream ss;

  ss << (now->tm_year + 1900) << '-'
     << (now->tm_mon + 1) << '-'
     <<  now->tm_mday
     << endl;

  ofstream myfile;
  myfile.open (ss.str());
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;

  return(0);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top