Я написал функцию C++, которая использует «recursive_directory_iterator» для получения информации обо всех файлах и папках в родительской папке. Затем я написал класс DataFolder для хранения атрибутов каждого файла, таких как размер файла, путь, имя, дата и т. д. Наконец, я использовал векторный объект для хранения коллекции объектов DataFolder.
Для векторного объекта я использую push_back для добавления объектов DataFolder. Первое назначение работает, однако при последующих попытках назначения выполняются без проблем с памятью или доступом, но данные, содержащиеся во всех ранее сохраненных элементах, повреждаются. Неизменным остается только самое последнее добавление.
Как добавить объекты DataFolder к моему векторному объекту C++ STL и сохранить данные, ранее хранившиеся в векторе?
Это функция, которую я создал: Directory_base.
#include
#include
#include
#include
#include "CDir.h"
using namespace std;
using namespace std::filesystem;
// CDIR List folder.
// CDIR NAME lists the files in a folder.NAME must be specified as a
// character vector or string scalar.
//
// NAME can include a relative path, but the relative path must be in the
// current folder.Otherwise, NAME must include a full path.
//
// To list filesand folders at a remote location, NAME must contain a
// full path specified as a uniform resource locator(URL).
//
// Pathnamesand asterisk wildcards may be used in NAME.A single asterisk
// in the path touching only file separators will represent exactly one
// folder name.A single asterisk at the end of an input will represent
// any filename.An asterisk followed or preceded by characters will
// resolve to zero or more characters.A double asterisk can only be used
// in the path and will represent zero or more folder names.It cannot
// touch a character other than a file separator.For example, DIR* .m
// lists all files with a.m extension in the current folder.DIR*/*.m
// lists all files with a .m extension exactly one folder under the
// current folder. CDIR **/* .m lists all files with a.m extension zero or
// more folders under the current folder.
//
// D = CDIR('NAME') returns the results in an M - by - 1
// structure with the fields :
// name -- Filename
// folder -- Absolute path
// date -- Modification date
// bytes -- Number of bytes allocated to the file
// isdir-- 1 if name is a folder and 0 if not
// datenum -- Modification date as a MATLAB serial date number.
// This value is locale - dependent.
//
// See also WHAT, CD, TYPE, DELETE, LS, RMDIR, MKDIR, DATENUM.
// Copyright 1984 - 2019 The MathWorks, Inc.
// Built - in function.
static const char* convertIntToMonth(int imon)
{
if (imon == 1)
{
return "Jan";
}
else if (imon == 2)
{
return "Feb";
}
else if (imon == 3)
{
return "Mar";
}
else if (imon == 4)
{
return "Apr";
}
else if (imon == 5)
{
return "May";
}
else if (imon == 6)
{
return "Jun";
}
else if (imon == 7)
{
return "Jul";
}
else if (imon == 8)
{
return "Aug";
}
else if (imon == 9)
{
return "Sep";
}
else if (imon == 10)
{
return "Oct";
}
else if (imon == 11)
{
return "Nov";
}
else if (imon == 12)
{
return "Dec";
}
else if (imon < 1 || imon > 12)
{
return "OOR";
}
return "INV";
}
static double dateNumber(double year, int month, double day)
{
double cumdays[] = { 0, 0,31,59,90,120,151,181,212,243,273,304,334 };
double retval = 365 * year + cumdays[month] + day;
retval += year / 4;
return retval;
}
const vector& directory_base(const char* path, vector& datfldr)
{
int ii = 0;
cout path()))
{
DataFolder df{};
filesystem::path df_name = i->path();
string fn = df_name.string();
df.name = new char[fn.length()];
df.name = const_cast(fn.c_str());
struct stat attrib {};
struct tm *clock = new tm();
stat(df.name, &attrib);
errno_t errNo = localtime_s(clock, &(attrib.st_mtime));
size_t fsz = file_size(df.name);
df.bytes = static_cast(file_size(df_name));
string tmp = to_string(clock->tm_mday) + "-" +
convertIntToMonth(clock->tm_mon+1) + "-" + to_string(clock->tm_year+1900) + "
" + to_string(clock->tm_hour) + ":" + to_string(clock->tm_min) + ":" +
to_string(clock->tm_sec);
df.date = new char[tmp.length()];
df.date = const_cast(tmp.c_str());
df.datenum = dateNumber(static_cast(clock->tm_year)+1900, clock-
>tm_mon+1, clock->tm_mday);
filesystem::path df_fldr = i->path().parent_path();
string ffldr = df_fldr.string();
df.folder = new char[ffldr.length()];
df.folder = const_cast(ffldr.c_str());
df.isdir = false;
cout path().filename()
Подробнее здесь: [url]https://stackoverflow.com/questions/78521071/the-data-inside-c-vector-changes-when-i-use-push-back[/url]
Я написал функцию C++, которая использует «recursive_directory_iterator» для получения информации обо всех файлах и папках в родительской папке. Затем я написал класс DataFolder для хранения атрибутов каждого файла, таких как размер файла, путь, имя, дата и т. д. Наконец, я использовал векторный объект для хранения коллекции объектов DataFolder. Для векторного объекта я использую push_back для добавления объектов DataFolder. Первое назначение работает, однако при последующих попытках назначения выполняются без проблем с памятью или доступом, но данные, содержащиеся во всех ранее сохраненных элементах, повреждаются. Неизменным остается только самое последнее добавление. Как добавить объекты DataFolder к моему векторному объекту C++ STL и сохранить данные, ранее хранившиеся в векторе? Это функция, которую я создал: Directory_base. [code]#include #include #include #include #include "CDir.h"
using namespace std; using namespace std::filesystem;
// CDIR List folder. // CDIR NAME lists the files in a folder.NAME must be specified as a // character vector or string scalar. // // NAME can include a relative path, but the relative path must be in the // current folder.Otherwise, NAME must include a full path. // // To list filesand folders at a remote location, NAME must contain a // full path specified as a uniform resource locator(URL). // // Pathnamesand asterisk wildcards may be used in NAME.A single asterisk // in the path touching only file separators will represent exactly one // folder name.A single asterisk at the end of an input will represent // any filename.An asterisk followed or preceded by characters will // resolve to zero or more characters.A double asterisk can only be used // in the path and will represent zero or more folder names.It cannot // touch a character other than a file separator.For example, DIR* .m // lists all files with a.m extension in the current folder.DIR*/*.m // lists all files with a .m extension exactly one folder under the // current folder. CDIR **/* .m lists all files with a.m extension zero or // more folders under the current folder. // // D = CDIR('NAME') returns the results in an M - by - 1 // structure with the fields : // name -- Filename // folder -- Absolute path // date -- Modification date // bytes -- Number of bytes allocated to the file // isdir-- 1 if name is a folder and 0 if not // datenum -- Modification date as a MATLAB serial date number. // This value is locale - dependent. // // See also WHAT, CD, TYPE, DELETE, LS, RMDIR, MKDIR, DATENUM.
// Copyright 1984 - 2019 The MathWorks, Inc. // Built - in function.
static const char* convertIntToMonth(int imon) { if (imon == 1) { return "Jan"; } else if (imon == 2) { return "Feb"; } else if (imon == 3) { return "Mar"; } else if (imon == 4) { return "Apr"; } else if (imon == 5) { return "May"; } else if (imon == 6) { return "Jun"; } else if (imon == 7) { return "Jul"; } else if (imon == 8) { return "Aug"; } else if (imon == 9) { return "Sep"; } else if (imon == 10) { return "Oct"; } else if (imon == 11) { return "Nov"; } else if (imon == 12) { return "Dec"; } else if (imon < 1 || imon > 12) { return "OOR"; }