visual如何在C++中将文件保存到桌面
visual 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<<"hellon";
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<<"hellon";
file.close();
return 0;
}
file.open(appData +"/.txt");
在此文件路径中没有文件名。
此外,此函数调用也是无效的。您应该将第二个参数作为开放类型传递。
file.open(appData +"/file.txt", fstream::out);
是正确的。
您应该使用PathAppend来连接路径,这将处理丢失和/或额外的反斜杠()字符集。
我不确定这是否可用:
file.open("%userprofile%\Desktop\file.txt", fstream::out);
你可以试试。
相关文章:
- 无法通过头文件保存变量的值
- 是否有标准的文件保存和交换模式
- C++两次从文件保存对象读取多重继承
- 如何选择文件保存到的位置?
- 如何将文本文件保存到C 中的字符串结构
- 将文件保存到目录C
- 如何在不保存文件的情况下制作打印屏幕并将其发送到FTP服务器?我的工作代码将文件保存到HDD
- 从文件C++保存和读取双向量
- 使用 depend将对象文件保存在相同的生成文件目录中
- 在C++中创建文件时,创建的文件保存在何处
- 在 cab 应用程序卸载时将文件保存在文件夹中
- 读取.txt文件保存在内存中
- 如何将CSV文件保存为UTF-8
- 使用iostream将文件保存在路径
- 在Qt中将文件保存到网络
- 将链表写入 txt 文件(保存过程)
- 在 C++ 中将编辑过的内文件保存到输出文件时出现问题
- 将文件保存在不同的linux位置
- 多线程文件保存操作
- 文件保存期间的进度