本地时间替代方案不会覆盖提供的结构
本质上,我想做的是检查文件的上次访问时间并将其与字符串进行比较。这是相关的块:
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<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
是用户输入的字符串。
问题:当“问题”行运行时,节点上的节点是垃圾向量。我想知道是否可以完成这项任务而不将节点变成垃圾。
由于这是家庭作业,并且正如您可能会告诉我的那样,我不习惯 C++,因此如果朝着正确的方向坚定地推动,将会得到“接受”。
谢谢。
Essentially, what I'm trying to do is to check the last access time of a file and compare it with a string. Here's the relevant 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
is a vector of file paths; I'm not sure if it's relevant but I'll include the code that I'm using to set 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);
Where searchPath
is a user-inputted string.
The problem: when the 'problem' line is run, from there on nodes
is a vector of garbage. I'm wondering if I can accomplish this task without turning nodes
into garbage.
Since this is homework, and as you can probably tell I'm not used to C++, a solid push in the right direction will be given the 'accept'.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它与您的
strftime
调用无关,但与以下事实有关:(来自 此处):由于您只是推送一个指向可能被后续调用 readdir 覆盖的数据的字符指针,因此您很可能会得到垃圾。
您可以通过使用 C 字符串的副本来修复它,例如:
并且,如果您的实现没有
strdup
(它不是标准的一部分) ,你可以使用我的(发现此处)。It has nothing to do with your
strftime
call but with the fact that (from here):Since you're simply pushing a character pointer that points to data that may be overwritten by subsequent calls to
readdir
, you may well end up with garbage.You can probably fix it by using a copy of the C string with something like:
And, if your implementation doesn't have a
strdup
(it's not part of the standard), you can use mine (found here).您在向量中存储的指针立即变得无效(
cur
在下一次readdir
或closedir
调用之前一直有效)。最好的解决方法是编写您想要的代码 - 将nodes
设为string
的向量。最简单的修复:You're storing pointers in the vector that immediately become invalid (
cur
is valid until the nextreaddir
orclosedir
call). The best fix is to code what you want -- makenodes
a vector ofstring
s. The easiest fix: