【问题标题】:How can I name the text file I create after the current date/time如何在当前日期/时间之后命名我创建的文本文件
【发布时间】:2014-03-16 03:53:32
【问题描述】:

首先,我对 X++ 的了解很少,我只需要编辑给定的代码。 我有一个 C++ 程序,它创建一个文本文件并在其中存储数据。现在程序正在使用:

outfile.open("C:/Users/Admin/Documents/MATLAB/datafile.txt", std::ios::app);

但我需要更改此代码,因此每次运行此代码时,它都会创建一个新文件名。我的建议是以某种方式将时间/日期合并为文件名,但我不确定如何执行此操作。我已经尝试过研究,看起来使用time_t 是可行的方法,但我不确定如何在我的情况下使用它。

是否可以将时间/日期保存为变量,然后使用:

outfile.open("C:/Users/td954/Documents/MATLAB/<DEFINED VARIABLE>", std::ios::app);
//                                            ^^^^^^^^^^^^^^^^^^

如果是这样,我该怎么做?

谢谢大家

【问题讨论】:

    标签: c++ datetime time text-files time-t


    【解决方案1】:

    代码如下:

    time_t currentTime = time(0);
    tm* currentDate = localtime(&currentTime);
    char filename[256] = {0};
    
    strcpy(filename, "C:/Users/Admin/Documents/MATLAB/datafile");
    strcat(filename, fmt("-%d-%d-%d@%d.%d.%d.txt",
           currentDate->tm_hour, currentDate->tm_min, currentDate->tm_sec,
           currentDate->tm_mday, currentDate->tm_mon+1,
           currentDate->tm_year+1900).c_str());
    
    outfile.open(filename, std::ios::app);
    

    tm* 和 time_t 在 ctime 标头中。 fmt 只是像 sprintf 一样的函数,它格式化字符串。实现(不是我的,在 stackoverflow IIRC 上找到):

    #include <cstdarg>
    std::string fmt(const std::string& fmt, ...) {
        int size = 200;
        std::string str;
        va_list ap;
        while (1) {
            str.resize(size);
            va_start(ap, fmt);
            int n = vsnprintf((char*)str.c_str(), size, fmt.c_str(), ap);
            va_end(ap);
            if (n > -1 && n < size) {
                str.resize(n);
                return str;
            }
            if (n > -1)
                size = n + 1;
            else
                size *= 2;
        }
        return str;
    }
    

    【讨论】:

    • 我已尝试实现您建议的代码,但我收到错误“fmt”:未找到标识符。是否有我需要为该功能包含的标题
    • 看整个帖子...我已经给了你 fmt 的代码。这是第二个代码。
    • 复制第二个代码(fmt函数定义),然后放#include ,然后在它下面放第一个代码。
    【解决方案2】:

    当然,你可以这样做:

    // Calculate the path
    time_t current_time = time(nullptr);
    std::ostringstream path_out(prefix);
    path_out << "-" < < current_time << ".txt";
    std::string path = path_out.str();
    
    // Open a file with the specified path.
    std::ofstream out(path.c_str(), std::ios::app);
    
    // do stuff with "out"
    

    话虽如此,如果您尝试使用文件名的时间来创建临时文件,那么您正在寻找的解决方案可能是特定于平台的。在基于 UNIX 的系统上,mkstemp 是创建临时文件的首选方式(我不确定在 Windows 上执行此操作的首选方式是什么,但谁在乎 ;))。

    【讨论】:

    • 行内:std::ostringstream path_out(prefix);前缀是什么意思,我得到了未定义的标识符。谢谢
    • 我假设您有一个名为“prefix”的字符串变量,其中包含“C:\...”(将“...”替换为该路径的其余部分)。
    【解决方案3】:

    您可以使用通过 C++11 的日期和时间工具提供的时间戳。特别是,std::chrono 命名空间的now() 函数将返回您想要的:

    #include <chrono>
    
    std::ostringstream oss;
    oss << "myfile" << std::chrono::system_clock::now() << ".txt";
    //                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    
    std::ofstream out(oss.str(), std::ios_base::app);
    

    【讨论】:

      【解决方案4】:
      #include <ctime>
      #include <stdexcept>
      #include <sstream>
      
      std::string getTimestampedFilename(const std::string &basePathname) {
         std::ostringstream filename;
         filename << basePathname << '.' << static_cast<unsigned long>(::time(0));
         return filename.str();
      }
      

      现在,您可以在其他地方使用它...

      template<class T>
      void writeToFile(const std::string &basePathname, T data) {
          std::string filename = getTimestampedFilename(basePathname);
          std::ofstream outfile(filename.c_str());
      
          if (outfile) {
             outfile << data;
          }
          else {
             throw std::runtime_error("Cannot open '" + filename + "' for writing.");
          }
      }
      

      【讨论】:

      • 使用这种方法的另一个好处是您使用了一个可重用的函数,该函数清楚地说明了它在做什么。这应该是您编写的任何软件的目标。
      【解决方案5】:

      试试这样的:

      std::time_t t = std::time(NULL);
      std::tm *ptm = std::localtime(&t);
      std::stringstream ss;
      ss << ptm->tm_year+1900 << std::setw(2) << ptm->tm_mon+1 << ptm->tm_mday << ptm->tm_hour+1 << ptm->tm_min+1 << ptm->tm_sec+1;
      outfile.open(("C:/Users/Admin/Documents/MATLAB/datafile_"+ss.str()+".txt").c_str(), std::ios::app);
      

      【讨论】:

        猜你喜欢
        • 2013-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多