qfedu-linux-advanced-level/day2/homework/h2.c

34 lines
929 B
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 编写一个程序使用open系统调用打开一个已存在的文件并使用read系统调用从文件中读取内容并将读取到的内容打印到控制台上。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
// 打开文件
int fd = open("a.txt", O_RDONLY);
if (fd < 0)
{
perror("open"); // 打开文件失败时打印错误信息
return -1;
}
char buf[1024] = "";
ssize_t len = read(fd, buf, sizeof(buf)); // 从文件中读取内容
if (len != -1)
{
// printf("%s\n", buf); // 将读取到的内容打印到控制台上
write(STDOUT_FILENO, buf, len); // 将读取到的内容写入标准输出
}
if (close(fd) < 0)
{
perror("close"); // 关闭文件失败时打印错误信息
return -1;
}
return 0;
}