C 語言 remove() 函數返回 -1 表示刪除失敗,且 errno 會被設定。許多開發者確認路徑無誤卻仍失敗,往往忽略了權限、檔案鎖定、工作目錄等隱性因素。本文提供系統性排查清單。
#include <stdio.h>
#include <errno.h>
#include <string.h>
if (remove("test.txt") == -1) {
printf("刪除失敗: %s (errno=%d)\n", strerror(errno), errno);
}
| errno | 宏定義 | 常見原因 |
|---|---|---|
| 13 | EACCES | 權限不足、檔案唯讀、目錄無寫入權限 |
| 2 | ENOENT | 檔案不存在(路徑錯誤、相對路徑陷阱) |
| 16 | EBUSY | 檔案被其他進程開啟/鎖定(Windows 常見) |
| 21 | EISDIR | 路徑指向目錄而非檔案 |
| 30 | EROFS | 檔案系統唯讀 |
fclose() 中被開啟Resource Monitor → CPU → Associated Handles 搜尋檔名fopen 必配對 fclose,異常路徑也要 fcloseDebug/)GetModuleFileName / getcwd 確認實際工作目錄_fullpath 轉換remove() 只能刪檔案,目錄需用 rmdir() (Windows) / remove() 遞迴 (POSIX)int safe_remove(const char *path) {
struct stat st;
if (stat(path, &st) != 0) return -1; // 不存在
if (S_ISDIR(st.st_mode)) {
#ifdef _WIN32
return _rmdir(path);
#else
// 遞迴刪除目錄內容...
return rmdir(path);
#endif
} else {
return remove(path);
}
}
access(path, W_OK) 檢查寫入權限strerror(errno) 而非只看 -1_wremove(L"path") 支援 Unicode 路徑remove() 返回 -1 多半是 檔案被佔用 (EBUSY) 或 權限不足 (EACCES)。務必檢查 errno、確認絕對路徑、以管理員權限測試、確保所有檔案控制代碼已關閉。Windows 開發者特別注意防毒軟體即時掃描造成的短暫鎖定。