如何在C 中读取具有前缀和时间戳为文件名的文件

How to read files which has a prefix and a timestamp as a file name in c++

本文关键字:时间戳 文件名 文件 前缀 读取      更新时间:2023-10-16

通常,当文件名是" example.txt"时,我可以使用以下代码从文件中读取。

string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << 'n';
    }
    myfile.close();
  }
  else cout << "Unable to open file"; 

但是,当文件名为示例_201703140.txt或exampe_201703142.txt时,我如何使用相同的程序读取文件。(我们只说此文件是该前缀位置中唯一的文件。换句话说,该位置可以具有示例_201703031140.txt或exampem_201703031142.txt,而不是两者)

为了进一步澄清问题,如何编写一个可以读取动态更改文件名的程序?例如,想象一个我必须写入文件的场景,该方案命名为example_timestamp并从单独的模块读取该文件(该文件无法访问完整文件名,但知道它具有前缀"示例",然后是时间戳。)

更新:您不知道时间戳是什么,您只知道这是时间戳。

我想你想要这样的东西:

DIR* dirp = opendir("the dir name");
while(struct dirent* e = readdir(dirp)){
     if e->d_name matches the pattern you wanted{
           do whatever you want with this file.
     }
}

首先,您需要创建文件名的前缀或后缀,例如创建日期时间格式:

char buffer[128];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 80, format.c_str(), timeinfo);
out << buffer;

之后,您构建了文件名来验证并使用它。

在链接链接中显示您如何创建图书馆以创建动态名称并重复使用它们:

https://github.com/jorgemedra/apilogcpp/blob/master/master/apilogcpp/uipilog/logmanager.cpp