21xrx.com
2024-09-20 06:30:09 Friday
登录
文章检索 我的文章 写文章
如何在C++程序中正确关闭文件?
2023-07-05 06:34:49 深夜i     --     --
C++ 文件关闭 fclose() RAII 异常处理

在C++程序中,文件是一个重要的操作对象,因此正确地关闭文件是非常重要的。如果不关闭文件,它可能会占用系统资源,导致程序崩溃甚至可能损坏文件。为此,本文将介绍如何在C++程序中正确关闭文件。

1. 使用fclose()函数

在使用fopen()函数打开文件后,文件必须使用fclose()函数关闭。该函数的原型如下:

int fclose(FILE *stream);

该函数接受一个 FILE 类型的参数,代表要关闭的文件。

示例代码:


#include <stdio.h>

int main() {

  FILE *fp = fopen("test.txt", "w");

  if (fp == NULL) {

    perror("Failed to open file.");

    return -1;

  }

  

  fputs("Hello, world!", fp);

  

  if (fclose(fp) == 0) {

    printf("File closed successfully.")

  }

  

  return 0;

}

在上述代码中,使用fopen()打开一个名为“test.txt”的文件,并将字符串“Hello,world!”写入该文件。在完成写入后,使用fclose()函数关闭文件。如果关闭成功,将输出“File closed successfully.”。

2. 自动关闭文件

除了显示地使用fclose()函数关闭文件之外,还可以在程序运行结束时自动关闭文件。这可以通过定义一个类来实现。当创建对象时,它将打开文件。当对象销毁时(例如在程序结束时),该文件将自动关闭。该方法可以防止程序员忘记关闭文件。

示例代码:


#include <fstream>

class AutoCloseFile {

public:

  AutoCloseFile(std::string filename) {

    file = fopen(filename.c_str(), "w");

  }

  

  ~AutoCloseFile() {

    if (file != NULL) {

      fclose(file);

    }    

  }

  

  FILE *getFile()

    return file;

  

  

private:

  FILE *file;

};

int main() {

  AutoCloseFile file("test.txt");

  if (file.getFile() == NULL) {

    perror("Failed to open file.");

    return -1;

  }

  

  fputs("Hello, world!", file.getFile());

  

  return 0;

}

在上述代码中,AutoCloseFile类定义了一个文件指针file,并在构造函数中使用fopen()打开一个名为“test.txt”的文件。在析构函数中,它使用fclose()函数关闭文件。在主函数中,创建一个AutoCloseFile对象,将字符串“Hello,world!”写入该文件。

通过使用上述两种方法之一,我们可以正确地关闭文件,使程序更加健壮,避免了可能出现的问题。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复