[英]How to get the directory of a file from the full path in C
我正在尝试从我在参数中获得的文件名(例如C:\some\dir\file
)动态获取父目录(例如C:\some\dir
dir ),并将其放入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:\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));
int len = strlen(filepath);
char* dir = malloc(len + 1);
strcpy(dir, filepath);
while (len > 0) {
len--;
if (dir[len] == '\\' || dir[len] == '/') {
dir[len] = '\0';
break;
}
}
没有足够的声誉发表评论,因此请在此处添加答案。
正如 Grijesh Chauhan 所评论的那样,您可以使用 strrchr() 来获取原始字符串的较短版本。
但是, strrchr()
的返回值是char *
,不应将其分配给\0
使其指向 nothing ,相反,您可以使用*
或[0]
修改它的第一个元素以缩短原始字符串。
像这样:
strrchr(File, '\\')[0] = '\0'
// or this
*(strrchr(File, '\\') = '\0'
很好的答案,Grijesh 应该让它成为一个答案:D
这是一个获取完整路径和缓冲区的函数。 它会将缓冲区更新为父路径。 检查功能。 请享用 :)
/*
Use: Get parent path by full path
Input: full path, parent buffer
Output: None
*/
void getParent(char* path, char* parent)
{
int parentLen;
char* last = strrchr(path, '/');
if (last != NULL) {
parentLen = strlen(path) - strlen(last + 1);
strncpy(parent, path, parentLen);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.