如何在 c++ 中获取文件后缀
How to get file suffix in c++?
我想获取我知道存在于某个文件夹中的文件的后缀(.txt,.png等)。我知道文件名(前缀)在此文件夹中是唯一的。语言是 c++。
谢谢
假设"后缀"是文件扩展名,您可以这样做:
char * getfilextension(char * fullfilename)
{
int size, index;
size = index = 0;
while(fullfilename[size] != ' ') {
if(fullfilename[size] == '.') {
index = size;
}
size ++;
}
if(size && index) {
return fullfilename + index;
}
return NULL;
}
它是 C 代码,但我相信可以轻松移植到 C++(也许没有变化)。
getfilextension("foo.png"); /* output -> .png */
我希望这对你有所帮助。
更新:
您将需要扫描目录的所有文件,如果等于您的目标,则比较每个没有扩展名的文件。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <limits.h>
#include <dirent.h>
#include <string.h>
//.....
char * substr(char * string, int start, int end)
{
char * p = &string[start];
char * buf = malloc(strlen(p) + 1);
char * ptr = buf;
if(!buf) return NULL;
while(*p != ' ' && start < end) {
*ptr ++ = *p++;
start ++;
}
*ptr++ = ' ';
return buf;
}
char * getfilenamewithoutextension(char * fullfilename)
{
int i, size;
i = size = 0;
while(fullfilename[i] != ' ') {
if(fullfilename[i] == '.') {
size = i;
}
i ++;
}
return substr(fullfilename, 0, size);
}
char * getfilextension(char * fullfilename)
{
int size, index;
size = index = 0;
while(size ++, fullfilename[size]) {
if(fullfilename[size] == '.') {
index = size;
}
}
if(size && index) {
return fullfilename + index;
}
return NULL;
}
char*FILE_NAME;
int filefilter(const struct dirent * d)
{
return strcmp(getfilenamewithoutextension((char*)d->d_name), FILE_NAME) == 0;
}
然后:
void foo(char * path, char * target) {
FILE_NAME = target;
struct dirent ** namelist;
size_t dirscount;
dirscount = scandir(path, &namelist, filefilter, alphasort);
if(dirscount > 0) {
int c;
for(c = 0; c < dirscount; c++) {
printf("Found %s filename,the extension is %s.n", target, getfilextension(namelist[c]->d_name));
free(namelist[c]);
}
free(namelist);
} else {
printf("No files found on %sn", path);
}
}
和主代码:
int main(int argc, char * argv[])
{
foo(".", "a"); /* The .(dot) scan the current path */
}
对于包含此文件的目录:
a.c a.c~ a.out
a.o makefile test.cs
输出为:
Found a filename,the extension is .c.
Found a filename,the extension is .c~.
Found a filename,the extension is .o.
Found a filename,the extension is .out.
注意:scandir()
函数是 GNU 扩展/GNU 库的一部分,如果你的编译器上没有这个函数,告诉我我会为它写一个别名或使用此实现(不要忘记阅读许可证)。
如果您使用的是Windows,请使用PathFindExtension。
在 c++ 中没有列出目录内容的标准功能。因此,如果您知道应用中允许的扩展,则可以循环访问并查找文件是否存在。
其他选项是使用特定于操作系统的 API 或使用类似 Boost 的东西。您也可以使用"ls |grep *文件名"或"dir"命令转储并解析输出。
相关文章:
- 获取文件数据预处理器宏
- 如何在Windows内核中获取文件大小
- 从 C 中的变量获取文件的路径,C++
- 如何使用 C/C++ 和 system() 系统调用以外的其他方法在 Linux 中获取文件功能?
- 如何使用 jpeglib.h 获取文件是否为 JPEG 类型
- 谁能告诉我,程序中的错误是什么?该程序仅用于获取文件扩展名
- 我需要通过窗口句柄(HWND)获取文件,我该怎么办?
- 如何用C++部分地获取文件中的行
- 使用内置的Windows方法获取文件夹的内容
- 在 Apache Velocity 模板语言中获取文件目录
- 如何在C#或C++中获取文件或文件夹的有效权限?有什么 API 吗?
- 对字符求和并减去以获取文件
- 从 FutureAccessList 同步获取文件夹路径
- 通过HTTPS从POCO StreamCopier获取文件下载进度
- 如何使用C 17获取文件大小
- getline 无法获取文件的第一行
- 如何使用 Win API 获取文件夹中的文件列表(带过滤器)
- 无法从零MQ ZMQ_SERVER套接字中获取文件描述符
- HttpQueryInfo 获取文件大小
- 通过文件资源管理器获取文件夹目录