2013-07-31 31 views
0

我要删除的用户登录文件中使用函数库DeleteFile(),我没有得到......如何在C/C++中删除当前用户的文件?

我尝试这样做:

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

也试图捕获用户名像这样:

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

,但不知道把变量name功能DeleteFile()

回答

0

获得用户名后,将包含该字符串的字符串与您关心的其他作品放在一起。我会考虑这个一般顺序的东西:

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()); 
0

从我个人理解,你必须通过用户名到函数的麻烦。 为什么不能简单地做一个新的字符串,并将其传递给函数,像这样:

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); 
1

唯一干净的方式来获取用户的配置文件目录是使用SHGetSpecialFolderPath API与适当CSIDL代码(在你的情况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文件夹查询。)

相关问题