std::remove (Header <cstdio> / <stdio.h>) ใช้สำหรับ ลบไฟล์ ออกจาก Filesystem ทำให้เข้าถึงไม่ได้อีกต่อไป
ลายเซ็น
int remove(const char* filename);
- คืนค่า
0= สำเร็จ - คืนค่า
-1= ล้มเหลว (ตั้งค่าerrno)
ตัวอย่าง: สร้างไฟล์ แล้วลบ
#include <cstdio>
#include <cstring>
#include <iostream>
int main() {
const char* filename = "temp_file.txt";
// 1. สร้างไฟล์ทดสอบ
FILE* fp = std::fopen(filename, "w");
if (!fp) {
std::cerr << "Cannot create file\n";
return 1;
}
std::fprintf(fp, "This is test content for removal.\n");
std::fclose(fp);
std::cout << "File created.\n";
// 2. ลบไฟล์
int ret = std::remove(filename);
if (ret == 0) {
std::cout << "File deleted successfully\n";
} else {
std::perror("Error deleting file"); // พิมพ์ Error Message จาก errno
}
return 0;
}
ผลลัพธ์
File created.
File deleted successfully
ข้อระวังและข้อจำกัด
- ไฟล์เปิดอยู่: บน Windows ไม่สามารถลบไฟล์ที่ถูก Process อื่นเปิดอยู่ได้ (Linux ได้ แต่ Inode ยังคงอยู่จนปิด)
- Directory:
removeไม่ลบ Directory (ใช้rmdirหรือstd::filesystem::remove_all) - Permissions: ต้องมี Write Permission บน Directory ที่เก็บไฟล์
- Race Condition: ระหว่าง Check Existence และ Remove ไฟล์อาจหายไป/ถูกสร้างใหม่
Modern C++: std::filesystem::remove (C++17)
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::path path = "temp_file.txt";
// สร้างไฟล์
std::ofstream(path) << "content";
// ลบ (คืน bool, โยน Exception ได้)
try {
bool removed = fs::remove(path);
std::cout << (removed ? "Deleted" : "Not found") << '\n';
} catch (const fs::filesystem_error& e) {
std::cerr << "Error: " << e.what() << '\n';
}
}
สรุป
std::remove เป็น C-style File Deletion ใช้งานง่ายแต่ Error Handling ผ่าน errno C++17 std::filesystem::remove ให้ Interface ที่ดีกว่า (bool return, Exception, Path Object) และรองรับ Directory Removal ด้วย remove_all