CRT 提供 _splitpath(解析)與 _makepath(合成)兩個函數,配合 _MAX_PATH 等常量,能輕鬆拆解/組裝 Windows 路徑。若只需提取文件名/擴展名,std::string 操作更簡潔。
void _splitpath(const char* fullPath,
char* drive, char* dir, char* fname, char* ext);
drive:驅動器 "C:"dir:目錄 "\\sample\\file\\"fname:文件名 "makepath"ext:擴展名 ".c"void _makepath(char* path, const char* drive, const char* dir,
const char* fname, const char* ext);
#include <stdlib.h>
#include <stdio.h>
int main() {
char full[_MAX_PATH], drive[_MAX_DRIVE], dir[_MAX_DIR],
fname[_MAX_FNAME], ext[_MAX_EXT];
_makepath(full, "c", "\\sample\\file\\", "makepath", "c");
printf("Full: %s\n", full); // c:\sample\file\makepath.c
_splitpath(full, drive, dir, fname, ext);
printf("Drive: %s\nDir: %s\nFile: %s\nExt: %s\n",
drive, dir, fname, ext);
return 0;
}
#define _MAX_PATH 260 #define _MAX_DRIVE 3 #define _MAX_DIR 256 #define _MAX_FNAME 256 #define _MAX_EXT 256
#include <string>
#include <algorithm>
#include <iostream>
std::string filePath = "E:\\file\\main.cpp";
std::string ext;
// 擴展名
size_t pos = filePath.find_last_of('.');
if (pos != std::string::npos) {
ext = filePath.substr(pos + 1);
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
}
std::cout << ext << std::endl; // cpp
// 文件名(不含擴展名)
size_t slash = filePath.find_last_of("\\/");
size_t dot = filePath.find_last_of('.');
std::string name = filePath.substr(slash + 1, dot - slash - 1);
_splitpath/_makepath 或 PathCch* 系列(Win8+)。std::filesystem::path 提供 parent_path()、filename()、extension()、stem() 等現代接口,強烈推薦。