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

Ale*_*ose 4 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);
Run Code Online (Sandbox Code Playgroud)

Jon*_*art 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
);
Run Code Online (Sandbox Code Playgroud)

示例代码(未经测试):

#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);           
Run Code Online (Sandbox Code Playgroud)


vad*_*vad 6

您已经有了文件的完整路径(例如: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));
Run Code Online (Sandbox Code Playgroud)