如何在C/C++中删除当前用户的文件
How to delete file of the current user in C/C++?
我想删除用户使用函数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);
相关文章:
- 以非特权用户身份查询 NTFS 特殊文件的元数据?
- 用户输入字符串的文件附加问题..C++
- MAKE:找不到包含的用户定义的头文件?
- 从标准输入读取文件后读取用户输入
- 限制用户可以在 QFileDialog 中选择的文件数量
- 如何在公共头文件中向库的用户公开枚举,同时在内部使用它?
- Windows 后台服务(系统配置文件)无法使用 C++ 访问 win 10 上的用户 appData 文件夹?
- 如何让用户在 tinyxml2 中输入 XML 文件的路径
- Arduino-Makefile:编译器无法编译用户库 cpp 文件
- 将所有 *.txt 文件合并到一个文本文件中,其名称由用户使用 C++ 提供
- 如何在 c++ 中将密码和用户名保存到 .txt 文件中.如果用户尝试登录,我仍然希望能够检索它们
- 尝试将文本文件中的整数替换为用户输入的整数 [C++]
- 尝试读取.txt文件并根据用户输入的字母拉出特定行
- Win7 C++ - 从以用户身份登录的服务启动可执行文件的问题
- 可以将Boost消息队列文件重定向到用户指定的位置
- 在 Win32 应用中,如果未选择文件夹并且用户单击"确定",则文件夹选择对话框将关闭
- 是否可以用类似C/C++(或任何语言)的语言,从作为用户输入的字符串或文件中创建用户定义的数据类型
- 访问QT上的本地用户文件进行Web组件
- C++编程:导航到用户文件以保存每个用户的应用程序数据
- CSIDL常数为用户文件夹为Windows XP