gpt4 book ai didi

c++ - 不会覆盖提供的结构的本地时间替代方案

转载 作者:太空宇宙 更新时间:2023-11-04 09:53:01 27 4
gpt4 key购买 nike

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

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 */

nodes 是文件路径的 vector ;我不确定它是否相关,但我将包括我用来设置 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 是用户输入的字符串。

问题:当“问题”行运行时,nodes 上的是一个垃圾 vector 。我想知道我是否可以在不将 nodes 变成垃圾的情况下完成这项任务。

由于这是家庭作业,而且您可能会说我不习惯 C++,因此向正确的方向坚定推进将获得“接受”。

谢谢。

最佳答案

它与您的 strftime 调用无关,但与以下事实有关(来自 here ):

The pointer returned by readdir() points to data which may be overwritten by another call to readdir() on the same directory stream.

由于您只是推送一个字符指针,该指针指向的数据可能会被后续调用 readdir 覆盖,因此您很可能会得到垃圾。

您可能可以通过使用 C 字符串的拷贝 来修复它,例如:

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

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

关于c++ - 不会覆盖提供的结构的本地时间替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8903930/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com