C++ 遍历所有文件和文件夹,建立文件夹

首先介绍一下”DWORD”
在win32中有这样的定义:

#define DWORD unsigned long

表示一个32位无符号整型数,或用来表示段地址和段地址的偏移量;Windows下经常用来保存地址(或者存放指针).

C++ 遍历所有文件和文件夹, 包含头文件#include <windows.h>

WIN32_FIND_DATA fd;

HANDLE hFind = ::FindFirstFile("C:\\*.*", &fd);
if(hFind != INVALID_HANDLE_VALUE)
{
    do
    {
        printf(fd.cFileName);
    }
    while(::FindNextFile(hFind, &fd));
    ::FindClose(hFind);
}

如果想遍历所有文件和文件夹,以及所有子目录、子文件,则需要用SetCurrentDirectory设置当前的下一级目录,然后递归调用

GetCurrentDirectory和SetCurrentDirectory是获取和设置的线程的当前工作路径,而不是线程所在路径。下面的代码是源文件所在路径下有一个文件为write.txt,而上一级路径下没有这个文件,来说明这两个函数的功能。

#ifndef _TEST_H  

#include <iostream>  
#include <windows.h>  
#include <string>  
#include <stdlib.h>  
using namespace std;  
int main()  
{  
    char buf[1000];  
    int i=1000;  
    GetCurrentDirectory(1000,buf);  //得到当前工作路径  

    string a;  
    a.assign(buf);  
    cout<<a<<endl;  
    a.append("\\..\\");  

    FILE *pFile;  
    pFile = fopen("write.txt","r");  
    if (pFile == NULL)  
        cout << "open failure" << endl;  
    fclose(pFile);  

    int test = SetCurrentDirectory(a.c_str());  //设置当前路径值  
    if (test == 0 )  
        cout << "execute failed\n";  
    GetCurrentDirectory(1000,buf);  
    cout << buf << endl;  

    pFile = fopen("write.txt","r");  
    if (pFile == NULL)  
        cout << "open failure" << endl;  
    else   
        fclose(pFile);  

    return 0;  
}  


#endif //_TEST_H  

用到的函数:access和mkdir,分别包含头文件io.h和direct.h如果想深入了解就去查msdn。

char *fileName=".\\1\\2\\3\\a.txt",*tag;
for(tag=fileName;*tag;tag++)
{
   if (*tag=='\\')
   {
    char buf[1000],path[1000];
    strcpy(buf,fileName);
    buf[strlen(fileName)-strlen(tag)+1]=NULL;
    strcpy(path,buf);
    if (access(path,6)==-1)
    {
     mkdir(path);
    }
   }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值