- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - remove() 函式
C 庫的 remove(const char *filename) 函式刪除給定的檔名,使其不再可訪問。
語法
以下是 C 庫 remove() 函式的語法:
remove(const char *filename);
引數
此函式僅接受一個引數:
- filename: 指向一個字串的指標,該字串指定要刪除的檔名。檔名可以包含相對路徑或絕對路徑。
返回值
如果檔案成功刪除,則函式返回 0。如果發生錯誤,則返回非零值。如果發生錯誤,則 errno 會設定為指示特定的錯誤程式碼,該程式碼可用於確定失敗的原因。
常見錯誤程式碼
- ENOENT: 指定的檔名不存在。
- EACCES: 刪除檔案許可權被拒絕。
- EPERM: 操作不被允許,例如嘗試刪除目錄。
示例 1:成功刪除檔案
此示例建立一個名為 example1.txt 的檔案,然後使用 remove 函式成功刪除它。
以下是 C 庫 remove() 函式的示例。
#include <stdio.h>
int main() {
const char *filename = "example1.txt";
// Create a file to be deleted
FILE *file = fopen(filename, "w");
if (file) {
fprintf(file, "This is a test file.\n");
fclose(file);
}
// Attempt to remove the file
if (remove(filename) == 0) {
printf("File %s successfully deleted.\n", filename);
} else {
perror("Error deleting file");
}
return 0;
}
輸出
以上程式碼產生以下結果:
File example1.txt successfully deleted.
示例 2:在沒有許可權的情況下刪除檔案
此示例模擬嘗試在沒有必要許可權的情況下刪除檔案,這將導致許可權被拒絕錯誤。
#include <stdio.h>
#include <errno.h>
int main() {
const char *filename = "protectedfile.txt";
// Create a file to be deleted
FILE *file = fopen(filename, "w");
if (file) {
fprintf(file, "This is a test file with restricted permissions.\n");
fclose(file);
}
// Simulate restricted permissions (actual permission setting code omitted for simplicity)
// Attempt to remove the file
if (remove(filename) == 0) {
printf("File %s successfully deleted.\n", filename);
} else {
perror("Error deleting file");
}
return 0;
}
輸出
執行以上程式碼後,我們得到以下結果:
Error deleting file: Permission denied
廣告