[英]How to search and move files from one path to another C++?
I'm trying to search all files that follow this pattern " console-*
" and move them to another path on my machine if they exist.我正在尝试搜索遵循此模式“
console-*
”的所有文件,并将它们移动到我机器上的另一个路径(如果它们存在)。 (For example from: /documents/fs/pstore
to /sdk/sys/kernel_dump/
). (例如从:
/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;
}
I've experienced with the code above, but it does not seem to work properly, should I try another approach, maybe with the rename() function?我已经体验过上面的代码,但它似乎不能正常工作,我应该尝试另一种方法,也许使用rename() function? (I'm working on Linux)
(我在 Linux 上工作)
Any advice would be greatly appreciated, thank you in advance.任何建议将不胜感激,在此先感谢您。
You can call glob() and rename() C functions in Linux if C++17's std::filesystem is not an option for you.如果 C++17 的 std::filesystem 不适合您,您可以在 Linux 中调用 glob() 和 rename() C 函数。 glob() gives you the list of files that matches globbing pattern like *, ?
glob() 为您提供匹配通配符模式的文件列表,例如 *, ? and [].
和 []。 However, rename() may fail if the mount position of from and to path are not identical.
但是,如果 from 和 to 路径的挂载 position 不相同,rename() 可能会失败。 In this case, you should create your own copy and remove file function.
在这种情况下,您应该创建自己的副本并删除文件 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.