I want to get the suffix(.txt,.png etc.) of a file that I know that exists in some folder. I know that the file name(prefix) is unique in this folder. The language is c++.
thanks
I want to get the suffix(.txt,.png etc.) of a file that I know that exists in some folder. I know that the file name(prefix) is unique in this folder. The language is c++.
thanks
假设“后缀”是文件扩展名,您可以这样做:
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 库的一部分,如果您的编译器上没有此函数,请告诉我,我将为它写一个别名或使用此实现(不要忘记阅读许可证) .
如果您使用的是 Windows,请使用PathFindExtension。
在 C++ 中没有列出目录内容的标准功能。因此,如果您知道应用程序中允许的扩展名,您可以遍历并查找文件是否存在。
其他选项是使用操作系统特定的 API 或使用类似 Boost 的东西。您还可以使用“ls | grep *filename”或“dir”命令转储并解析输出。