How can I find the a file by its part of name in c++/linux? The file full name maybe like:
foo.db.1
or
foo.db.2
How can I find the file by part of its name "foo.db", Thanks
The Posix standard function for your use case is glob()
. Earlier somebody posted an easy to use C++ wrapper around it here on Stackoverflow.
For example with:
find /your/path -name "foo.db.*"
It will match all files in /your/path
structure whose name is like foo.db.<something>
.
If the text after db.
is always a number, you can do:
find /your/path -name "foo.db.[0-9]*"
You can also use ls
:
ls -l /your/path/ls.db.[0-9]
to get files whose name is like foo.db.<number>
or even
ls -l /your/path/ls.db.[0-9]*
to get files whose name is like foo.db.<different numbers>
Do like this:
find /filepath -name "foo.db*"
In C/C++, you can do like this:
void findFile(const char *path)
{
DIR *dir;
struct dirent *entry;
char fileName[] = "foo.db";
if (!(dir = opendir(path)))
return;
if (!(entry = readdir(dir)))
return;
do {
if (entry->d_type == DT_DIR) {
char path[1024];
int len = snprintf(path, sizeof(path)-1, "%s/%s", path, entry->d_name);
path[len] = 0;
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
if(strstr(fileName, entry->d_name) != NULL) {
printf("%s\n", "", entry->d_name);
}
findFile(path);
}
else
printf(" %s\n", "", entry->d_name);
} while (entry = readdir(dir));
closedir(dir);
}