如何在C/C++中删除当前用户的文件

How to delete file of the current user in C/C++?

本文关键字:用户 文件 删除 C++      更新时间:2023-10-16

我想删除用户使用函数DeleteFile()库登录的文件,但我没有。。。

我试过这个:

DeleteFile ("c:   users  % username%   file");

还试图捕获这样的用户名:

TCHAR name [UNLEN + 1];
UNLEN DWORD size = + 1;
GetUserName (name, & size);

但不知道要放入变量CCD_ 2函数CCD_。

获取用户配置文件目录的唯一干净方法是使用带有适当CSIDL代码的SHGetSpecialFolderPath API(在您的情况下为CSIDL_profile)。下面是一个简短的(未经测试的)例子:

char the_profile_path[MAX_PATH]; 
if (SHGetSpecialFolderPath(NULL, the_profile_path, CSIDL_PROFILE, FALSE) == FALSE) 
{
    cerr << "Could not find profile path!" << endl;
    return;
}
std::ostringstream the_file;
buffer << the_profile_path << "\file";
if (DeleteFile(buffer.c_str()) == TRUE)
{
    cout << buffer << " deleted" << endl;
}
else
{
    cout << buffer << " could not be deleted, LastError=" << GetLastError() << endl;
}

任何其他"构建"用户配置文件路径或Windows的任何其他特殊文件夹的方法都可能导致严重的问题。例如,如果配置文件的位置在未来版本中发生变化(就像在Windows XP和Vista之间发生的那样),或者路径的某些部分依赖于语言(我认为从Vista开始就不应该是问题了),或者用户重新定位配置文件(在管理环境中可能是问题,等等),会降低应用程序的可移植性

还请注意,您应该为应用程序创建文件的位置不是配置文件的根路径,而是AppData或LocalAppData(两者都可以使用适当的CSIDL查询)文件夹。

获得用户名后,将包含用户名的字符串与您关心的其他部分放在一起。我会考虑这个通用订单上的一些东西:

TCHAR name [UNLEN + 1];
DWORD size = UNLEN+1;
GetUserName(name, &size);
std::ostringstream buffer;
buffer << "C:\users\" << user_name << "\file";
DeleteFile(buffer.str().c_str());

据我所知,您很难将用户名传递给函数。为什么不简单地制作一个新字符串并将其传递给函数,如下所示:

TCHAR name [UNLEN + 1];
UNLEN DWORD size = + 1;
GetUserName (name, & size);
TCHAR path [MAX_PATH + 1] = "c:   users  ";
strcat(path, name);
strcat(path,"  file");
DeleteFile (path);