c++中read()函數(shù)的基本用法是什么

c++
小樊
81
2024-09-13 01:29:08

在C++中,read()函數(shù)通常與文件操作相關(guān),并用于從文件描述符(例如打開(kāi)的文件)讀取數(shù)據(jù)

#include <unistd.h>

ssize_t read(int fd, void *buf, size_t count);

參數(shù)說(shuō)明:

  • fd: 文件描述符,表示要讀取的文件。
  • buf: 指向存儲(chǔ)讀取數(shù)據(jù)的緩沖區(qū)的指針。
  • count: 要讀取的字節(jié)數(shù)。

返回值:

  • 成功時(shí),返回實(shí)際讀取的字節(jié)數(shù)。如果已到達(dá)文件末尾,則返回0。
  • 失敗時(shí),返回-1,并設(shè)置errno以指示錯(cuò)誤。

以下是一個(gè)簡(jiǎn)單的示例,展示了如何使用read()函數(shù)從文件中讀取數(shù)據(jù):

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

int main() {
    const char *file_path = "example.txt";
    int fd = open(file_path, O_RDONLY); // 打開(kāi)文件

    if (fd == -1) {
        std::cerr << "Error opening file: "<< file_path<< std::endl;
        return 1;
    }

    const size_t buffer_size = 1024;
    char buffer[buffer_size];

    ssize_t bytes_read = read(fd, buffer, buffer_size); // 讀取文件內(nèi)容

    if (bytes_read == -1) {
        std::cerr << "Error reading from file: "<< file_path<< std::endl;
        close(fd); // 關(guān)閉文件
        return 1;
    }

    if (bytes_read > 0) {
        std::cout << "Read "<< bytes_read << " bytes from file: "<< std::endl;
        std::cout.write(buffer, bytes_read);
    } else {
        std::cout << "Reached end of file."<< std::endl;
    }

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

這個(gè)示例首先打開(kāi)一個(gè)名為example.txt的文件,然后使用read()函數(shù)讀取最多1024字節(jié)的數(shù)據(jù)。接著,將讀取到的數(shù)據(jù)輸出到控制臺(tái),并關(guān)閉文件。

0