首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C/C++ 文件路徑解析與合成:_splitpath / _makepath 與 std::string 實現

     編輯:關於C++

CRT 提供 _splitpath(解析)與 _makepath(合成)兩個函數,配合 _MAX_PATH 等常量,能輕鬆拆解/組裝 Windows 路徑。若只需提取文件名/擴展名,std::string 操作更簡潔。

一、_splitpath 解析路徑

void _splitpath(const char* fullPath,
                char* drive, char* dir, char* fname, char* ext);
  • drive:驅動器 "C:"
  • dir:目錄 "\\sample\\file\\"
  • fname:文件名 "makepath"
  • ext:擴展名 ".c"

二、_makepath 合成路徑

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

五、std::string 輕量提取文件名/擴展名

#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);

六、跨平台建議

  • Windows 專用:_splitpath/_makepath 或 PathCch* 系列(Win8+)。
  • C++17 跨平台:std::filesystem::path 提供 parent_path()、filename()、extension()、stem() 等現代接口,強烈推薦。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved