问题描述
我想找到一种将文件保存到桌面的方法.由于每个用户都有不同的用户名,我发现以下代码可以帮助我找到其他人桌面的路径.但是如何将以下内容保存到桌面?file.open(appData +"/.txt");
不起作用.你能给我举个例子吗?
I want to find a way to save a file to a desktop. Since every user has different user name, I found following code will help me find the path to someone else’s desktop. But how can I save the following to desktop? file.open(appData +"/.txt");
doesn't work. Can you please show me an example?
#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;
}
Microsoft Visual Studio 2010、Windows 7、C++ 控制台
Microsoft Visual Studio 2010, Windows 7, C++ console
更新:
#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;
}
推荐答案
您不能使用 appData +"/.txt"
连接 TCHAR
数组.使用 stringstream
构造路径并从中提取文件的完整路径:
You cannot concatenate TCHAR
array using appData +"/.txt"
. Use a stringstream
to construct the path and extract the full path of the file from it:
#include <sstream>
...
std::ostringstream file_path;
file_path << appData << "\\filename.txt";
file.open(file_path.str().c_str());
对于我使用 VS2010,以下编译并正确执行:
The following compiles, and executes correctly, for me with VS2010:
#include <iostream>
#include <windows.h>
#include <fstream>
#include <direct.h>
#include <shlobj.h>
#include <sstream>
#include <tchar.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;
std::basic_ostringstream<TCHAR> file_path;
file_path << appData << _TEXT("\\filename.txt");
file.open(file_path.str().c_str());
file<<"hello\n";
file.close();
return 0;
}
这篇关于如何在 C++ 中将文件保存到桌面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!