Search code examples
cfile-exists

check if file exists with a partial name in C


I know the directory of a file, but I have only a partial file name. How can check if this file exists in C

For example:

/tmp/God_of_War

The filename is actually called:

/tmp/God_of_War_PSP(USA).rar

Solution

  • This is impossible in portable C because the C Standard Library does not have an API for enumerating files in a directory (then matching them yourself) let alone an API for matching file names by a pattern. This is because C predates modern notions of hierarchical directories (even the original Macintosh in 1984 didn't support subdirectories) - and because C still supports those systems today (think: microcontrollers).

    In practice, you'd use your platform's filesystem API: on Unix-like/POSX systems including Linux that's done with dirent.h - and for your problem specifically you'd use the glob function: http://pubs.opengroup.org/onlinepubs/009604499/basedefs/glob.h.html

    glob_t result;
    const int ok = glob( "/tmp/God_of_War*", /*flags:*/ 0, /*errfunc:*/ NULL, &result );
    if( 0 == ok ) {
        for( size_t i = 0; i < result.gl_pathc; i++ ) {
            puts( result.gl_pathv[i] );
        }
    }
    else {
        // error
    }
    globfree( &result);
    

    On Windows, that's FindFirstFile and FindNextFile which you can use wildcards with, just like glob.

    WIN32_FIND_DATA result;
    HANDLE searchHandle = FindFirstFile( "God_of_War*", &result);
    if( searchHandle == INVALID_HANDLE_VALUE ) {
        // handle error, use GetLastError() for details
    }
    else {
        do {
            puts( searchHandle.cFileName );
        }
        while( FindNextFile( searchHandle, &searchHandle ) );
        DWORD lastError = GetLastError();
        if( lastError != ERROR_NO_MORE_FILES ) {
            // handle error
        }
    }