如何从C中的完整路径获取文件的目录

时间:2014-01-20 08:27:10

标签: c string file path

我正在尝试从参数中的文件名(例如C:\some\dir)动态获取父目录(假设为C:\some\dir\file),并将其放在char*中。我已经在char*中拥有完整路径和文件。我究竟会在C中做到这一点?

我有一些代码,但在我看来它是乱码,我无法理解它。我该如何改写/重写这个?

/* Gets parent directory of file being compiled */
    short SlashesAmount;
    short NamePosition;
    short NameLength;
    char* Pieces[SlashesAmount];
    char* SplitPath;
    short ByteNumber;
    short PieceNumber;
    char* ScriptDir;
    NameLength = strlen(File);

    //Dirty work
    SplitPath = strtok(File, "\");
    do {
        ByteNumber = 0;
        do {
            File[NamePosition] = CurrentPiece[ByteNumber];
            NamePosition++;
        } while(File[NamePosition] != '\n');
        PieceNumber++;
    } while(NamePosition < NameLength);

2 个答案:

答案 0 :(得分:8)

您正在寻找的是dirname(3)。这只是POSIX。

Windows替代方案是_splitpath_s

errno_t _splitpath_s(
   const char * path,
   char * drive,
   size_t driveNumberOfElements,
   char * dir,
   size_t dirNumberOfElements,
   char * fname,
   size_t nameNumberOfElements,
   char * ext, 
   size_t extNumberOfElements
);

示例代码(未经测试):

#include <stdlib.h>
const char* path = "C:\\some\\dir\\file";
char dir[256];

_splitpath_s(path,
    NULL, 0,             // Don't need drive
    dir, sizeof(dir),    // Just the directory
    NULL, 0,             // Don't need filename
    NULL, 0);           

答案 1 :(得分:3)

您已经拥有该文件的完整路径(例如:C:\ some \ dir \ file.txt),只需:
1.通过strrchr()找到最后一个斜杠:叫做p
2.从路径的开头复制到p - 1(不包括'/')
所以代码看起来像:

char *lastSlash = NULL;
char *parent = NULL;
lastSlash = strrchr(File, '\\'); // you need escape character
parent = strndup(File, strlen(File) - (lastSlash - 1));