024. 打开和关闭文件

在C语言中,文件操作是通过标准库中的函数来完成的,主要包括打开文件、读写文件以及关闭文件。这些操作通常使用FILE指针和相关的函数来实现。以下将详细介绍如何在C语言中打开和关闭文件。

1. 打开文件

在C语言中,使用fopen函数来打开文件。fopen函数的原型如下:

FILE *fopen(const char *filename, const char *mode);
  • filename:文件的路径和名称。

  • mode:文件的打开模式,常见的模式包括:

  • "r":以只读方式打开文件。

  • "w":以写入方式打开文件,文件内容会被清空。

  • "a":以追加方式打开文件,写入的内容会追加到文件末尾。

  • "r+":以读写方式打开文件,文件必须存在。

  • "w+":以读写方式打开文件,文件内容会被清空。

  • "a+":以读写方式打开文件,写入的内容会追加到文件末尾。

示例1:打开文件

#include <stdio.h>

int main() {
    FILE *file;

    // 打开文件
    file = fopen("example.txt", "w");
    if (file == NULL) {
        printf("Failed to open the file.\n");
        return 1;
    }

    printf("File opened successfully.\n");

    // 关闭文件
    fclose(file);
    printf("File closed successfully.\n");

    return 0;
}

输出结果

File opened successfully.
File closed successfully.

2. 关闭文件

在完成文件操作后,必须使用fclose函数关闭文件。fclose函数的原型如下:

int fclose(FILE *stream);
  • stream:要关闭的文件指针。

  • 返回值:成功时返回0,失败时返回EOF(通常为-1)。

示例2:关闭文件

#include <stdio.h>

int main() {
    FILE *file;

    // 打开文件
    file = fopen("example.txt", "w");
    if (file == NULL) {
        printf("Failed to open the file.\n");
        return 1;
    }

    printf("File opened successfully.\n");

    // 关闭文件
    if (fclose(file) == 0) {
        printf("File closed successfully.\n");
    } else {
        printf("Failed to close the file.\n");
    }

    return 0;
}

输出结果

File opened successfully.
File closed successfully.

通过上述示例,你可以看到如何在C语言中打开和关闭文件:

  1. 打开文件:使用fopen函数,指定文件名和打开模式。
  2. 关闭文件:使用fclose函数,确保文件指针有效。

视频讲解

BiliBili: 视睿网络-哔哩哔哩视频 (bilibili.com)