用c++编写一个程序 实现从某一文件夹中找出扩展名相同的文件 并存放在一个新建的文件夹里

文件夹的新建与文件的拷贝在程序中完成。

使用VC下的MFC项目里的API“FindFile”以及“MoveFile"可以轻松实现你的需求。

FindFile用于查找文件,而MoveFile则用于移动文件,代码如下:

//ext是要移动的文件扩展名,如:"exe"
//dir是要移动的目标目录路径,如:"D:\\DestDir"
void MoveFileByExt(const CString& ext, const CString& dir)
{
    CString cond, path;
    CFileFind ff;

    //组成文件筛选条件 
    cond.Format(_T("*.%s"), ext); 
    
    //查找条件下的文件
    BOOL bRet = ff.FindFile(cond);
    while (bRet)
    {
        bRet = ff.FindNextFile();
        if (ff.IsDirectory()) continue;
 
        //组成移动后的文件路径 
        path.Format(_T("%s\\%s"), dir, ff.GetFileName());
  
        //移动文件 
        MoveFile(ff.GetFilePath(), path);
    }
    ff.Close();
}


 

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-07-19

以下环境均在GNU/Linux下。

并且由于本人常年使用C语言,所以写出来的代码类似C

原理:

通过遍历该目录下所有文件,并取得后缀名,再次遍历是否有后缀名相同的文件,并且复制如以该文件后缀名为名的文件。

代码:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>

void cpFile(char *src, char *target) /* src为文件,target为文件夹 */
{
FILE *srcH = NULL;
FILE *outH = NULL;
char buffer[1024] = "";
char path[1024] = "";

snprintf(path, sizeof(path), "%s/%s", target, src);

srcH = fopen(src, "rb"); /* rb表示打开二进制 */
if (srcH == NULL)
{
perror("fopen");
return;
}
outH = fopen(path, "wb+");
if (outH == NULL)
{
perror("fopen");
return;
}

while (fread(buffer, 1, 1024, srcH) != 0)
{
fwrite(buffer, 1, 1024, outH);
memset(buffer, 0, sizeof(buffer)); /* 清空buffer
                                        中的内容 */
}

fclose(outH);
fclose(srcH);
}

int main()
{
DIR *dp;
struct dirent *dirInfo;
char lastName[10] = "";
DIR *kindDir;
struct dirent *kindDirInfo;

if (NULL == (dp = opendir("./")))
{
perror("opendir");
exit(EXIT_FAILURE);
}

while ((dirInfo = readdir(dp)) != NULL) /* 遍历 */
{
if (dirInfo->d_type & DT_DIR)
{
continue;
}

memcpy(lastName, strstr(dirInfo->d_name, "."), sizeof(lastName));

if (0 != access(lastName, F_OK)) /* 检测文件夹是否存在,
                           如果不存在那么创建该文件夹 */
{
if (-1 == mkdir(lastName, 0755))
{
perror("mkdir");
continue;
}
}

if (NULL == (kindDir = opendir("./")))
{
perror("opendir");
continue;
}


/* 再次遍历查找是否有相同后缀名的文件,
并将其复制到指定文件夹 */
while ((kindDirInfo = readdir(kindDir)) != NULL)
{
if (dirInfo->d_type & DT_DIR)
{
continue;
}

if (0 == strcmp(lastName, strstr(dirInfo->d_name, ".")))
{
cpFile(dirInfo->d_name, lastName);
}
}

closedir(kindDir);
}

closedir(dp);

return 0;
}

注:由于是以.开头,所以在GNU/Linux为隐藏文件。

相似回答