#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
int fd;
char buffer[1024];
ssize_t bytes_read;
// 打开文件
fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
// 读取文件内容
bytes_read = read(fd, buffer, sizeof(buffer) - 1);
if (bytes_read == -1) {
perror("read");
close(fd);
exit(EXIT_FAILURE);
}
// 确保字符串以null结尾
buffer[bytes_read] = '\0';
// 输出读取的内容
printf("File content: %s\n", buffer);
// 关闭文件描述符
close(fd);
return 0;
}
包含头文件:
#include <unistd.h>:包含了 read 和 close 函数的声明。#include <fcntl.h>:包含了 open 函数的声明。#include <stdio.h>:用于标准输入输出函数,如 printf 和 perror。#include <stdlib.h>:用于 exit 函数。打开文件:
fd = open("example.txt", O_RDONLY);:以只读方式打开文件 example.txt,返回文件描述符 fd。如果打开失败,fd 会是 -1。读取文件内容:
bytes_read = read(fd, buffer, sizeof(buffer) - 1);:从文件描述符 fd 中读取最多 sizeof(buffer) - 1 字节的数据到 buffer 中。read 返回实际读取的字节数,如果读取失败则返回 -1。确保字符串以 null 结尾:
buffer[bytes_read] = '\0';:确保读取的内容是一个以 null 结尾的字符串,避免后续使用时出现未定义行为。输出读取的内容:
printf("File content: %s\n", buffer);:将读取的内容打印到标准输出。关闭文件描述符:
close(fd);:关闭文件描述符 fd,释放资源。错误处理:
perror 打印错误信息,并在发生错误时调用 exit 终止程序。上一篇:linux 设置静态ip
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站