0

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

fedorqui
  • 275,237
  • 103
  • 548
  • 598
user1853170
  • 65
  • 1
  • 2
  • 8

3 Answers3

3

The Posix standard function for your use case is glob(). Earlier somebody posted an easy to use C++ wrapper around it here on Stackoverflow.

Community
  • 1
  • 1
rerx
  • 1,133
  • 8
  • 19
2

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>

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    thanks, how to combine it with c++ code? I want to get the full file name in c++ – user1853170 Sep 26 '13 at 15:43
  • In fact... People are more curious about how to do it in c++. I guess bash does this for us by running a program multiple times for different files found. – Chen Sep 26 '13 at 15:45
  • @fedorqui Till now I know the directory I am searching in, and know the namepattern("foo.db.[0-9]*"), what I want it to know what is the number that at the end of the file name, like if I find "foo.db.13", I would like to know the number is 13, in c++, Thanks – user1853170 Sep 26 '13 at 15:54
  • @user1853170 check [rerx answer](http://stackoverflow.com/a/19032887/1983854), I think it is a good introduction to what you want. – fedorqui Sep 27 '13 at 08:09
0

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);
}
Umer Farooq
  • 7,356
  • 7
  • 42
  • 67