不会覆盖提供的结构的本地时间替代项

localtime alternative that won't overwrite the supplied struct

本文关键字:时间 结构 覆盖      更新时间:2023-10-16

本质上,我要做的是检查文件的最后访问时间,并将其与字符串进行比较。这是相关的区块:

struct stat file;
char timeStr[ 100 ];
stat(nodes.at(0), &file);
strftime(timeStr, 100, "%H:%M:%S-%m/%d/%y", localtime(&file.st_atime)); /* problem */

CCD_ 1是文件路径的向量;我不确定它是否相关,但我会包括我用来设置nodes:的代码

vector<char*> nodes;
DIR *dir;
struct dirent *cur
if((dir = opendir(searchPath.c_str())) == NULL) {
    cout << "Error opening search path. Are you sure '" 
        << searchPath.c_str() << "' is a valid search path?" << endl;
    return 0;
}
while((cur = readdir(dir)) != NULL) {
    if(string(cur->d_name) == "." || string(cur->d_name) == "..") continue;
    nodes.push_back(cur->d_name);
}
closedir(dir);

其中,searchPath是用户输入的字符串。

问题是:当"problem"行运行时,nodes上会出现一个垃圾向量。我想知道我是否可以在不把nodes变成垃圾的情况下完成这项任务。

既然这是家庭作业,而且你可能知道我不习惯C++,那么朝着正确的方向努力就会得到"接受"。

谢谢。

它与strftime调用无关,而是与以下事实有关(从这里开始):

readdir()返回的指针指向的数据可能会被同一目录流上另一个对readdir(()的调用所覆盖。

由于您只是简单地推送一个字符指针,该指针指向可能被随后对readdir的调用覆盖的数据,因此很可能会以垃圾告终。

您可能可以通过使用C字符串的副本来修复它,比如:

nodes.push_back (strdup (cur->d_name)); // plus error handling if need be.

而且,如果您的实现没有strdup(它不是标准的一部分),您可以使用我的(在这里找到)。

nodes.push_back(cur->d_name);

您在向量中存储的指针会立即变为无效(cur在下一次nodes0或closedir调用之前一直有效)。最好的解决方案是编写您想要的代码——使nodes成为strings的向量。最简单的解决方案:

nodes.push_back(strdup(cur->d_name));