Tim
Tim

Reputation: 11

Default write file to desktop

Is there a default code in c++ to write a file(.txt) to a desktop, which could be used for any computer without knowing the leading /desktop?

Upvotes: 1

Views: 880

Answers (3)

AntiClimacus
AntiClimacus

Reputation: 1420

Just use standard header fstream with 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;
}

Upvotes: 0

L&#225;szl&#243; Papp
L&#225;szl&#243; Papp

Reputation: 53185

The most portable way is to use Qt, namely QStandardPaths.

The standard library does not have any off-hand support for it, so you will either need to reinvent the wheel or find a robust solution that already exists. Qt is such a thing.

QStandardPaths::DesktopLocation 0 Returns the user's desktop directory.

In which case, you could use QFile as well as ofstream to write the file to that folder. You would only need to depend on QtCore for this.

The code would look like this:

#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!

This will gently work across distributions and operating systems that QtCore supports, including, but limited to:

  • Windows

  • Linux

  • Mac

  • QNX

and so forth.

Upvotes: 3

imbtfab
imbtfab

Reputation: 493

Use SHGetKnownFolderPath with FOLDERID_Desktop (Vista and later), alternatively SHGetFolderPath with CSIDL_DESKTOP to obtain the folder that represents the desktop for the current user. Depends on your Windows version targets, there's several functions, and some of them deprecated.

Upvotes: 0

Related Questions