linux下 c语言递归遍历文件夹下所有文件和子文件夹(附上替换文本文件内容的方法)

来源:互联网 发布:js设置radio不可用 编辑:程序博客网 时间:2024/05/09 05:04

#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 * 512int 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);}


附上一个C语言实现文本替换的例子

#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");}


0 0
原创粉丝点击