21xrx.com
2025-04-18 01:22:39 Friday
文章检索 我的文章 写文章
如何用C++随机从文件夹中选取文件?
2023-07-03 15:04:29 深夜i     26     0
C++ 随机选取 文件夹

在编程中,有时需要从一个文件夹中随机选取一个文件进行处理,以便提高程序的灵活性和可扩展性。针对这一需求,可以使用C++语言来编写程序实现。下面是一份简单的教程,介绍如何使用C++随机从文件夹中选取文件。

第一步:获取文件夹中的所有文件名

要从文件夹中选取一个文件,首先需要获取这个文件夹中的所有文件名。可以通过C++中提供的 头文件来实现。使用该头文件中的opendir()函数打开指定文件夹,再使用readdir()函数逐个读取文件夹中的文件。

代码示例:

#include <dirent.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> get_file_names(const string& folder_path)
{
  vector<string> files;
  DIR *dir;
  struct dirent *ent;
  if ((dir = opendir(folder_path.c_str())) != NULL)
  {
    while ((ent = readdir(dir)) != NULL)
    {
      if (ent->d_type == DT_REG)
      {
        string file_name = ent->d_name;
        files.push_back(file_name);
      }
    }
    closedir(dir);
  }
  else
  
    cerr << "Cannot open folder " << folder_path << endl;
  
  return files;
}

在上面的代码中,get_file_names()函数可以传入指定的文件夹路径,返回一个string类型的vector,其中包含该文件夹中所有文件的文件名。

第二步:从文件名列表中随机选取一个文件

有了文件名列表,就可以随机选取一个文件了。使用C++中的标准库random头文件中的random_shuffle()函数将文件名随机打乱顺序,再选取第一个文件名即可。

代码示例:

#include <algorithm>
#include <random>
string select_file_name(const vector<string>& file_names)
{
  vector<string> temp_files = file_names;
  random_shuffle(temp_files.begin(), temp_files.end());
  return temp_files[0];
}

在上面的代码中,select_file_name()函数传入文件名列表,返回一个string类型的文件名。

第三步:完整代码示例

将上述两个函数集成在一起,就可以实现从文件夹中随机选取一个文件了。完整代码如下:

#include <dirent.h>
#include <iostream>
#include <random>
#include <string>
#include <vector>
using namespace std;
vector<string> get_file_names(const string& folder_path)
{
  vector<string> files;
  DIR *dir;
  struct dirent *ent;
  if ((dir = opendir(folder_path.c_str())) != NULL)
  {
    while ((ent = readdir(dir)) != NULL)
    {
      if (ent->d_type == DT_REG)
      {
        string file_name = ent->d_name;
        files.push_back(file_name);
      }
    }
    closedir(dir);
  }
  else
  
    cerr << "Cannot open folder " << folder_path << endl;
  
  return files;
}
string select_file_name(const vector<string>& file_names)
{
  vector<string> temp_files = file_names;
  random_shuffle(temp_files.begin(), temp_files.end());
  return temp_files[0];
}
int main()
{
  string folder_path = "/home/user/files"// 指定文件夹路径
  vector<string> file_names = get_file_names(folder_path);
  if (file_names.size() > 0)
  {
    string selected_file = select_file_name(file_names);
    cout << "Selected file: " << selected_file << endl;
  }
  else
  
    cerr << "No files in folder " << folder_path << endl;
  
  return 0;
}

在上述代码中,指定文件夹路径后,依次执行get_file_names()和select_file_name()函数即可选取一个随机文件名。注意,使用以上代码需要导入相应的头文件并链接相关库。

  
  

评论区

请求出错了