如何用c++将文件夹中的文件名存储到数组中

How to store name of file in folder to array in c ++?

本文关键字:文件名 存储 数组 c++ 文件夹 何用      更新时间:2023-10-16

我是c++的新手。我想写一个函数,从文件夹中取名字。

例如,我有一个名为C:\TEST的文件夹,在这个文件夹中,我有很多text.txt文件,我想将所有.txt文件名存储在字符串数组中。

任何人都可以在这个问题上帮助我。

我试过这样的东西,但失败了

const int arr_size = 10;
some_type src[arr_size];
// ...
some_type dest[arr_size];
std::copy(std::begin(src), std::end(src), std::begin(dest));

使用boost文件系统:

#include<vector>
#include<string>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
int main(int argc, char* argv[])
{
    vector<string> fnames; //your filenames will be stored here
    path p (argv[1]);   // C:TEST
    directory_iterator di(p);
    directory_iterator di_end;
    while(di != di_end)
    {
        fnames.push_back( di->path().filename().string() );
        ++di;
    }
}

指定C:TEST作为上面程序的命令行参数。

TCHAR szDir[MAX_PATH]; 
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE; 
hFind = FindFirstFile(szDir, &ffd);
if (INVALID_HANDLE_VALUE != hFind) 
{
 do
  {
   if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    {
     // You can do a recursive search here, the current file is a directory
    }
   src[arr_size] = ffd.cFileName;
   arr_size++;
  }
  while (FindNextFile(hFind, &ffd) != 0);

  FindClose(hFind);
}