本文部分转载https://www.cnblogs.com/lisuyun/archive/2013/10/31/3399232.html感谢博主
最简单的提取文件后缀名的方法,调用stdlib的函数;
_splitpath
需要的头文件是:<stdlib.h>
函数原型如下
void _splitpath( const char *path, char *drive, char *dir, char *fname, char *ext);
其中包含5个参数,第一个是待处理的完整的文件名路径,例如:“c:\windows\myfile.txt”,当然这个文件名也可以不是那么完整,即使是"myfile.txt"这样的字符串也可以成功处理。
后面四个参数分别代表四个需要从原始文件路径中截取的字符串,有驱动器盘符(drive),中间的路径(dir),文件名(fname),和后缀名(ext)。
只要在这四个参数中传入对应的字符串指针,函数返回时即可获取对应截取的字符串,不想获取的可以直接填入NULL进行忽略,比如我只想截取文件的后缀名,那么这个函数可以如下调用:
_splitpath(path, NULL, NULL, NULL, ext);
其中ext必须是已经分配了内存空间的字符串指针,否则会出错(c语言的基本特性,我就不赘述了)
使用范例:
/* MAKEPATH.C */
#include <stdlib.h>
#include <stdio.h>
void main( void )
{
char path_buffer[_MAX_PATH];
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
_makepath( path_buffer, "c", "\\sample\\crt\\", "makepath", "c" );
printf( "Path created with _makepath: %s\n\n", path_buffer );
_splitpath( path_buffer, drive, dir, fname, ext );
printf( "Path extracted with _splitpath:\n" );
printf( " Drive: %s\n", drive );
printf( " Dir: %s\n", dir );
printf( " Filename: %s\n", fname );
printf( " Ext: %s\n", ext );
}
这里面的ext数组存放的即为文件后缀名;
于是对绿色计算模拟赛一阶段的第3题写了一发(没看头文件),还是不能用,仅当参考吧。
#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <shlwapi.h>
using namespace std;
#define max(x, y) x >= y ? x : y
#define min(x, y) x <= y ? x : y
#define INF 0x3f3f3f3f
typedef struct dirent dirent;
void showDirStructure(char *folderPath)
{
static int flor = 0; //²ãÊý
for (int i = 0; i < flor*2; i++) cout << " "; //Êä³öÇ°Öÿոñ
char buf[256];
int len = 0;
for (int i = strlen(folderPath)-1; folderPath[i] != '/'; i--) buf[len++] = folderPath[i];
buf[len] = '\0';
for (int i = 0; i < len/2; i++) {
char t = buf[i];
buf[i] = buf[len-1-i];
buf[len-1-i] = t;
}
cout << "+--" << buf << endl;
DIR *dir = opendir(folderPath);
struct dirent *i = NULL;
while ((i = readdir(dir)) != NULL) {
if (!strcmp(i->d_name, ".") || !strcmp(i->d_name, "..")) continue;
strcpy(buf, folderPath);
strcat(buf, "/");
strcat(buf, i->d_name);
struct stat M;
stat(buf, &M);
if (S_ISDIR(M.st_mode))
{
flor += 1;
showDirStructure(buf);
flor -= 1;
}
else
{
char ext[_MAX_EXT];
_splitpath(buf, NULL, NULL, NULL, ext);
if (!strcmp(ext, ".jpg") || !strcmp(ext, ".png") || !strcmp(ext, ".bmp")) {
for (int j = 0; j < (flor+1)*2; j++) cout << " ";
cout << "--" << i->d_name << endl;
}
}
}
closedir(dir);
}
int main()
{
char *file = "C:/Users/Administrator/Downloads/step3Dir/root";
showDirStructure(file);
return 0;
}