POSIX或Linux API函数可从路径获取文件扩展名 [英] POSIX or Linux API function to get file extension from path

查看:202
本文介绍了POSIX或Linux API函数可从路径获取文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个POSIX或Linux API函数,该函数需要文件路径并返回该文件的扩展名.每个平台都应该有一个,但对于Linux,我不能.叫什么?

I need a POSIX or Linux API function that takes file path and returns this file's extension. Every platform should have one, but I can't it for Linux. What's it called?

推荐答案

首先使用strrchr查找路径名中的最后一个'.'.如果不存在,就没有扩展名".

First use strrchr to find the last '.' in the pathname. If it doesn't exist, there's no "extension".

接下来,使用strchr检查最后一个'.'之后是否还有任何'/'.如果是这样,则最后一个'.'位于目录组件中,而不是文件名中,因此没有扩展名.

Next, use strchr to check whether there's any '/' after the last '.'. If so, the last '.' is in a directory component, not the filename, so there's no extension.

否则,您找到了扩展名.您可以将指针直接用作的位置,并将其用作C字符串.除非将原始字符串释放或破坏后再使用,否则无需将其复制到新的存储中.

Otherwise, you found the extension. You can use the pointer to the position one past the '.' directly as a C string. No need to copy it to new storage unless the original string will be freed or clobbered before you use it.

注意:上面假设您将扩展名"定义为仅最后一个'.'分隔的组件.如果您想将.tar.gz.cpp.bak之类的内容视为扩展,则可以使用一种稍微不同的方法:

Note: The above is assuming you define "extension" as only the final '.'-delimited component. If you want to consider things like .tar.gz and .cpp.bak as extensions, a slightly different approach works:

首先,使用strrchr查找最终的'/'.如果未找到,则将字符串的开头视为您的结果.

First, use strrchr to find the final '/'. If not found, treat the start of the string as your result.

第二,使用strchr从刚找到的位置开始查找第一个'.'.结果就是您的扩展名.

Second, use strchr to find the first '.' starting from the position you just found. The result is your extension.

这篇关于POSIX或Linux API函数可从路径获取文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆