1. 程式人生 > >linux下 c語言遞迴遍歷資料夾下所有檔案和子資料夾(附上替換文字檔案內容的方法)

linux下 c語言遞迴遍歷資料夾下所有檔案和子資料夾(附上替換文字檔案內容的方法)

#include <stdio.h>
#include <sys/dir.h>
#include <string>
#include <sys/stat.h>

//判斷是否為資料夾
bool isDir(const char* path);

//遍歷資料夾的驅動函式
void findFiles(const char *path);

//遍歷資料夾de遞迴函式
void findFiles(const char *path, int recursive);

#define MAX_LEN 1024 * 512

int main(int argc, const char * argv[])
{
    findFiles("未命名資料夾");
    
    return 0;
}

//判斷是否為目錄
bool isDir(const char* path)
{
    struct stat st;
    lstat(path, &st);
    return 0 != S_ISDIR(st.st_mode);
}


//遍歷資料夾的驅動函式
void findFiles(const char *path)
{
    unsigned long len;
    char temp[MAX_LEN];
    //去掉末尾的'/'
    len = strlen(path);
    strcpy(temp, path);
    if(temp[len - 1] == '/') temp[len -1] = '\0';
    
    if(isDir(temp))
    {
        //處理目錄
        int recursive = 1;
        findFiles(temp, recursive);
    }
    else   //輸出檔案
    {
        printf("======%s\n", path);
    }
}



//遍歷資料夾de遞迴函式
void findFiles(const char *path, int recursive)
{
    DIR *pdir;
    struct dirent *pdirent;
    char temp[MAX_LEN];
    pdir = opendir(path);
    if(pdir)
    {
        while((pdirent = readdir(pdir)))
        {
            //跳過"."和".."
            if(strcmp(pdirent->d_name, ".") == 0
               || strcmp(pdirent->d_name, "..") == 0)
                continue;
            sprintf(temp, "%s/%s", path, pdirent->d_name);
            
            //當temp為目錄並且recursive為1的時候遞迴處理子目錄
            if(isDir(temp) && recursive)
            {
                findFiles(temp, recursive);
            }
            else
            {
                printf("======%s\n", temp);
            }
        }
    }
    else
    {
        printf("opendir error:%s\n", path);
    }
    closedir(pdir);
}



#include<cstdlib>
#include<string>
#include<cstring>
#include<fstream>
using namespace std;
void myreplace(const string& filename,const string& tofind,const string& toreplace)
{
    ifstream fin(filename.c_str(),ios_base::binary);
    string str(1024*1024*2,0);
    fin.read(&str[0],2*1024*1024);
    fin.close();
    ofstream fout(filename.c_str(),ios_base::binary);
    string::size_type beg=0,pos,find_size=tofind.size(),replace_size=toreplace.size();

    while((pos=str.find(tofind,beg))!=string::npos)
    {
        fout.write(&str[beg],pos-beg);
        fout.write(&toreplace[0],replace_size);
        beg=pos+find_size;
    }
    fout.write(&str[beg],strlen(str.c_str())-beg);
    fout.close();
}
int main()
{
    myreplace("abca.txt","123ABCD123","456EFG456");
}