获取没有完整路径的目录名称(C unix)

时间:2015-09-29 13:06:06

标签: c file unix dir

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

我正在尝试创建一个程序来查找具有特定名称的所有文件/文件夹但是使用我当前的代码我得到了完整的文件路径,因此我无法使用strcmp来查找我的路径。假设argv [2] ==“程序”然后如果路径是“c:// Programs”则找不到它。在C中有没有办法获取目录的名称?

1 个答案:

答案 0 :(得分:1)

  

C中是否有任何方法可以获取目录的名称?

在Linux上我使用这样的东西:

#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;
}

输出:

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

或类似的东西:

#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;
}