read()
函數用于從文件描述符(通常是套接字、文件等)讀取數據。
#include <unistd.h>ssize_t read(int fd, void *buf, size_t count);
-
fd
:- 是文件描述符,可以是套接字、文件等。
-
buf
:- 是一個指向要讀取數據的緩沖區的指針。
-
count
:- 是要讀取的字節數。
-
返回值:
- 如果成功,返回讀取的字節數(可能為 0,表示已經讀到文件末尾)。
- 如果出錯,返回 -1,并設置
errno
表示錯誤原因。
示例用法:
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>int main() {int fd = open("example.txt", O_RDONLY);if (fd == -1) {perror("open");exit(EXIT_FAILURE);}char buffer[1024];ssize_t bytesRead = read(fd, buffer, sizeof(buffer));if (bytesRead == -1) {perror("read");close(fd);exit(EXIT_FAILURE);}printf("Read %zd bytes: %s\n", bytesRead, buffer);close(fd);return 0;
}
在上述示例中,read()
從文件中讀取數據,并將其存儲在 buffer
緩沖區中。讀取的字節數由 bytesRead
返回。請注意,read()
函數在讀到文件末尾時返回 0。