面试题答案
一键面试#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
int main() {
// 假设fd已经被正确初始化
int fd;
char buf[100];
// 从文件描述符fd对应的文件中读取100字节的数据
ssize_t bytes_read = read(fd, buf, 100);
// 检查读取操作是否成功
if (bytes_read == -1) {
perror("read error");
exit(EXIT_FAILURE);
} else if (bytes_read < 100) {
printf("Read fewer bytes than expected. Read %zd bytes.\n", bytes_read);
} else {
printf("Successfully read 100 bytes.\n");
}
return 0;
}
步骤解释:
- 定义变量:
fd
:假设已经被正确初始化的文件描述符。buf[100]
:定义一个字符数组buf
,用于存储从文件中读取的100字节数据。
- 读取数据:
ssize_t bytes_read = read(fd, buf, 100);
:调用read
函数从文件描述符fd
对应的文件中读取100字节的数据到buf
缓冲区中。read
函数返回实际读取的字节数,如果读取失败返回 -1。
- 检查读取结果:
if (bytes_read == -1)
:如果read
函数返回 -1,表示读取操作失败,使用perror
函数打印错误信息,并调用exit
函数以失败状态退出程序。else if (bytes_read < 100)
:如果实际读取的字节数小于100,表示没有读取到预期的100字节,打印提示信息说明实际读取的字节数。else
:如果实际读取的字节数等于100,表示成功读取100字节,打印成功信息。