在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ù)。返回值:
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)閉文件。