C
페이지 정보

본문
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#define TARGET_DIR "./target_folder" // 対象フォルダのパス
int is_regular_file(const char *path) {
struct stat path_stat;
if (stat(path, &path_stat) != 0) {
return 0;
}
return S_ISREG(path_stat.st_mode);
}
int main() {
DIR *dir;
struct dirent *entry;
char filepath[1024];
int file_found = 0;
dir = opendir(TARGET_DIR);
if (!dir) {
perror("ディレクトリオープン失敗");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
// "." と ".." は無視
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
snprintf(filepath, sizeof(filepath), "%s/%s", TARGET_DIR, entry->d_name);
if (is_regular_file(filepath)) {
file_found = 1;
if (remove(filepath) != 0) {
perror("削除失敗");
closedir(dir);
return 1;
}
}
}
closedir(dir);
printf("完了: %s\n", file_found ? "ファイルを削除しました" : "ファイルは存在しませんでした");
return 0;
}
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#define TARGET_DIR "./target_folder" // 対象フォルダのパス
int is_regular_file(const char *path) {
struct stat path_stat;
if (stat(path, &path_stat) != 0) {
return 0;
}
return S_ISREG(path_stat.st_mode);
}
int main() {
DIR *dir;
struct dirent *entry;
char filepath[1024];
int file_found = 0;
dir = opendir(TARGET_DIR);
if (!dir) {
perror("ディレクトリオープン失敗");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
// "." と ".." は無視
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
snprintf(filepath, sizeof(filepath), "%s/%s", TARGET_DIR, entry->d_name);
if (is_regular_file(filepath)) {
file_found = 1;
if (remove(filepath) != 0) {
perror("削除失敗");
closedir(dir);
return 1;
}
}
}
closedir(dir);
printf("完了: %s\n", file_found ? "ファイルを削除しました" : "ファイルは存在しませんでした");
return 0;
}
댓글목록
등록된 댓글이 없습니다.