c++ 替换修改一个文件夹下的所有文件的文件名

代码简洁,亲测可用。

1,首先来获取(输出)一个文件夹中所有的文件名

void getFiles(string path, vector<string>& files)
{
    //文件句柄
    long   hFile = 0;
    //文件信息
    struct _finddata_t fileinfo;
    string p;
    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)
                    getFiles(p.assign(path).append("\\").append(fileinfo.name), files);
            }
            else
            {
                files.push_back(p.assign(path).append("\\").append(fileinfo.name));
            }
        } while (_findnext(hFile, &fileinfo) == 0);
        _findclose(hFile);
    }
}
void main()
{
    InitConsoleWindow1();
    char * filePath = "E:/gait/004";
    vector<string> files;

        getFiles(filePath, files);

        char str[30];
        int size = files.size();
        for (int i = 0; i < size; i++)
        {
            cout << files[i].c_str() << endl;
        }
}

因为当时写的是个mfc框架,Initconsolewindow1()是为了能在mfc运行时输出控制台信息

void InitConsoleWindow1()
{
    int nCrt = 0;
    FILE* fp;
    AllocConsole();
    nCrt = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
    fp = _fdopen(nCrt, "w");
    *stdout = *fp;
    setvbuf(stdout, NULL, _IONBF, 0);
}

2,然后替换(修改)其中的某些字符

#include<string>
#include<iostream>
using namespace std;

//第一种替换字符串的方法用replace()

void string_replace(string&s1,const string&s2,const string&s3)
{
    string::size_type pos=0;
    string::size_type a=s2.size();
    string::size_type b=s3.size();
    while((pos=s1.find(s2,pos))!=string::npos)
    {
        s1.replace(pos,a,s3);
        pos+=b;
    }
}

//第二种替换字符串的方法用erase()和insert()

void string_replace_2(string&s1,const string&s2,const string&s3)
{
    string::size_type pos=0;
    string::size_type a=s2.size();
    string::size_type b=s3.size();
    while((pos=s1.find(s2,pos))!=string::npos)
    {
        s1.erase(pos,a);
        s1.insert(pos,s3);
        pos+=b;
    }
}


3,利用c++改变文件夹内文件的名字,使之变成你修改后的。

rename(oldfilename,newfilename);

oldfilename是char*型,c的这个函数真是很好使啊。

值得注意的是:

1,替换函数,while中的顺序在!=前面是个整体,一开始漏掉那个括号导致没有跳出循环

2,替换函数,整体基本都要在读取文件的while函数中,除了个别不会改变的变量,如a,b的值。之前把string::size_type pos = 0;放在读取文件的while函数外面导致只修改了一个文件的名字。

就酱~

原文链接: https://www.cnblogs.com/Daringoo/p/5405946.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/232080

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午3:18
下一篇 2023年2月13日 下午3:18

相关推荐