remove 函數用法詳解#includeint remove(const char *filename);
0,失敗返回非零值(並設置 errno)。#includeint main() { char filename[256]; printf("Please input a file to delete: "); if (scanf("%255s", filename) != 1) return -1; if (remove(filename) == 0) { printf("OK: File '%s' deleted.\n", filename); } else { perror("Could not delete the file"); } return 0; }
remove **不能**刪除非空目錄,需遞歸刪除內容後用 rmdir。remove("*.tmp") 無效,需自行遍歷匹配文件逐個刪除。#include#include #include #include int remove_recursive(const char *path) { struct stat st; if (stat(path, &st) != 0) return -1; if (S_ISDIR(st.st_mode)) { DIR *d = opendir(path); if (!d) return -1; struct dirent *entry; char subpath[1024]; while ((entry = readdir(d))) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; snprintf(subpath, sizeof(subpath), "%s/%s", path, entry->d_name); if (remove_recursive(subpath) != 0) { closedir(d); return -1; } } closedir(d); return rmdir(path); } else { return remove(path); } }
remove 是 C 標準庫刪除文件的唯一標準函數,簡單易用。掌握其返回值判斷、errno 錯誤碼分析(EACCES、ENOENT、EPERM 等),並注意跨平台差異(特別是文件佔用行為),即可可靠實現文件刪除功能。