Linux 系统 IO - 文件读写
系统调用实现文件拷贝,涉及 open, close, read, write.
/*********************************************************
Copyright © 2022 Shengkai Liu. All rights reserved.
FileName: copy.c
Author: Shengkai Liu
Date: 2022-05-30
***********************************************************/
#include <fcntl.h> // open, O_RDONLY, O_WRONLY, O_CREAT
#include <stdio.h> // perror
#include <unistd.h> // close, read, write
#define SRC_FILE_NAME "src.txt"
#define DST_FILE_NAME "dst.txt"
int main()
{
// open (read)
int src_fd = open(SRC_FILE_NAME, O_RDONLY);
if (src_fd == -1) perror("open");
// open (create and write)
int dst_fd = open(DST_FILE_NAME, O_WRONLY | O_CREAT, 0664);
if (dst_fd == -1) perror("open");
char buf[1024] = {0};
int len = 0;
// copy from src to dst
while (len = read(src_fd, buf, sizeof(buf)))
{
write(dst_fd, buf, len);
}
// close
close(src_fd);
close(dst_fd);
return 0;
}