可以使用以下代码示例进行清理:
#include
#include
#include
#include
void clear_junk_files(void) {
DIR *dir;
struct dirent *entry;
const char *target_dir = "."; // 改为需要清理的目录
const char *suffix = ".o";
if ((dir = opendir(target_dir)) != NULL) {
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) {
size_t suffix_len = strlen(suffix);
size_t name_len = strlen(entry->d_name);
if (name_len > suffix_len && strcmp(entry->d_name + name_len - suffix_len, suffix) == 0) {
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", target_dir, entry->d_name);
if (remove(path) != 0) {
fprintf(stderr, "Failed to delete the file: %s\n", path);
}
}
}
}
closedir(dir);
} else {
perror("Failed to open the directory");
}
}
示例代码中使用了POSIX标准的opendir
和readdir
函数来读取目录中的文件列表,然后遍历每个文件名,根据后缀名判断是否是需要清理的对象。最后使用remove函数删除文件。需要注意的是,该示例代码中只清理后缀为.o
的文件,如果还需要清理其他垃圾文件,可以修改后缀名或使用更复杂的逻辑来判断是否是要清理的文件。
上一篇:编译C程序的困难