我想用C++从一个引导器中获取字符串中的文件名
我有一个名为test的目录。此目录是在运行代码的另一部分时动态创建的。测试包含不同的文件。这些文件也会自动生成。假设我在目录测试中生成了a1.txt、a2.txt、a.c、a3.txt、b.c。我想在变量中获取a3.txt文件名。这意味着我要迭代目录的内容,并获取与最大数字关联的.txt文件的名称。请帮助我解决这个问题。使用opendir函数我想用C++从一个引导器中获取字符串中的文件名,c++,linux,file,C++,Linux,File,我有一个名为test的目录。此目录是在运行代码的另一部分时动态创建的。测试包含不同的文件。这些文件也会自动生成。假设我在目录测试中生成了a1.txt、a2.txt、a.c、a3.txt、b.c。我想在变量中获取a3.txt文件名。这意味着我要迭代目录的内容,并获取与最大数字关联的.txt文件的名称。请帮助我解决这个问题。使用opendir函数 DIR *opendir(const char *name); 打开该目录后,使用readdir获取该目录中的文件 struct dirent *rea
DIR *opendir(const char *name);
打开该目录后,使用readdir获取该目录中的文件
struct dirent *readdir(DIR *dirp);
using namespace std;
int getDirContent (string dir, vector<string> &files) {
DIR *dp;
struct dirent *dirp;
if ((dp = opendir(dir.c_str())) == NULL) {
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
while ((dirp = readdir(dp)) != NULL) {
files.push_back(string(dirp->d_name));
}
closedir(dp);
return 0;
}
string dir = string(".");
vector<string> files = vector<string>();
getDirContent(dir,files);
使用该结构,您可以获得文件名并使用该文件。以下内容提供了给定目录中的目录和文件
struct dirent *readdir(DIR *dirp);
using namespace std;
int getDirContent (string dir, vector<string> &files) {
DIR *dp;
struct dirent *dirp;
if ((dp = opendir(dir.c_str())) == NULL) {
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
while ((dirp = readdir(dp)) != NULL) {
files.push_back(string(dirp->d_name));
}
closedir(dp);
return 0;
}
string dir = string(".");
vector<string> files = vector<string>();
getDirContent(dir,files);
Linux。Ubuntu 12.04。执行此命令时,“./a.out”中出现***错误:双重释放或损坏输出:0x00007ffff869f680***中止内核转储错误!汇编成功。