c++读取文件夹内容

可以读取某个文件夹下面所有文件名称 / 目录名称

#include <string>
#include <iostream>
#include <vector>
#include <direct.h>
using namespace std;
//读取所有文件名到vector数组里面
void getJustCurrentFile(string path, vector<string>& files)
{
    //文件句柄
    //long hFile = 0;
    intptr_t hFile = 0;//这个intptr_真是坑死了,一开始一直报错
    //文件信息
    struct _finddata_t fileinfo;//文件信息读取结构
    string p;
    if((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
    {
        do
        {
            if((fileinfo.attrib & _A_SUBDIR))//判断文件类型是不是目录
            {
                ;
            }
            else
            {
                files.push_back(fileinfo.name);
            }
        }
        while(_findnext(hFile, &fileinfo) == 0);
        _findclose(hFile);
    }
}

//读取所有目录
void getJustCurrentDir(string path, vector<string>& files)
{
    //文件句柄
    intptr_t hFile = 0;
    //文件信息
    struct _finddata_t fileinfo;//文件信息读取结构
    string p;//assign() string的赋值函数
    if((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
    {
        do
        {
            if((fileinfo.attrib & A_SUBDIR))//判断文件类型是否是目录
            {
                if(strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
                {
                    files.push_back(fileinfo.name);
                }
            }
        }
        while(_findnext(hFile, &fileinfo) == 0)//寻找下一个,成功返回0,否则-1
        _findclose(hFile);
    }
}

int main()
{
    string path;
    cin >> path;
    vector<string> files;
    getJustCurrentFile(path, files);
    for(int i = 0; i < files.size(); i++)
    {
        cout << files[i] << endl;
    }
}

 

posted @ 2021-02-20 00:49  花与不易  阅读(243)  评论(0)    收藏  举报