c++ read()函數(shù)處理大文件的方法

c++
小樊
82
2024-09-13 01:31:09
欄目: 編程語言

在C++中,處理大文件時(shí)可以使用read()函數(shù)進(jìn)行分塊讀取

#include<iostream>
#include <fcntl.h>
#include <unistd.h>
#include <cstdint>

const size_t BUFFER_SIZE = 4096; // 定義緩沖區(qū)大小

int main() {
    int fd = open("large_file.txt", O_RDONLY); // 打開大文件
    if (fd == -1) {
        std::cerr << "Error opening file."<< std::endl;
        return 1;
    }

    char buffer[BUFFER_SIZE]; // 創(chuàng)建緩沖區(qū)
    ssize_t bytes_read;

    while (true) {
        bytes_read = read(fd, buffer, BUFFER_SIZE); // 分塊讀取文件
        if (bytes_read == -1) {
            std::cerr << "Error reading file."<< std::endl;
            close(fd);
            return 1;
        }
        if (bytes_read == 0) {
            break; // 文件已讀完
        }

        // 處理讀取到的數(shù)據(jù)(例如,將其輸出到控制臺(tái))
        for (ssize_t i = 0; i< bytes_read; ++i) {
            std::cout<< buffer[i];
        }
    }

    close(fd); // 關(guān)閉文件描述符
    return 0;
}

這個(gè)示例程序首先打開一個(gè)名為large_file.txt的大文件。然后,它使用read()函數(shù)分塊讀取文件內(nèi)容,每次讀取BUFFER_SIZE字節(jié)。在每個(gè)循環(huán)中,程序?qū)⒆x取到的數(shù)據(jù)輸出到控制臺(tái)。當(dāng)文件讀取完畢時(shí),程序?qū)㈥P(guān)閉文件描述符并退出。

注意:在實(shí)際應(yīng)用中,你可能需要根據(jù)具體需求對(duì)讀取到的數(shù)據(jù)進(jìn)行處理,而不僅僅是將其輸出到控制臺(tái)。

0