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

标签 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);

最佳答案

您要找的是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);           

关于c - 如何从C中的完整路径获取文件的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21229214/

相关文章:

javascript - 字符串第一个单词在 Javascript 中的位置

java - JNI 字符串获取额外字符

c - memset(&mystruct, 0, sizeof mystruct) 和 mystruct = { 0 }; 一样吗?

将 char 数组转换为字符串 [和 Pebble]

java - 去除重复的字符串

ruby - Linux 和 Windows 兼容的文件管理脚本

c - 尝试从文件中读取数据并使用 strtok() 和 fgets() 在 c 中对其进行标记化

Java正则表达式在多个目录中查找文件

c - 从标准输入读取脚本

c - C 多久/何时执行 if/else 语句中的内容?