如何在c++中使用read()函數(shù)讀取文件

c++
小樊
82
2024-09-13 01:30:27

在C++中,read()函數(shù)通常與文件描述符一起使用,它是從UNIX系統(tǒng)調(diào)用中繼承的

#include<iostream>
#include <fcntl.h>      // 包含文件控制函數(shù)和宏
#include <unistd.h>     // 包含read()和close()函數(shù)
#include <sys/stat.h>   // 包含文件狀態(tài)相關(guān)的函數(shù)和宏

int main() {
    const char *file_name = "example.txt";  // 要打開的文件名
    int file_descriptor;                    // 文件描述符
    char buffer[1024];                       // 存儲(chǔ)讀取內(nèi)容的緩沖區(qū)
    ssize_t bytes_read;                      // 實(shí)際讀取到的字節(jié)數(shù)

    // 以只讀模式打開文件,返回文件描述符
    file_descriptor = open(file_name, O_RDONLY);
    if (file_descriptor < 0) {
        std::cerr << "Error opening file: "<< file_name<< std::endl;
        return 1;
    }

    // 使用read()函數(shù)讀取文件內(nèi)容
    bytes_read = read(file_descriptor, buffer, sizeof(buffer) - 1);
    if (bytes_read < 0) {
        std::cerr << "Error reading file: "<< file_name<< std::endl;
        close(file_descriptor);
        return 1;
    }

    // 確保字符串以'\0'結(jié)尾
    buffer[bytes_read] = '\0';

    // 輸出讀取到的內(nèi)容
    std::cout << "File content: "<< std::endl<< buffer<< std::endl;

    // 關(guān)閉文件描述符
    close(file_descriptor);

    return 0;
}

這個(gè)示例程序首先打開一個(gè)名為example.txt的文件,然后使用read()函數(shù)將文件內(nèi)容讀取到緩沖區(qū)。接下來,程序?qū)⒆x取到的內(nèi)容輸出到控制臺(tái),并關(guān)閉文件描述符。

注意:這個(gè)示例程序沒有處理可能發(fā)生的錯(cuò)誤,例如文件不存在或無法打開。在實(shí)際應(yīng)用中,你需要添加適當(dāng)?shù)腻e(cuò)誤處理代碼。

0