我想找到一種方法將文件保存到桌面。由於每個用戶都有不同的用戶名,我發現下面的代碼會幫助我找到別人桌面的路徑。但是,我怎樣才能將以下內容保存到桌面? file.open(appData +"/.txt");
不起作用。你能告訴我一個例子嗎?如何將文件保存到C++的桌面?
#include <iostream>
#include <windows.h>
#include <fstream>
#include <direct.h>
#include <shlobj.h>
using namespace std;
int main()
{
ofstream file;
TCHAR appData[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL,
CSIDL_DESKTOPDIRECTORY | CSIDL_FLAG_CREATE,
NULL,
SHGFP_TYPE_CURRENT,
appData)))
wcout << appData << endl; //This will printout the desktop path correctly, but
file.open(appData +"file.txt"); //this doesn't work
file<<"hello\n";
file.close();
return 0;
}
微軟的Visual Studio 2010,Windows 7中,C++控制檯
更新:
#include <iostream>
#include <windows.h>
#include <fstream>
#include <direct.h>
#include <shlobj.h>
#include <sstream>
using namespace std;
int main()
{
ofstream file;
TCHAR appData[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL,
CSIDL_DESKTOPDIRECTORY | CSIDL_FLAG_CREATE,
NULL,
SHGFP_TYPE_CURRENT,
appData)))
wcout << appData << endl; //This will printout the desktop path correctly, but
std::ostringstream file_path;
file_path << appData << "\\filename.txt";//Error: identifier file_path is undefined
file.open(file_path.str().c_str()); //Error:too few arguments in function call
return 0;
}
Windows路徑與'\\'否?而且您還需要該文件的名稱。 – Tudor 2012-02-16 11:09:50
我想你正在添加兩個字符指針。你想連接字符串。建議使用一個stringstream,並將其推入到它?另外,你實際上似乎沒有在文件名中加上.txt擴展名。最近沒有使用過Windows,但是不會在這方面做些什麼? – BoBTFish 2012-02-16 11:11:36
@Tudor即使在Windows上,C++和C也可以使用'/'作爲目錄分隔符!儘管你對文件名稱是正確的,'.txt'是一個糟糕的名字。 – 2012-02-16 11:14:23