C++批量修改文件后缀名(提供多种方法)

C++批量修改文件后缀名的Qt程序

方法一:

#include "stdafx.h"

#include <stdio.h>
#include <fstream>
#include <Windows.h>

#include <cstdio>
#include <iostream>
#include <string>
#include <io.h>
#include <vector>

#include <direct.h>
#include <stdlib.h>
#include <memory>

using namespace std;

void getFilesAll( 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)
                    {
                        getFilesAll(  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 postfix()
{
    char *filePath="G:\\image\\";
    char strname[60];
    vector<string> filesa;
    getFilesAll(filePath ,filesa );
    for(unsigned int i=0 ; i<filesa.size(); i++)
    {
        char newname[80]; //store the folder's name
        char oldname[80];

        strcpy(oldname, filesa[i].c_str());

        cout<<filesa[i].c_str()<<endl;
        //strcpy(newname, filesa[i].c_str());
        sprintf(newname,"G:\\result\\%d.jpg",i);
        //sprintf(newname,"%d.jpg",i);
        rename(oldname,newname);
        if (rename(oldname,newname))
        {
            cout<<"第"<<i<<"个文件名字从"<<filesa[i].c_str()<<"修改为"<<newname<<"成功"<<endl;
        }
        cout<<strname<<endl;
    }
}
void main()
{
    postfix();
    system("pause");
}

方法二

#include <cstdlib>
#include <iostream>
#include <dirent.h>
#include <fcntl.h>
using namespace std;

int main(int argc, char *argv[])
{
    DIR *dirp=NULL;
    struct dirent *dp = NULL;
    char doing_file[1024];
    dirp = opendir("F:/Dev-Cpp/changename");
    FILE  *doing_fd;
    if(dirp == NULL)
  {
   printf("打开文件失败!/n/n");
   system("PAUSE");
            return EXIT_SUCCESS;
  }
    while( (dp = readdir(dirp)) != NULL )
  {
  // printf("..readdir:%s/n",dp->d_name);
      sprintf(doing_file,"%s",dp->d_name);
      string filename_old(doing_file); //改名前的文件名
      string filename_new(doing_file); //改名后的文件
      string::size_type point = filename_new.rfind("bmp");
      if(point != string::npos)
      {
                filename_new.replace(point,3,"jpg");
                if(rename(filename_old.c_str(),filename_new.c_str()) == 0)
                {
                   printf("改名成功完成/n/n");                                                 
                }
                else    
                perror("rename");    
            }
        } 
    closedir(dirp);
    system("PAUSE");
    return EXIT_SUCCESS;
}

方法三

c++修改指定文件夹下所有文件扩展名

#include <io.h>  
#include <iostream>  
#include <cstring>  
#include <string>

using namespace std; 
//读取文件夹设定
const string path = "D:\\pp\\";


int main(){  
    _finddata_t file;  
    long lf;  
    if((lf = _findfirst((path + "*.*").c_str(), &file))==-1)  
        cout<<"Not Found!"<<endl;  
    else{  
       // cout<<"file name list:"<<endl;  
        while(_findnext( lf, &file)==0){  
            {  
                string str=file.name;  
                //修改扩展名为.jpeg
                str += ".jpeg";
                //重命名文件
                if (rename((path + string(file.name)).c_str(), (path + str).c_str()) == 0)
                {
                    //cout << "1" << endl;
                }
            }  
        }  
    }  
    _findclose(lf);  
    return 0;  
}  

方法四

Qt应用程序
核心代码

#ifndef FILEOPERATION_H
#define FILEOPERATION_H
#include <stdio.h>
#include <string>
#include <vector>
#include <windows.h>

class FileOperation
{
public:
    FileOperation();
    FileOperation(std::string dir, std::string suffix);
    ~FileOperation();
    std::string err_msg() const { return err_msg_;}
    int error_code() const { return error_code_;}
    void set_error_code(int error_code) { error_code_ = error_code;}
    void set_err_msg(std::string err_msg) { err_msg_ = err_msg;}
    int Count() const { return file_list_->size();}
    bool RenameFile();
protected:
    void FindFiles();
private:
    std::string dirname_;
    std::string suffix_;
    std::string err_msg_;
    std::vector<std::string> *file_list_;
    WIN32_FIND_DATAA current_file_;
    HANDLE handle_;
    int error_code_;
    bool FindNext();
};

#endif // FILEOPERATION_H

#include "FileOperation.h"
#include <algorithm>
#include <iterator>
#include <windows.h>

FileOperation::FileOperation() : dirname_("D:/web/new/"), suffix_("html"),
    file_list_(new std::vector<std::string>()), error_code_(0)
{

}

FileOperation::FileOperation(std::string dir, std::string suffix) :
    dirname_(dir), suffix_(suffix), file_list_(new std::vector<std::string>()),  error_code_(0)
{
    dirname_+= "/";
}

FileOperation::~FileOperation()
{
    delete file_list_;
}

bool FileOperation::RenameFile()
{
    this->FindFiles();
    for(std::string &file_data : *file_list_) {
        //从尾部开始找‘.’,中间的.不修改
//        auto name_iter = std::find(file_data.cbegin(), file_data.cend(), '.');
        auto name_iter = std::find(file_data.crbegin(), file_data.crend(), '.');
        std::string name = std::string(file_data.cbegin(), name_iter.base());
        name += suffix_;
        name = dirname_ + name;

        if ( rename((dirname_ + file_data).c_str(), name.c_str()) != 0) {
            error_code_ = -1;
            err_msg_ += "文件"+ file_data +"更改失败";
        }
    }
    return true;
}

void FileOperation::FindFiles()
{

    LPCSTR dirname = (dirname_ + "*").c_str();
    handle_ = ::FindFirstFileA(dirname, &current_file_);
    if (handle_ != INVALID_HANDLE_VALUE) {
        if (FindNext())
            while (FindNext()) {
                file_list_->push_back(current_file_.cFileName);
            }
    }
    ::FindClose(handle_);
}

bool FileOperation::FindNext()
{
    return ::FindNextFileA(handle_, &current_file_);
}

完整源码下载地址:传送门

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在C语言中,rename函数用于将一个文件重命名。它接受两个参数,分别是旧文件名和新文件名。通常情况下,rename函数只需提供文件名和新文件名即可完成文件的重命名操作。引用的代码示例展示了一个使用rename函数的示例程序。程序首先打开旧文件,如果打开失败,则输出"File Open Failed!",然后关闭文件。接着,通过调用rename函数将旧文件重命名为新文件。如果重命名操作失败,则输出"file rename failed!"。最后,程序使用system函数暂停程序的执行,以便查看结果。 需要注意的是,rename函数在重命名文件时需要确保新文件名不存在,否则重命名操作将失败。此外,还可以使用open函数来打开文件,它接受两个参数,分别是文件名和打开模式。open函数可以用于打开文件,以便进行读取、写入等操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [文件操作——修改文件名](https://blog.csdn.net/m0_67555362/article/details/124446265)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [C++——rename异常导致的程序退出](https://blog.csdn.net/windxgz/article/details/119996940)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

whb1815

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值