C 库 - remove() 函数



C 库的 remove(const char *filename) 函数删除给定的文件名,使其不再可访问。

语法

以下是 C 库 remove() 函数的语法:

remove(const char *filename);

参数

此函数仅接受一个参数:

  • filename: 指向一个字符串的指针,该字符串指定要删除的文件名。文件名可以包含相对路径或绝对路径。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

如果文件成功删除,则函数返回 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
广告