用c++隐藏文件不写路径行吗?
时间: 2024-03-21 18:42:18 浏览: 12
不行,您必须提供文件的完整路径才能隐藏文件。如果您不知道文件的完整路径,您需要使用其他方法来查找文件的路径。例如,您可以使用 `FindFirstFile` 和 `FindNextFile` 函数来遍历文件系统以查找文件,并使用文件名构建文件的完整路径。
以下是一个示例代码,它可以遍历指定目录下的所有文件,并隐藏指定的文件:
```c++
#include <iostream>
#include <windows.h>
#include <string>
void hideFile(const std::string& file_path) {
if (SetFileAttributes(file_path.c_str(), FILE_ATTRIBUTE_HIDDEN)) {
std::cout << "File hidden successfully: " << file_path << std::endl;
} else {
std::cout << "Error hiding file: " << file_path << std::endl;
}
}
void traverseDirectory(const std::string& dir_path, const std::string& file_name) {
std::string search_path = dir_path + "\\*.*";
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd);
if (hFind != INVALID_HANDLE_VALUE) {
do {
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (strcmp(fd.cFileName, ".") != 0 && strcmp(fd.cFileName, "..") != 0) {
std::string subdir_path = dir_path + "\\" + fd.cFileName;
traverseDirectory(subdir_path, file_name);
}
} else {
std::string file_path = dir_path + "\\" + fd.cFileName;
if (file_name == fd.cFileName) {
hideFile(file_path);
}
}
} while (::FindNextFile(hFind, &fd));
::FindClose(hFind);
}
}
int main() {
std::string dir_path = "C:\\Users\\user\\Desktop";
std::string file_name = "example.txt";
traverseDirectory(dir_path, file_name);
return 0;
}
```
在上面的示例中,`traverseDirectory` 函数递归地遍历指定目录下的所有文件和子目录,并调用 `hideFile` 函数来隐藏指定的文件。您需要将 `dir_path` 更改为您要遍历的目录的路径,将 `file_name` 更改为要隐藏的文件的名称。请注意,您需要对此程序使用管理员权限才能成功隐藏文件。