Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Hàm remove() xóa file trong C/C++

Hàm remove() trong thư viện C (<cstdio> hoặc <stdio.h>) dùng để xóa file khỏi hệ thống tệp.

Cú pháp


int remove(const char* filename);

Tham số & Giá trị trả về

  • filename: Đường dẫn file cần xóa (chuỗi C-string)
  • Trả về 0: Thành công
  • Trả về -1: Thất bại (set errno)

Ví dụ: Tạo file rồi xóa

#include <cstdio>
#include <cstring>

int main() {
    const char* filename = "file.txt";
    FILE* fp;
    
    // 1. Tạo file và ghi dữ liệu
    fp = fopen(filename, "w");
    if (!fp) {
        perror("Khong the tao file");
        return 1;
    }
    fprintf(fp, "%s", "Day la noi dung file");
    fclose(fp);
    
    // 2. Xóa file
    int ret = remove(filename);
    
    if (ret == 0) {
        printf("File da duoc xoa thanh cong\n");
    } else {
        perror("Loi xoa file");
    }
    
    return 0;
}

Kết quả

File da duoc xoa thanh cong

Lưu ý quan trọng

  • File phải không đang được mở bởi tiến trình nào (kể cả chính chương trình)
  • Trên Windows: Không xóa được file đang mở. Trên Linux: Có thể xóa, nhưng không gian đĩa chỉ giải phóng khi file handle đóng
  • Cần quyền ghi trên thư mục chứa file
  • Không có thùng rác (Recycle Bin) - xóa vĩnh viễn

Xử lý lỗi chi tiết


#include <cerrno>
#include <cstring>

int ret = remove("file.txt");
if (ret != 0) {
    switch (errno) {
        case ENOENT:  printf("File khong ton tai\n"); break;
        case EACCES:  printf("Khong co quyen xoa\n"); break;
        case EPERM:   printf("File read-only hoac dang dung\n"); break;
        default:      printf("Loi khac: %s\n", strerror(errno));
    }
}

C++17: std::filesystem::remove (Khuyến nghị)


#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    fs::path path = "file.txt";
    
    if (fs::exists(path)) {
        std::error_code ec;
        bool removed = fs::remove(path, ec);
        
        if (removed) {
            std::cout << "Da xoa: " << path << std::endl;
        } else {
            std::cout << "Loi: " << ec.message() << std::endl;
        }
    } else {
        std::cout << "File khong ton tai" << std::endl;
    }
}

Ưu điểm std::filesystem::remove

  • Cross-platform (Windows/Linux/macOS)
  • Type-safe với fs::path
  • Xử lý lỗi tốt với std::error_code
  • Hỗ trợ xóa thư mục rỗng

Tóm tắt

  • C-style: remove(const char*) từ <cstdio>
  • C++17: std::filesystem::remove (khuyến nghị)
  • Luôn kiểm tra kết quả trả về
  • File xóa không thể khôi phục