默认将文件写入桌面

Default write file to desktop

本文关键字:桌面 文件 默认      更新时间:2023-10-16

c++中是否有默认代码将文件(.txt)写入桌面,该文件可用于任何不知道前导/桌面的计算机?

最可移植的方法是使用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支持的发行版和操作系统中温和地工作,包括但不限于:

  • Windows

  • Linux

  • Mac

  • QNX-

等等。

SHGetKnownFolderPath与FOLDRID_Desktop(Vista及更高版本)一起使用,或者将SHGetFolderPathCSIDL_DESKTOP一起使用,以获得代表当前用户桌面的文件夹。根据您的Windows版本目标,有几个函数,其中一些已弃用。

只需将标准标头fstreamgetenv:一起使用

#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;
}