我想要获取后缀(.txt、.png等)我所知道的某个文件夹中存在的文件。我知道文件名(前缀)在此文件夹中是唯一的。语言是c++。
谢谢
发布于 2012-05-01 04:24:15
假设文件扩展名为"suffix“,您可以这样做:
char * getfilextension(char * fullfilename)
{
int size, index;
size = index = 0;
while(fullfilename[size] != '\0') {
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 != '\0' && start < end) {
*ptr ++ = *p++;
start ++;
}
*ptr++ = '\0';
return buf;
}
char * getfilenamewithoutextension(char * fullfilename)
{
int i, size;
i = size = 0;
while(fullfilename[i] != '\0') {
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 %s\n", 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库的一部分,如果你的编译器上没有这个函数,请告诉我我会为它写一个别名或者使用this实现(别忘了阅读许可证)。
发布于 2012-05-01 04:28:10
如果你使用的是Windows,那就使用PathFindExtension。
发布于 2012-05-01 04:30:28
在c++中没有列出目录内容的标准功能。因此,如果你知道你的应用程序中允许的扩展名,你可以遍历并查找文件是否存在。
其他选项是使用特定于操作系统的API或使用Boost之类的东西。您还可以使用"ls | grep *filename“或"dir”命令转储并解析输出。
https://stackoverflow.com/questions/10389983
复制相似问题