如何将文件属性从目录填充到结构向量中?

时间:2017-07-28 13:01:29

标签: c++ file vector struct

我是C ++的新手,我试图自己学习,所以我遇到了很多简单的问题。现在我想查看一个目录,其中包含以" .img"结尾的文件,并仅将文件名和创建时间推送到结构向量中。

如何将push_back转换为向量?是否每个结构都被推回到向量中,或者是否可能出错并覆盖之前的push_back?我不知道我是不是在想这个......

有人可以查看我的代码,如果我正确地执行此操作或我可能需要进行更改,请告诉我们吗?非常感谢你!

void filterContextByHsiTime(const char *context_path, int hsi_create_time) {

struct contextFileStruct {                                          //Define Struct containing key elements of a file
    double createTime;
    string fileName;
};
std::vector<contextFileStruct> contextVector;                       //Initialize resizable vector array of type contextFileStruct
contextFileStruct tempStruct;
_finddata_t allFiles;                                               //Structure that holds file specific elements

int findFirstContextImage = _findfirst(context_path, &allFiles);    //Int variable holding result of the findfirst function 
                                                                    //where -1 = no image fround and any other number = image found
tempStruct.fileName = allFiles.name;
tempStruct.createTime = allFiles.time_create;
contextVector.push_back(tempStruct);

if (findFirstContextImage != -1 ) {
    int findNextContextImage = 0;                                   //iterator for next context image in dir
    while (findNextContextImage != -1) {
        findNextContextImage = _findnext(findFirstContextImage, &allFiles);
        tempStruct.fileName = allFiles.name;
        tempStruct.createTime = allFiles.time_create;
        contextVector.push_back(tempStruct);
    }
    _findclose(findFirstContextImage);                              //Close findfirst file function to prevent memory leaks
}
else {
    cout << "There are no .img files in this directory!" << endl;   //error handling for when there are no context files
}

}

1 个答案:

答案 0 :(得分:0)

我在调试器中看错了。我没有查看向量的填充,而只是查看结构填充然后添加下一个文件,所以它看起来好像是覆盖了。我的愚蠢错误。我的代码按照我的意图工作,谢谢!