默认将文件写入桌面
Default write file to desktop
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及更高版本)一起使用,或者将SHGetFolderPath
与CSIDL_DESKTOP
一起使用,以获得代表当前用户桌面的文件夹。根据您的Windows版本目标,有几个函数,其中一些已弃用。
只需将标准标头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;
}
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 我无法在 Flutter 桌面嵌入项目(在 Visual Studio 上)中创建 obj 文件
- 在窗口或桌面窗口中单击文件
- 对桌面进行了更改.ini使用批处理文件,但文件夹图标不会更改
- 无法创建或打开 *.VS 2015 中的 VC.db 文件(桌面快速版)更新 3RC
- 如何获取哪些快捷方式和文件在桌面等文件夹路径中突出显示
- 学习C++.正在将文件写入桌面.无处可寻
- 使用winapi从桌面用c++打开一个文件
- 在桌面上创建文件 (C++)
- 将文件拖放到C++WinForms中的桌面图标上
- 将多个文件输出/输入到桌面
- visual如何在C++中将文件保存到桌面
- 您可以将C++桌面应用程序中的输入数据或其他类型的数据存储在文本文件之外的文件中吗
- 具有桌面.ini和即时刷新功能的自定义文件夹图标
- 使用fopen在桌面上打开文件时,权限被拒绝
- SoundCloud桌面应用LibCurl:如何上传文件
- 如何在桌面上的文件夹中创建文本文件
- 默认将文件写入桌面
- 在哪里放置要与Windows用户的桌面设置一起漫游的用户数据文件?