[英]How to save a file to a Desktop in C++?
我想找到一种将文件保存到桌面的方法。 由于每个用户都有不同的用户名,因此我发现以下代码将帮助我找到其他人的桌面的路径。 但是,如何将以下内容保存到桌面? file.open(appData +"/.txt");
不起作用。 你能给我举个例子吗?
#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 ++控制台
更新:
#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
构造路径并从中提取文件的完整路径:
#include <sstream>
...
std::ostringstream file_path;
file_path << appData << "\\filename.txt";
file.open(file_path.str().c_str());
编辑:
以下代码对我来说是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;
}
file.open(appData +"/.txt");
在此文件路径中没有文件名。
同样,此函数调用无效。 您应该将第二个参数作为开放类型传递。
file.open(appData +"/file.txt", fstream::out);
是正确的。
您应该使用PathAppend串联路径,以处理丢失和/或多余的反斜杠( \\
)字符集。
我不确定这是否可用:
file.open("%userprofile%\\\\Desktop\\\\file.txt", fstream::out);
您可以尝试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.