c++遍历当前windows目录

文章介绍了在C++17环境下,如何避免VS中的字符集兼容问题,以及使用`<filesystem>`库简化目录遍历与文件操作。对比了C++11和C++17在处理文件系统的差异。

前言

设置vs的高级属性为使用多字节字符集,不然会报char类型的实参与LPCWSTR类型的形参类型不兼容的错误

代码

#include <iostream>
#include <cstring>
#include <windows.h>

void listFiles(const char* dir);

int main()
{
    using namespace std;
    char dir[100] = "D:/prostate_run/";
    /*cout << "Enter a directory (ends with \'\\\'): ";
    cin.getline(dir, 100);*/
    strcat_s(dir, "*.*");    // 需要在目录后面加上*.*表示所有文件/目录
    listFiles(dir);
    return 0;
}

void listFiles(const char* dir)
{
    using namespace std;
    HANDLE hFind;
    WIN32_FIND_DATA findData;
    LARGE_INTEGER size;
    hFind = FindFirstFile(dir, &findData);
    if (hFind == INVALID_HANDLE_VALUE)
    {
        cout << "Failed to find first file!\n";
        return;
    }
    do
    {
        // 忽略"."和".."两个结果 
        if (strcmp(findData.cFileName, ".") == 0 || strcmp(findData.cFileName, "..") == 0)
            continue;
        if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)    // 是否是目录 
        {
            cout << findData.cFileName << "\t<dir>\n";
        }
        else
        {
            size.LowPart = findData.nFileSizeLow;
            size.HighPart = findData.nFileSizeHigh;
            cout << findData.cFileName << "\t" << size.QuadPart << " bytes\n";
        }
    } while (FindNextFile(hFind, &findData));
    cout << "Done!\n";
}

在这里插入图片描述

如果使用c++17,就简单很多了

#include"ICommonFuncs.h"
#include<filesystem>
#include<iostream>

namespace fs = std::filesystem;

int main()
{
	std::string dataDir("F:\\dicom2nii_data\\dicom-data");
	fs::path currentPath(dataDir);

	ICommonFuncs ifc;
	ImagePointerType inputImage;

	for (const auto& entry : fs::directory_iterator(currentPath))
	{
		if (fs::is_directory(entry.status()))
		{
			/*std::cout << entry.path() << std::endl;
			std::cout << entry.path().filename() << std::endl;*/

			ifc.readDicomSeries(entry.path().string(), inputImage);
			std::string saveNiiPath(dataDir+"/" +entry.path().filename().string() + ".nii.gz");
			ifc.writeData<ImageType, ImagePointerType>(inputImage, saveNiiPath);
		}
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值