【问题标题】:How to search and move files from one path to another C++?如何搜索文件并将其从一个路径移动到另一个 C++?
【发布时间】:2020-08-11 08:54:20
【问题描述】:

我正在尝试搜索遵循此模式“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?
  • 我仅限于 C++14
  • 不要用 C 标记 C++ 问题,这是不好的标记
  • 如果boost 没问题,那么看看boost.filesystem

标签: c++ file path


【解决方案1】:

如果 C++17 的 std::filesystem 不适合您,您可以在 Linux 中调用 glob() 和 rename() C 函数。 glob() 为您提供匹配通配符模式的文件列表,例如 *, ?和 []。但是,如果 from 和 to 路径的挂载位置不相同,rename() 可能会失败。在这种情况下,您应该创建自己的复制和删除文件功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-11
    • 1970-01-01
    • 2013-08-25
    • 2021-01-26
    • 1970-01-01
    相关资源
    最近更新 更多