c語(yǔ)言close函數(shù)的用法是什么

小億
324
2023-11-20 19:50:36

在C語(yǔ)言中,close函數(shù)用于關(guān)閉一個(gè)打開(kāi)的文件。其原型如下:

int close(int fd);

參數(shù)fd是一個(gè)文件描述符,表示要關(guān)閉的文件。

close函數(shù)將文件描述符fd所指向的打開(kāi)文件關(guān)閉,并釋放相關(guān)的資源。成功關(guān)閉文件時(shí),返回值為0;失敗時(shí)返回值為-1,并設(shè)置errno變量來(lái)指示具體的錯(cuò)誤原因。

示例:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main() {
    int fd = open("file.txt", O_RDONLY);
    if (fd == -1) {
        perror("open");
        exit(1);
    }

    // 使用fd進(jìn)行文件讀取操作...

    if (close(fd) == -1) {
        perror("close");
        exit(1);
    }

    return 0;
}

在上面的示例中,open函數(shù)打開(kāi)了一個(gè)名為file.txt的文件,并返回一個(gè)文件描述符fd。然后,我們可以使用該文件描述符進(jìn)行文件讀取操作。最后,通過(guò)調(diào)用close函數(shù)來(lái)關(guān)閉文件并釋放資源。

0