C++ remove()

C++ 中的 remove() 函数用于删除指定的文件。它定义在 cstdio 头文件中。

示例

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
  char filename[] = "program.cpp";

// remove the file "program.cpp" int result = remove(filename);
cout << result; return 0; } // Output: -1

remove() 语法

remove() 函数的语法是:

remove(const char* filename);

remove() 参数

remove() 函数接受以下参数:

  • filename - 指向 C 字符串的 指针,其中包含要删除的文件的名称及其路径。

注意: C++ string 类的变量不能用作 remove() 的参数。


remove() 的返回值

remove() 函数返回:

  • 如果文件成功删除,则返回零。
  • 如果在删除过程中发生错误,则返回非零值。

remove() 原型

remove() 在 cstdio 头文件中的原型是:

int remove(const char* filename);

使用 remove() 删除已打开的文件

如果被删除的文件已被某个进程打开,remove() 函数的行为是实现定义的。

  • POSIX 系统 - 如果该名称是文件的最后一个链接,但仍有进程打开该文件,则该文件将继续存在,直到最后一个运行的进程关闭该文件。
  • Windows - 如果文件仍被任何进程打开,则不允许删除该文件。

示例:C++ remove()

#include <iostream>
#include <cstdio>

using namespace std;

int main() {
  char filename[] = "C:\\Users\\file.txt";
	
// deletes the file if it exists int result = remove(filename);
// check if file has been deleted successfully if (result != 0) { // print error message cerr << "File deletion failed"; } else { cout << "File deleted successfully"; } return 0; }

输出

File deletion failed
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战