我不知道這裏發生了什麼。這裏是代碼示例:CPP中的「SetCurrentDirectory」(「windows.h」)中的一些不理解的東西
#include<stdio.h>
#include<iostream>
#include<string>
#include <Windows.h>
using namespace std;
int main()
{
char my_current_path[1024];
string current_path(R"(C:)");
if (!SetCurrentDirectory(current_path.c_str()))
cout << "cant change to that directory.";
GetCurrentDirectory(1024, my_current_path);
std::cout << my_current_path << endl;
system("pause");
return 1;
}
我在這裏做的是試圖將目錄更改爲某些目錄。
我的代碼有兩件奇怪的事情。
(1奇怪的事情)
當我嘗試更改爲 「c:」 這樣的:
#include<stdio.h>
#include<iostream>
#include<string>
#include <Windows.h>
using namespace std;
int main()
{
char my_current_path[1024];
string current_path(R"(C:)");
if (!SetCurrentDirectory(current_path.c_str()))
cout << "cant change to that directory.";
GetCurrentDirectory(1024, my_current_path);
std::cout << my_current_path << endl;
system("pause");
return 1;
}
它不工作,不改變路徑(和它的好事。 )但它不顯示當目錄沒有改變時顯示的消息:
cout << "cant change to that directory.";
這是爲什麼? (當我嘗試改變像「efef:」或「存在」之類的東西時,它顯示我是messege。但是爲什麼在這裏它不顯示我,並且還嘗試更改當前的工作目錄?
奇怪的事情)
當我目錄更改爲「G:」它由於某種原因,工作..
#include<stdio.h>
#include<iostream>
#include<string>
#include <Windows.h>
using namespace std;
int main()
{
char my_current_path[1024];
string current_path(R"(G:)");
if (!SetCurrentDirectory(current_path.c_str()))
cout << "cant change to that directory.";
GetCurrentDirectory(1024, my_current_path);
std::cout << my_current_path << endl;
system("pause");
return 1;
}
該代碼編譯,表明我成功地改變了目錄,以「G」。 改變到那條路徑之後,我試圖改變爲「C:」(之前沒有做任何事情),現在它工作!但奇怪的是,它不是移動到「C:\」但到:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE
而且它怪異的,以前它沒有工作,現在當我在「G:」路徑,並試圖轉移到「c:」再次,然後它走向我不想要的路徑!
'如果函數失敗,則返回值爲零。要獲得擴展的錯誤信息,請調用GetLastError.'因此,添加一些錯誤檢查,以便知道它爲什麼失敗。 –
爲什麼'「(C :)」'你只能'「C:\\」' – Raindrop7
@RetiredNinja它沒有改變目錄,但沒有進入if(有一個如果案件它返回零 –