首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 語言刪除文件:remove 函數用法詳解

     編輯:關於C語言

C 語言刪除文件:remove 函數用法詳解

函數原型

#include 
int remove(const char *filename);
  • 參數:文件路徑(相對或絕對)。
  • 返回值:成功返回 0,失敗返回非零值(並設置 errno)。
  • 行為:刪除文件,使其不可訪問。若文件被其他進程打開,行為取決於操作系統(Windows 通常失敗,Linux 允許刪除但磁盤空間不釋放直到所有句柄關閉)。

完整示例:交互式刪除文件

#include 

int 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;
}

常見錯誤與注意事項

  • 路徑錯誤:確保路徑正確,相對路徑基於進程工作目錄。
  • 權限不足:需對文件所在目錄有寫入/執行權限,對文件本身有刪除權限(Windows 需檢查 ACL,Linux 需檢查目錄寫權限)。
  • 文件被佔用:Windows 下文件被打開時無法刪除;Linux 下可刪除但實體不釋放。
  • 非空目錄: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 等),並注意跨平台差異(特別是文件佔用行為),即可可靠實現文件刪除功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved