c ++中是否有默认代码将文件(.txt)写入桌面,可以在不知道领先/桌面的情况下用于任何计算机?
答案 0 :(得分:3)
最便携的方式是使用Qt,即QStandardPaths。
标准库没有任何副手支持,因此您需要重新发明轮子或找到已存在的强大解决方案。 Qt就是这样。
QStandardPaths :: DesktopLocation 0返回用户的桌面目录。
在这种情况下,您可以使用QFile
以及ofstream将文件写入该文件夹。您只需依赖QtCore
即可。
代码如下所示:
#include <QFile>
#include <QStandardPaths>
#include <QDebug>
#include <QTextStream>
...
QFile file(QStandardPaths::locate(QStandardPaths::DesktopLocation, ""));
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
qDebug() << "Failed to open";
QTextStream out(&file);
// Done, yay!
这将适用于QtCore支持的发行版和操作系统,包括但不限于:
窗
Linux的
的Mac
QNX
等等。
答案 1 :(得分:0)
只需使用标准标题fstream
和getenv
:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <sstream>
using namespace std;
int main (int argc, char **argv)
{
if(argc != 2)
{
cerr << "usage: " << argv[0] << " filename" << endl;
return 1;
}
std::ostringstream oss;
#ifdef _WIN32
oss << getenv("HOMEDRIVE") << getenev("HOMEPATH");
#else
oss << getenv("HOME");
#endif
oss << "/" << argv[1];
ofstream f;
f.open (oss.str().c_str());
f << "bar";
f.close();
return 0;
}
答案 2 :(得分:0)
将SHGetKnownFolderPath
与FOLDERID_Desktop(Vista及更高版本)一起使用,或SHGetFolderPath
与CSIDL_DESKTOP
一起使用,以获取代表当前用户桌面的文件夹。取决于您的Windows版本目标,有几个功能,其中一些已弃用。