c++传入string文件路径获取文件后缀
时间: 2024-08-19 09:00:43 浏览: 25
在C++中,你可以使用`find_last_of()`函数找到文件扩展名的最后一个`.`字符的位置,然后通过`substr()`或`erase()`方法来获取文件后缀。这里有几个示例:
1. 使用`substr()`方法[^1]:
```cpp
// 假设你有一个字符串变量file_path存储文件路径
std::string file_path = "example.txt";
std::string fileType = file_path.substr(file_path.find_last_of(".") + 1);
```
这会返回".txt"。
2. 如果你不希望包括`.`在内,可以这样简化:
```cpp
fileType = file_path.substr(file_path.find_last_of(".") + 1, file_path.length() - (file_path.find_last_of(".") + 1));
```
3. 或者直接使用`erase()`方法去掉前面的部分:
```cpp
fileType = file_path.erase(0, file_path.find_last_of(".") + 1);
```
这都将从找到`.`后的下一个字符开始截取到字符串结束,得到文件后缀。
相关问题
c++读取文件 中文路径
在 C++ 中,可以使用以下代码读取中文路径的文件:
```c++
#include <fstream>
#include <iostream>
#include <locale>
#include <codecvt>
int main() {
// 设置本地化
std::locale::global(std::locale(""));
// 打开文件
std::wifstream fin(L"文件路径");
// 设置字符集转换
fin.imbue(std::locale(std::locale(), new std::codecvt_utf8_utf16<wchar_t>));
// 读取文件内容
std::wstring line;
while (std::getline(fin, line)) {
std::wcout << line << std::endl;
}
// 关闭文件
fin.close();
return 0;
}
```
其中,`std::locale::global(std::locale(""))`是设置本地化,`std::wifstream`是以 Unicode 编码方式读取文件,`std::codecvt_utf8_utf16`是字符集转换器,将 UTF-8 编码转换成 UTF-16 编码。
c++文件拖动读取路径
以下是使用 C 语言在 Windows 平台下实现文件拖动读取路径的示例代码:
```c
#include <stdio.h>
#include <windows.h>
int main(int argc, char *argv[])
{
if (argc == 1)
{
// 如果没有命令行参数,则等待用户拖动文件到程序图标上
HINSTANCE hInstance = GetModuleHandle(NULL);
if (hInstance != NULL)
{
LPWSTR lpCmdLine = GetCommandLineW();
int nArgs;
LPWSTR* szArglist = CommandLineToArgvW(lpCmdLine, &nArgs);
if (szArglist != NULL && nArgs > 1)
{
// 从命令行参数中获取文件路径
WCHAR* szFile = szArglist[1];
char szPath[MAX_PATH];
WideCharToMultiByte(CP_UTF8, 0, szFile, -1, szPath, MAX_PATH, NULL, NULL);
printf("File path: %s\n", szPath);
LocalFree(szArglist);
return 0;
}
else
{
printf("Please drag and drop a file onto the program icon.\n");
getchar();
return 1;
}
}
}
else if (argc > 1)
{
// 从命令行参数中获取文件路径
printf("File path: %s\n", argv[1]);
return 0;
}
return 1;
}
```
在上述代码中,如果程序没有命令行参数,则等待用户拖动文件到程序图标上。在 Windows 平台下,当用户拖动一个或多个文件到程序图标时,系统会自动将文件路径作为命令行参数传递给程序。
为了获取文件路径,我们需要先获取命令行参数,并从中提取第一个参数即为文件路径。在 Windows 下,命令行参数是以 Unicode 编码的字符串形式传递的,我们需要将其转换为 UTF-8 编码的字符串才能在控制台中输出。
如果程序有命令行参数,则直接从命令行参数中获取文件路径。
需要注意的是,Windows 平台下的文件路径是以 Unicode 编码形式表示的,而 C 语言默认使用的是 ASCII 编码,因此需要进行编码转换。在上述代码中,我们使用了 Windows API 中的 WideCharToMultiByte 函数将 Unicode 编码的字符串转换为 UTF-8 编码的字符串。