visual如何在C++中将文件保存到桌面

visual How to save a file to a Desktop in C++?

本文关键字:文件 保存 桌面 C++ visual      更新时间:2023-10-16

我想找到一种将文件保存到桌面的方法。由于每个用户都有不同的用户名,我发现下面的代码可以帮助我找到其他人桌面的路径。但是如何将以下内容保存到桌面?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);

你可以试试。