我正在编写一些代码,它应该做的是将路径返回到没有文件名本身的文件。这是
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
int main() {
char binaryPath[MAX_PATH]; //I think my problems stem from the fact that
//isnt truly a string
GetModuleFileName(NULL, binaryPath, MAX_PATH); //Get filename
string i = (string) binaryPath;
string fileDir = "";
int tempSlashes = 0;
for (int x = 0; x < strlen(binaryPath); x++) {
if (i[x] == '\\') { //In eclipse CDT this gives warning 1 (below)
tempSlashes++;
}
}
for (int y = 0; y < tempSlashes; y++) {
fileDir.append(binaryPath[y]); //Line gives warning 2
}
cout << fileDir;
return 0;
}
无论如何,小警告注释
Error 1:
Multiple markers at this line
- comparison with string literal results in unspecified behaviour [-
Waddress]
- ISO C++ forbids comparison between pointer and integer [-
fpermissive]
Error 2:
Multiple markers at this line
- Invalid arguments ' Candidates are: std::basic_string<char,std::char_traits<char>,std::allocator<char>> & append(const
std::basic_string<char,std::char_traits<char>,std::allocator<char>> &) std::basic_string<char,std::char_traits<char>,std::allocator<char>> & append(const
std::basic_string<char,std::char_traits<char>,std::allocator<char>> &, unsigned int, unsigned int) std::basic_string<char,std::char_traits<char>,std::allocator<char>> & append(const
char *, unsigned int) std::basic_string<char,std::char_traits<char>,std::allocator<char>> & append(const char *) std::basic_string<char,std::char_traits<char>,std::allocator<char>> &
append(unsigned int, char) std::basic_string<char,std::char_traits<char>,std::allocator<char>> & append(#10000, #10000) '
- invalid conversion from 'char' to 'const char*' [-fpermissive]
程序本身拒绝编译,并运行早期的.exe
我不确定我在这里做错了什么,帮助(以及解释)会非常好。
谢谢!
答案 0 :(得分:2)
我建议向后迭代并寻找&#39; \&#39;。类似的东西:
int len = strlen(binaryPath);
char outPath[MAX_PATH];
strcpy(outPath, binaryPath);
for (int x = len - 1; x >= 0; --x) {
outPath[x] = 0;
if (binaryPath[x] == '\\') {
break;
}
}
答案 1 :(得分:1)
首先,在现代的Win32 C ++代码中,您可能希望使用 Unicode 而不是ANSI / MBCS(因此,wchar_t
代替char
和std::wstring
而不是std::string
)。
对于您的特定问题,您可能希望使用现有的Win32 API:PathRemoveFileSpec()。
以下是可编辑的示例代码:
#define UNICODE
#define _UNICODE
#include <iostream>
#include <string>
#include <Windows.h>
#include <Shlwapi.h>
using namespace std;
#pragma comment(lib, "Shlwapi.lib")
int main()
{
wchar_t binaryPath[MAX_PATH];
GetModuleFileName(nullptr, binaryPath, MAX_PATH);
PathRemoveFileSpec(binaryPath);
// You can assign to a std::wstring as well...
wstring fileDir = binaryPath;
wcout << fileDir << endl;
}
以下是一个示例测试:
C:\Temp\CppTests>cl /EHsc /W4 /nologo /MTd test.cpp test.cpp C:\Temp\CppTests>test.exe C:\Temp\CppTests
作为替代方案,一旦在原始C缓冲区中读取了文件名的完整路径:
wchar_t binaryPathBuffer[MAX_PATH];
GetModuleFileName(nullptr, binaryPathBuffer, MAX_PATH);
您可以将其复制到std::wstring
,然后使用其 rfind()
方法查找上一个'\'
的位置,然后提取正确的使用substr
std::wstring
方法的子字符串
wstring binaryPath = binaryPathBuffer;
size_t last = binaryPath.rfind(L'\\');
wstring fileDir = binaryPath.substr(0, last);