从 C 中的路径名中提取基本路径
问题
如何从 C 中的路径名中提取基本路径?
C 语言或 C 运行时库中是否有内置函数可以从 C 中的路径名中提取基本路径?< /strong>
我问的基本上与 这个问题。
注意:我更喜欢跨平台解决方案,但我在 Windows 中工作,因此如果有 Windows API 调用可以执行此操作,我仍然想知道。
示例
Input | Output
---------------------------------
C:\path\to\file -> C:\path\to\
C:\path\to\file.c -> C:\path\to\
C:\file -> C:\
.\file -> .\
.\ -> .\
\ -> \
参考
Question
How do you extract the base path from pathname in C?
Are there any functions built into the C language or the C-Runtime Library to extract the base path from a pathname in C?
I'm asking basically the opposite of this question.
NOTE: I prefer a cross-platform solution, but I'm working in Windows so if there is a Windows API call that does this, I'd still like to know.
Examples
Input | Output
---------------------------------
C:\path\to\file -> C:\path\to\
C:\path\to\file.c -> C:\path\to\
C:\file -> C:\
.\file -> .\
.\ -> .\
\ -> \
References
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
在 Windows 上,有 _splitpath。
例子
On Windows there is _splitpath.
Example
不,没有。路径名的规则是特定于平台的,因此标准不涵盖它们。
No there are not. Rules for path names are platform specific and so the standard does not cover them.
在 Windows 中,您可以使用 API 调用“PathRemoveFileSpec” http ://msdn.microsoft.com/en-us/library/bb773748(v=vs.85).aspx
由于不同操作系统之间的文件系统存在差异,跨平台解决方案实际上不可能实现。
In Windows you can use the API call "PathRemoveFileSpec" http://msdn.microsoft.com/en-us/library/bb773748(v=vs.85).aspx
Cross platform solutions will not really be possible due to variations in file systems bewtween different OS's.
只需从后到前循环,直到遇到第一个\
Just loop from back to forward until you meet the first \
WinAPI (shlwapi)
PathRemoveFileSpec
应该完成所有这些操作,但.\file
除外,它将作为.
返回WinAPI (shlwapi)
PathRemoveFileSpec
should do all of that with the exception of.\file
which would come back as.
我认为 Windows 上最好的解决方案是使用 _splitpath 正如建议的那样,在 Linux 上使用类似 basename 的内容(更多在此处)。
也就是说,由于有人已经建议实现我自己的(并且因为我在等待答案时已经完成了),所以这就是我的想法。它不是跨平台的,并且不会检查 /valid/ 路径或扩展短路径名或相对路径名。
I think the best solution on Windows is to use _splitpath as was suggested, to use something like basename on Linux (more on that here).
That said, since someone has already suggested implementing my own (and since I had already done it while I was waiting for an answer), here is what I came up with. It is not cross-platform and it does not check for /valid/ paths or expand short or relative path names.
没有标准的 C99 函数可以执行此操作。 POSIX 有
dirname()
,但在 Windows 上这对您没有多大帮助。不过,实现自己的功能对您来说应该不会太难;只需搜索字符串,查找最后一次出现的目录分隔符,并丢弃其后的任何内容。There is no standard C99 function for doing this. POSIX has
dirname()
, but that won't help you much on Windows. It shouldn't be too hard for you to implement your own function, though; just search through the string, looking for the last occurrence of the directory separator, and discard anything after it.str
之前是完整路径和文件名,str
之后只是路径:Before
str
is the full path and file name, afterstr
is just the path: