Search code examples
cfileunixdir

Get directory name without full path (C unix)


DIR *dir;
struct dirent *entry;
if ((dir = opendir (argv[1])) != NULL) {
  while ((entry = readdir (dir)) != NULL) {
    if(strcmp(entry->d_name,argv[2])==0)   
        printf ("%s\n", entry->d_name);
}
//recursive call, can post if needed

I'm trying to make a program to find all files/folders with a specific name but with my current code I get the full filepath so I can't really use strcmp to find my path. Let's say that argv[2]=="Programs" then it won't find it if the path is "c://Programs". Is there any way in C to just get the name of the directory?


Solution

  • Is there any way in C to just get the name of the directory?

    On Linux I use something like this:

    #include<stdio.h>
    #include<stdlib.h>
    #include<unistd.h>
    #include<linux/limits.h>
    #include<string.h>
    
    void *getCurrentDir(void){
        char *currWorkDir, *token;
        char buffer[PATH_MAX + 1];
        char *directory;
        size_t length;
    
        currWorkDir = getcwd(buffer, PATH_MAX + 1 );
        token = strrchr(currWorkDir, '/');
    
        if( currWorkDir == NULL ){
            printf("Error"); /* You decide here */
            exit(1);
        }
    
        if (token == NULL) {
            printf("Error"); /* You decide here */
            exit(1);
        }
    
        length = strlen(token);
        directory = malloc(length);
        memcpy(directory, token+1, length);
    
        return directory;
    }
    
    int main( void ){
        char *dir = getCurrentDir();
        printf("The current Working Directory is: %s\n", dir);
    
        free(dir);
        return 0;
    }
    

    Output:

    michi@michi-laptop:~$ pwd
    /home/michi
    
    michi@michi-laptop:~$ ./program
    The current Working Directory is: michi
    

    Or something like this:

    #include<stdio.h>
    #include<stdlib.h>
    #include<unistd.h>
    #include<linux/limits.h>
    #include<string.h>
    
    void *getCurrentDir(char *path){
        char *token;
        char *directory;
        size_t length;
    
        token = strrchr(path, '/');
    
        if (token == NULL) {
            printf("Error"); /* You decide here */
            exit(1);
        }
    
        length = strlen(token);
        directory = malloc(length);
        memcpy(directory, token+1, length);
    
        return directory;
    }
    
    int main( void ){
        char *path = "/home/michi";
        char *dir = getCurrentDir(path);
        printf("The current Working Directory is: %s\n", dir);
    
        free(dir);
        return 0;
    }