如何搜索文件并将其从一个路径移动到另一C ++?

问题描述

我正在尝试搜索遵循此模式“ console-*”的所有文件,并将它们移动到计算机上的其他路径(如果存在)。 (例如,从/documents/fs/pstore/sdk/sys/kernel_dump/)。

#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>

int dirExists(const char *pathname)
{
   struct stat info;

   if( stat( pathname,&info ) != 0 )
      return 0; //  printf( "cannot access %s\n",pathname );
   else if( info.st_mode & S_IFDIR )  // S_ISDIR() doesn't exist on my windows 
      return 1; //  printf( "%s is a directory\n",pathname );
   else
      return 0; //  printf( "%s is no directory\n",pathname );
}

int main()
{
    const char *path = "/documents/fs/pstore";
    if(dirExists(path))
        system("mv /documents/fs/pstore/console-* /sdk/sys/kernel_dump/ ");
    else
        printf( "error" );

    return 0;
}

我已经使用了上面的代码,但是它似乎无法正常工作,我是否应该尝试另一种方法,也许可以使用rename()函数? (我正在使用Linux)

任何建议将不胜感激,谢谢您。

解决方法

如果C ++ 17的std :: filesystem不是您的选择,则可以在Linux中调用glob()和rename()C函数。 glob()会为您提供与* 、?等glob模式匹配的文件列表。和[]。但是,如果from和to路径的安装位置不同,则rename()可能会失败。在这种情况下,您应该创建自己的副本并删除文件功能。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...